Merge pull request #9775 from davidmann4/integration-batch-9

Integration batch: 21 PRs on main
This commit is contained in:
aiongg authored and GitHub committed 2026-10-27 16:53:43 -04:00
commit 52f338e2df
211 files changed
+10223 -878

No files matched your search

+2 -1
View File
@@ -29,11 +29,12 @@ next to them.
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg` (113 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/sampler.svg` | Color Sampler tool glyph: a target reticle marking a sampled pixel | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/font-similar.svg`, `assets/icons/font-variable.svg` | Font menu filter glyphs: two waves (Show Similar Fonts) and a T over a slider (Show Variable Fonts), drawn on the 24 px icon grid | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/convert-point.svg` | Convert Point tool glyph: an angle with a square anchor on its apex, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/artboard.svg` | Artboard tool glyph: a board with a tick at each end of its edges | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/perspective-crop.svg` | Perspective Crop tool glyph: a crop frame in perspective with its grid and crop-mark ticks | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
Generated
+2
View File
@@ -5047,6 +5047,7 @@ dependencies = [
"photocraft-engine",
"photocraft-format",
"photocraft-io",
"photocraft-raster",
"photocraft-raw",
"rmcp",
"rustix 1.1.5",
@@ -5247,6 +5248,7 @@ dependencies = [
"craft-docpath",
"crc32fast",
"flate2",
"miniz_oxide 0.9.1",
"photocraft-affinity",
"photocraft-algo",
"photocraft-cms",
+1 -1
View File
@@ -51,7 +51,7 @@ clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
arc-swap = "1"
bytemuck = { version = "1", features = ["derive"] }
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
image = { version = "0.25", default-features = false }
# Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg.
zune-core = "0.5"
+26 -9
View File
@@ -18,10 +18,10 @@ mod recovery_tests;
/// Photoshop brushes (.abr), gradients (.grd), layer styles (.asl), swatches (.aco, .act, .ase) and keyboard shortcut sets
/// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts.
const OPEN_EXTS: &[&str] = &[
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico",
"qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3", "iff", "lbm",
"ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz", "aco", "act",
"ase", "kys", "af", "afdesign", "afphoto", "afpub",
"pcraft", "pdn", "ora", "xcf", "xcfgz", "gz", "kra", "krz", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "dib", "tga",
"ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pnm", "pam", "pfm", "pcx", "dds", "xpm", "fits", "fit", "fts", "dpx", "cin", "dcm", "dicom", "dc3",
"iff", "lbm", "ilbm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "asl", "svg", "svgz",
"aco", "act", "ase", "kys", "af", "afdesign", "afphoto", "afpub",
];
const SVG_EXTS: &[&str] = &["svg", "svgz"];
@@ -54,14 +54,14 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[
("TIFF", &["tif", "tiff"]),
("WebP", &["webp"]),
("GIF", &["gif"]),
("BMP", &["bmp"]),
("BMP", &["bmp", "dib"]),
("Targa", &["tga"]),
("ICO", &["ico"]),
("QOI", &["qoi"]),
("PCX", &["pcx"]),
("DDS", &["dds"]),
("XPM", &["xpm"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pam", "pfm"]),
("Portable Bitmap", &["pbm", "pgm", "ppm", "pnm", "pam", "pfm"]),
("OpenEXR", &["exr"]),
("Radiance HDR", &["hdr"]),
("FITS", &["fits", "fit", "fts"]),
@@ -91,15 +91,19 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[
("PhotoCraft", &["pcraft"]),
("OpenRaster", &["ora"]),
("PNG", &["png"]),
("JPEG", &["jpg"]),
("JPEG", &["jpg", "jpeg"]),
("WebP", &["webp"]),
("TIFF", &["tif"]),
("TIFF", &["tif", "tiff"]),
("Targa", &["tga"]),
// Also in Photoshop's Save As list; ICO is PhotoCraft's own (#4357): up to 256×256, with alpha.
("BMP", &["bmp"]),
("BMP", &["bmp", "dib"]),
("GIF", &["gif"]),
("ICO", &["ico"]),
("OpenEXR", &["exr"]),
// The encoder picks P5, P6, P7 or PFM from the image, not from the name, so only the neutral
// .pnm is offered: a .pbm or .pgm name would hold pixmap data (CodeRabbit on #9775).
("Netpbm", &["pnm"]),
("Radiance HDR", &["hdr"]),
("FITS", &["fits", "fit"]),
("DPX", &["dpx"]),
// Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327).
@@ -112,9 +116,21 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[
/// never swaps their extension for a document format's.
const OTHER_SAVE_FILTERS: &[(&str, &[&str])] = &[("Color Swatches", &["aco"]), ("Color Table", &["act"]), ("Swatch Exchange", &["ase"])];
/// `suggested` with a Netpbm subtype's extension (an opened .pgm) as the neutral .pnm, the name
/// every save dialog starts from: the encoder picks P5, P6, P7 or PFM from the image, so the old
/// suffix could name other data, and macOS and rfd keep the suggested name as it is.
fn netpbm_as_pnm(suggested: &str) -> String {
let path = Path::new(suggested);
let subtype = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).is_some_and(|e| ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&e.as_str()));
if subtype { path.with_extension("pnm").to_string_lossy().into_owned() } else { suggested.to_string() }
}
/// Lists the save dialog's file types with the `suggested` type first (added if unlisted), so the dialog keeps that extension instead of .psd.
fn save_filters(suggested: &str) -> Vec<(String, Vec<String>)> {
let ext = Path::new(suggested).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
// A Netpbm subtype's name (an opened .pgm) starts on the Netpbm type as .pnm: the encoder picks
// the subtype from the image, so the old name could describe other data (CodeRabbit on #9775).
let ext = if ["pbm", "pgm", "ppm", "pam", "pfm"].contains(&ext.as_str()) { "pnm".to_string() } else { ext };
if let Some((name, exts)) = OTHER_SAVE_FILTERS.iter().find(|(_, exts)| exts.contains(&ext.as_str())) {
return vec![(name.to_string(), exts.iter().map(|e| e.to_string()).collect())];
}
@@ -216,6 +232,7 @@ fn show_file_dialog(request: FileDialogRequest, parent: Option<&eframe::Frame>,
Box::pin(async move { picked.await.map(|folder| answer_one(folder.path(), true, FileDialogAnswer::FolderTo)) })
}
FileDialogRequest::Save { suggested } => {
let suggested = netpbm_as_pnm(&suggested);
let filters = save_filters(&suggested);
let name = dialog_file_name(&suggested, cfg!(windows));
let dir = Path::new(&suggested).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf);
+30 -1
View File
@@ -294,9 +294,33 @@ fn save_as_offers_only_writable_formats_including_ico() {
assert!(format.caps().write, "{name}: .{ext} can't be written");
}
}
for ext in ["ico", "gif", "bmp", "dds"] {
for ext in ["ico", "gif", "bmp", "dds", "pnm", "hdr", "dib", "jpeg", "tiff"] {
assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered");
}
// The codec writes P5/P6/P7/PF from the image, never from the name, so Netpbm offers only the
// neutral .pnm (#3609; CodeRabbit on #9775): a .pbm, .pgm or .pfm name would hold other data.
let netpbm = save_filters("Untitled").into_iter().find(|(name, _)| name == "Netpbm").map(|(_, exts)| exts);
assert_eq!(netpbm, Some(vec!["pnm".to_string()]));
// The suggested name itself becomes .pnm, as macOS and rfd keep it (CodeRabbit on #9775).
assert_eq!(netpbm_as_pnm("scans/image.pgm"), Path::new("scans/image.pnm").to_string_lossy());
assert_eq!(netpbm_as_pnm("image.PFM"), "image.pnm");
assert_eq!(netpbm_as_pnm("image.png"), "image.png");
assert_eq!(netpbm_as_pnm("Untitled-1"), "Untitled-1");
// Also when Save As starts from a subtype's name: no filter offers that subtype again.
for name in ["image.pbm", "image.pgm", "image.ppm", "image.pam", "image.pfm"] {
let filters = save_filters(name);
assert_eq!(filters[0], ("Netpbm".to_string(), vec!["pnm".to_string()]), "{name}");
let subtype = name.rsplit('.').next().unwrap_or_default();
assert!(!filters.iter().any(|(_, exts)| exts.iter().any(|e| e == subtype)), "{name}: .{subtype} is offered");
}
// File › Open lists every file Save As writes, also in that format's own type (PDF is written
// but not read yet).
for (name, exts) in SAVE_FILTERS {
for ext in exts.iter().filter(|e| **e != "pdf") {
assert!(OPEN_EXTS.contains(ext), "{name}: Open's All Formats lacks .{ext}");
assert!(OPEN_FILTERS.iter().any(|(_, open)| open.contains(ext)), "{name}: no Open type lists .{ext}");
}
}
assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type");
// What Save As writes there: an icon up to 256×256, and a clear error past that.
let doc = |side: u32| {
@@ -307,6 +331,11 @@ fn save_as_offers_only_writable_formats_including_ico() {
let opts = export_options(&photocraft_ui_egui::ExportSettings::default());
let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap();
assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header");
// And what the Netpbm and Radiance rows write.
let pnm = photocraft_io::export(&doc(4), "x.pnm", &opts).unwrap();
assert_eq!(pnm.bytes[..2], *b"P6", "an RGB document saves as a binary pixmap");
let hdr = photocraft_io::export(&doc(4), "x.hdr", &opts).unwrap();
assert!(hdr.bytes.starts_with(b"#?RADIANCE"), "a Radiance header");
let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string();
assert!(err.contains("256"), "{err}");
}
+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 9.5c2.7-2 5.3-2 8 0s5.3 2 8 0" />
<path d="M4 15.5c2.7-2 5.3-2 8 0s5.3 2 8 0" />
</svg>

After

Width:  |  Height:  |  Size: 305 B

+16
View File
@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 4h10M8 4v10" />
<path d="M14 8h7M17.5 8v6" />
<path d="M3 19h18" />
<circle cx="9" cy="19" r="2" fill="currentColor" />
</svg>

After

Width:  |  Height:  |  Size: 348 B

+1 -1
View File
@@ -332,7 +332,7 @@ fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
}
fn inflate(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
read_bounded(flate2::read::ZlibDecoder::new(data), size)
read_bounded(flate2::bufread::ZlibDecoder::new(data), size)
}
fn unzstd(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
+1
View File
@@ -11,6 +11,7 @@ workspace = true
[dependencies]
photocraft-doc = { workspace = true }
photocraft-raster = { workspace = true }
photocraft-compose = { workspace = true }
photocraft-codecs = { workspace = true }
photocraft-io = { workspace = true }
+16 -2
View File
@@ -33,9 +33,23 @@ pub fn open(path: &Path) -> Result<Opened, AutomationError> {
let document = photocraft_format::load_path(path)?;
return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false });
}
let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
open_bytes(&name, &bytes)
// A PSD/PSB is parsed from the open file (channel data read as it is decoded), so a CLI
// convert or info of a 2 GB file does not hold the file in memory next to the document.
#[cfg(any(unix, windows))]
{
let r =
photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e {
photocraft_io::IoError::Read(msg) => AutomationError::Io(msg),
e => e.into(),
})?;
Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only })
}
#[cfg(not(any(unix, windows)))]
{
let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
open_bytes(&name, &bytes)
}
}
/// Previews for a `.pcraft` bundle.
+2 -1
View File
@@ -187,7 +187,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s
// `read_to_end`, whose doubling reserves past `expected`. Once `expected` bytes are
// in, a one-byte read checks that the stream ends there.
let malformed = || err(format!("{what}: zlib data is malformed"));
let mut zlib = flate2::read::ZlibDecoder::new(packed);
let mut zlib = flate2::bufread::ZlibDecoder::new(packed);
let mut out = Vec::new();
let mut filled = 0;
while filled < expected {
@@ -756,6 +756,7 @@ mod tests {
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
z.write_all(&p).expect("write to a Vec");
let zips = z.finish().expect("finish a Vec");
assert!(decompress(Compression::ZIP1, &zips[..zips.len() - 1], n, "the table").is_err());
// RLE: the first byte as a literal, then runs of up to 128 copies of the next.
let mut rle = vec![0xFF, p[0]];
for run in p[1..].chunks(128) {
+15 -1
View File
@@ -39,16 +39,30 @@ pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result<MetaData, Codec
let meta = MetaData::read_from_buffered(Cursor::new(bytes), false).map_err(err)?;
// Flat decoding reads every part at once, so the parts' sizes are also capped together.
let mut total: u64 = 0;
// DWAA/DWAB parts are counted apart: they go past 2^16:1 (a flat 8192x4320 frame with 12
// alpha-scheme mattes is about 30 KB, over 75000:1).
let mut dwa: u64 = 0;
for header in meta.headers.iter() {
let size = header.layer_size;
let (w, h) = (u32::try_from(size.0).unwrap_or(u32::MAX), u32::try_from(size.1).unwrap_or(u32::MAX));
let bpp = header.channels.list.len().max(1) as u64 * 4;
limits.check_bytes(w, h, bpp)?;
total = total.saturating_add(u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp));
let bytes = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp);
total = total.saturating_add(bytes);
if matches!(header.compression, Compression::DWAA(_) | Compression::DWAB(_)) {
dwa = dwa.saturating_add(bytes);
}
}
if total > limits.max_alloc {
return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc)));
}
// The `exr` crate allocates a flat part's samples before reading its chunks, so the file
// must be able to hold them (#8597). The other compressions stay far below 2^16:1 even
// against this f32 budget. DWA's run-length channels are zlib-packed on top and reach about
// 132000:1, so DWA parts get 2^18:1. Deep parts size their samples from the file's own counts.
if !meta.requirements.has_deep_data {
Limits::check_plausible(total.saturating_sub(dwa).saturating_add(dwa / 4), bytes.len(), 1 << 16)?;
}
Ok(meta)
}
+74 -13
View File
@@ -150,8 +150,13 @@ fn data_end(b: &[u8]) -> (DataEnd, u64) {
loop {
let Some(&byte) = b.get(i) else { return cut(scan_data, scanned) };
if byte != 0xFF {
// Not where a marker should be: too odd to judge.
return (DataEnd::Complete, scanned);
// Not where a marker should be: skip to the next one, as a lenient decoder does, so
// segments after the stray bytes (padding among them) are still recognised. Stray
// bytes are not scan data, so they never count (junk would buy budget as padding
// did); with no marker left, the image data ends here.
let Some(p) = b.get(i..).and_then(|r| r.iter().position(|&v| v == 0xFF)) else { return cut(scan_data, scanned) };
i += p;
continue;
}
let Some(&code) = b.get(i + 1) else { return cut(scan_data, scanned) };
match code {
@@ -232,9 +237,10 @@ fn decode_craft_jpeg(bytes: &[u8], limits: &Limits, adobe_transform: Option<u8>)
Ok((img, d.damaged))
}
/// Most pixels one byte of truncated scan data may account for. Even a flat image costs a few
/// bits per 8×8 block, and truncated photographs are far above this.
const MAX_TRUNCATED_PIXELS_PER_BYTE: u64 = 2048;
/// Most pixels one byte of a JPEG may account for. Every 8×8 block of a frame needs at least a
/// one-bit DC code (512 pixels a byte for a flat image under ideal Huffman tables), and real files,
/// truncated or not, are far above this.
const MAX_PIXELS_PER_BYTE: u64 = 2048;
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
let (end, scan_bytes) = data_end(bytes);
@@ -252,7 +258,9 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
}
if let Some((w, h, _)) = meta.frame
&& end == DataEnd::Truncated
&& u64::from(w) * u64::from(h) / MAX_TRUNCATED_PIXELS_PER_BYTE > scan_bytes
// Only truncated scans: arithmetic coding (SOF9–SOF11) can spend well under a bit on
// a flat block, so a complete scan may be shorter than this bound.
&& u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > scan_bytes
{
return Err(err("the truncated scan is too short for the frame it declares"));
}
@@ -277,12 +285,14 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
_ => (ColorSpace::RGB, ChannelLayout::Rgb),
};
limits.check(w, h, layout, SampleType::U8)?;
// The backend fills whatever the scan no longer describes, so a short scan under a large
// frame is a gigabyte of synthesized output from a few kilobytes of file. The budget is
// measured on the scan data itself: APP padding can inflate `bytes.len()` arbitrarily
// without describing one more pixel.
if end == DataEnd::Truncated && u64::from(w) * u64::from(h) / MAX_TRUNCATED_PIXELS_PER_BYTE > scan_bytes {
return Err(err("the truncated scan is too short for the frame it declares"));
// The backend fills whatever the scan no longer describes, and allocates the whole output
// once a scan holds a byte, so a short scan under a large frame is a gigabyte of synthesized
// output from a few kilobytes of file (#8597), truncated or not. The budget is the scan data
// itself, not `bytes.len()`, which APP padding can inflate without describing one more pixel;
// where the walk stops early on an odd layout, what it couldn't read counts as scan data.
if u64::from(w) * u64::from(h) / MAX_PIXELS_PER_BYTE > scan_bytes {
let what = if end == DataEnd::Truncated { "the truncated scan" } else { "the scan data" };
return Err(err(format!("{what} is too short for the frame it declares")));
}
dec.set_options(dec.options().jpeg_set_out_colorspace(out_cs));
let mut px = dec.decode().map_err(err)?;
@@ -552,7 +562,7 @@ mod tests {
assert_eq!(data_end(&padded).0, DataEnd::Truncated);
// Well above the frame's pixels / budget, yet far above the scan data: the old
// file-length bound admitted this frame.
assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_TRUNCATED_PIXELS_PER_BYTE) as usize, "padding too small");
assert!(padded.len() > (u64::from(20_000u32) * u64::from(20_000u32) / MAX_PIXELS_PER_BYTE) as usize, "padding too small");
assert!(crate::decode_as(Format::Jpeg, &padded).is_ok());
let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap();
let mut huge = padded.clone();
@@ -561,6 +571,57 @@ mod tests {
assert!(e.to_string().contains("too short"), "{e}");
}
/// A complete file is measured on its scan data too: padding can't admit an oversized frame.
/// The same padded file at its real size decodes, and so does an odd layout whose unread tail
/// counts as scan data.
#[test]
fn app_padding_cannot_admit_an_oversized_complete_frame() {
let img = Image::from_raw(16, 16, ChannelLayout::Rgb, SampleType::U8, vec![128; 16 * 16 * 3]).unwrap();
let full = crate::encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
let fill = [b'p'; 65533];
let mut padded = full[..2].to_vec();
for _ in 0..4 {
padded.extend_from_slice(&[0xFF, 0xFE]);
padded.extend_from_slice(&0xFFFFu16.to_be_bytes());
padded.extend_from_slice(&fill);
}
padded.extend_from_slice(&full[2..]);
let (end, scanned) = data_end(&padded);
assert_eq!(end, DataEnd::Complete);
assert!(scanned < 1024, "the padding isn't scan data: {scanned}");
assert!(padded.len() as u64 > u64::from(20_000u32) * 20_000 / MAX_PIXELS_PER_BYTE, "padding too small");
assert!(crate::decode_as(Format::Jpeg, &padded).is_ok());
let sof = padded.windows(2).position(|w| w == [0xFF, 0xC0] || w == [0xFF, 0xC2]).unwrap();
let mut huge = padded.clone();
huge[sof + 5..sof + 9].copy_from_slice(&[0x4E, 0x20, 0x4E, 0x20]);
let e = crate::decode_as(Format::Jpeg, &huge).unwrap_err();
assert!(e.to_string().contains("too short"), "{e}");
// A stray byte where a marker should be, before the padding: the walk skips it and still
// recognises the padding, so an oversized frame is refused there too.
let mut odd = huge.clone();
odd.insert(2, 0x00);
let (end, scanned) = data_end(&odd);
assert_eq!(end, DataEnd::Complete);
assert!(scanned < 1024, "the padding after a stray byte isn't scan data: {scanned}");
let e = crate::decode_as(Format::Jpeg, &odd).unwrap_err();
assert!(e.to_string().contains("too short"), "{e}");
// Stray bytes never count: 256 KiB of junk where a marker should be (the decoder skips
// it), then the oversized frame's segments, is refused. (Bytes after a scan starts are
// entropy-coded data, any value, and count as such.)
let mut junk = huge[..2].to_vec();
junk.extend(std::iter::repeat_n(0x00u8, 4 * 65536));
junk.extend_from_slice(&huge[2..]);
let (end, scanned) = data_end(&junk);
assert_eq!(end, DataEnd::Complete);
assert!(scanned < 1024, "junk isn't scan data: {scanned}");
let e = crate::decode_as(Format::Jpeg, &junk).unwrap_err();
assert!(e.to_string().contains("too short"), "{e}");
// Junk with no marker after it: no image data at all.
let mut tail = vec![0xFF, 0xD8];
tail.extend(std::iter::repeat_n(0x00u8, 4096));
assert_eq!(data_end(&tail), (DataEnd::Empty, 0));
}
/// CMYK JPEG output must omit JFIF while retaining Adobe's CMYK marker.
#[test]
fn cmyk_jpeg_omits_jfif_but_keeps_adobe_cmyk_marker() {
+9 -4
View File
@@ -419,7 +419,7 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression
}
let lvl = match level {
PngCompression::None => flate2::Compression::none(),
PngCompression::Fast => flate2::Compression::fast(),
PngCompression::Fast => FAST,
PngCompression::Default => flate2::Compression::default(),
PngCompression::Best => flate2::Compression::best(),
};
@@ -428,6 +428,11 @@ fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression
z.finish().map_err(|e| CodecError::encode(F, e))
}
/// The deflate level of [`PngCompression::Fast`]: zlib-rs level 1 writes static Huffman blocks
/// only (20-30% bigger on filtered photos); level 3 is the lowest that is never bigger than
/// miniz's level 1 was, at about twice its time.
const FAST: flate2::Compression = flate2::Compression::new(3);
/// Images at least this large (bytes) are filtered and deflated on all cores.
const PARALLEL_MIN_BYTES: usize = 4 << 20;
@@ -456,7 +461,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio
let band_rows = (BAND_BYTES / stride.saturating_add(1)).max(1);
let bands: Vec<(usize, usize)> = (0..h).step_by(band_rows).map(|y| (y, (y + band_rows).min(h))).collect();
let lvl = match level {
PngCompression::Fast => flate2::Compression::fast(),
PngCompression::Fast => FAST,
PngCompression::Best => flate2::Compression::best(),
_ => flate2::Compression::default(),
};
@@ -494,7 +499,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio
let mut out = Vec::with_capacity(parts.iter().map(|p| p.1.len()).sum::<usize>() + 6);
// zlib header: deflate, 32 K window; FLEVEL only advertises the effort.
out.extend_from_slice(match level {
PngCompression::Fast => &[0x78, 0x01],
PngCompression::Fast => &[0x78, 0x5E],
PngCompression::Best => &[0x78, 0xDA],
_ => &[0x78, 0x9C],
});
@@ -509,7 +514,7 @@ fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompressio
/// Raw deflate of one band: ends on a sync flush, or finishes the stream for the `last` band.
/// The output buffer is sized past deflate's worst case so that one call takes the whole band
/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's Rust
/// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust
/// backend) can return before compressing the last lookahead bytes, and the next call only
/// drains the pending output, so a resumed flush silently drops data. `None` (the caller then
/// uses the serial encoder) if the single call did not finish.
+54 -3
View File
@@ -93,7 +93,25 @@ fn open<'a>(f: Format, bytes: &'a [u8], limits: &Limits) -> Result<impl ImageDec
reader.limits(il);
let dec = reader.into_decoder().map_err(|e| map_err(f, e))?;
let (w, h) = dec.dimensions();
limits.check_bytes(w, h, dec.color_type().bytes_per_pixel() as u64)?;
let bpp = dec.color_type().bytes_per_pixel() as u64;
limits.check_bytes(w, h, bpp)?;
// `DynamicImage::from_decoder` allocates the whole image before reading a pixel, so a
// header-only file must not be able to ask for gigabytes (#8597). GIF's LZW tops out near
// 11000:1 of RGBA output and TGA's and QOI's runs far below; AVIF has already decoded by now.
// Radiance HDR's old-style RLE repeat markers multiply their counts by 256 each in a row, and
// a BMP's RLE escapes (end of line, end of bitmap, delta) leave pixels unwritten, so no ratio
// bounds a valid file: only the allocation limit above applies to them.
let declared = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bpp);
// A GIF's first frame is what the file must hold: the logical screen around it needs no
// data, so up to 256 MiB of screen (8192x8192) is free and only the rest must be backed.
let frame = if f == Format::Gif { gif_first_frame(bytes) } else { None };
let declared = match frame {
Some((fw, fh)) => u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(bpp).max(declared.saturating_sub(1 << 28)),
_ => declared,
};
if !matches!(f, Format::Avif | Format::Hdr) && !(f == Format::Bmp && bmp_is_rle(bytes)) {
Limits::check_plausible(declared, bytes.len(), 1 << 14)?;
}
Ok(dec)
}
@@ -123,9 +141,36 @@ pub(crate) fn probe(f: Format, bytes: &[u8], limits: &Limits) -> Result<(u32, u3
Ok((w, h, dec.exif_metadata().ok().flatten()))
}
/// Whether a BMP's `biCompression` is RLE8 or RLE4 (only headers of 40 bytes or more have one).
fn bmp_is_rle(b: &[u8]) -> bool {
let u32_at = |at: usize| b.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
u32_at(14).is_some_and(|n| n >= 40) && matches!(u32_at(30), Some(1 | 2))
}
/// The width and height of a GIF's first image descriptor, if the blocks reach one.
fn gif_first_frame(b: &[u8]) -> Option<(u32, u32)> {
let mut at = None;
gif_walk(b, |i| {
at = Some(i);
false
});
let u16_at = |at: usize| b.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
// Descriptor: separator, left, top, width, height (little-endian u16s), packed fields.
let i = at?;
Some((u32::from(u16_at(i + 5)?), u32::from(u16_at(i + 7)?)))
}
/// Counts a GIF's frames (image descriptors) by walking its blocks, without decompressing any.
/// The total is unknown when the blocks end before the trailer or break off.
fn gif_more_frames(b: &[u8]) -> Option<DecodeWarning> {
let (frames, total) = gif_walk(b, |_| true);
(frames > 1).then_some(DecodeWarning::MoreFrames { total })
}
/// Walks a GIF's blocks without decompressing any, handing `frame` the offset of each image
/// descriptor until it returns false. Gives the descriptors seen, and the frame count if the
/// blocks reached the trailer.
fn gif_walk(b: &[u8], mut frame: impl FnMut(usize) -> bool) -> (u32, Option<u32>) {
// Size of the colour table a packed-fields byte announces.
let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
// Skips the data sub-blocks starting at `i` (each length-prefixed, ended by a zero length).
@@ -139,7 +184,10 @@ fn gif_more_frames(b: &[u8]) -> Option<DecodeWarning> {
}
};
// Header (6 bytes), logical screen descriptor (7) and the global colour table.
let mut i = 13 + table(*b.get(10)?);
let Some(&flags) = b.get(10) else {
return (0, None);
};
let mut i = 13 + table(flags);
let mut frames = 0u32;
let total = loop {
let next = match b.get(i) {
@@ -147,6 +195,9 @@ fn gif_more_frames(b: &[u8]) -> Option<DecodeWarning> {
Some(0x21) => skip(i + 2),
Some(0x2C) => {
frames = frames.saturating_add(1);
if !frame(i) {
break None;
}
// Descriptor (10 bytes, packed fields last), local colour table, LZW code size.
b.get(i + 9).and_then(|&flags| skip(i + 11 + table(flags)))
}
@@ -157,7 +208,7 @@ fn gif_more_frames(b: &[u8]) -> Option<DecodeWarning> {
None => break None,
}
};
(frames > 1).then_some(DecodeWarning::MoreFrames { total })
(frames, total)
}
pub(crate) fn from_dynamic(f: Format, d: DynamicImage) -> Result<Image, CodecError> {
+182
View File
@@ -398,6 +398,12 @@ fn pnm_header_alone_reserves_nothing_without_limits() {
}
}
#[test]
fn hdr_header_sizes_that_overflow_u64_are_errors_without_limits() {
let b = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 2147483648 +X 2147483648\n";
assert!(decode_with(b, &opts(Limits::none())).is_err());
}
#[test]
fn pnm_header_sizes_that_overflow_usize_are_errors_without_limits() {
let m = u32::MAX;
@@ -456,3 +462,179 @@ fn limits_check_api() {
assert!(l.check(10, 10, ChannelLayout::Rgba, SampleType::U8).is_err());
assert!(l.check(10, 10, ChannelLayout::Rgb, SampleType::U8).is_ok());
}
/// #8597: a small file whose header declares about 3 GB, inside the default limits, is refused
/// by the size-against-file check before the decoder allocates its output.
fn refused_as_implausible(f: Format, b: &[u8]) {
match decode(b) {
Err(CodecError::LimitExceeded(m)) => assert!(m.contains("cannot hold"), "{f:?}: {m}"),
other => panic!("{f:?}: expected an implausible-size refusal, got {:?}", other.map(|i| (i.width(), i.height()))),
}
}
fn find(b: &[u8], needle: &[u8]) -> usize {
b.windows(needle.len()).position(|w| w == needle).unwrap()
}
#[test]
fn jpeg_header_declaring_gigabytes_needs_a_plausible_file_size() {
let mut b = encoded(Format::Jpeg);
// SOF0: marker, length, precision, then height and width (big-endian).
let sof = find(&b, &[0xFF, 0xC0]);
b[sof + 5..sof + 7].copy_from_slice(&16000u16.to_be_bytes());
b[sof + 7..sof + 9].copy_from_slice(&65000u16.to_be_bytes());
// The decoder's own scan-size guard refuses it (one refusal path for truncated and complete
// files alike), before the backend allocates the frame.
match decode(&b) {
Err(e) => assert!(e.to_string().contains("too short for the frame"), "{e}"),
Ok(i) => panic!("decoded a {}×{} frame from {} bytes", i.width(), i.height(), b.len()),
}
}
#[test]
fn image_crate_headers_declaring_gigabytes_need_a_plausible_file_size() {
let side = 30000u32;
let mut bmp = encoded(Format::Bmp);
bmp[18..22].copy_from_slice(&(side as i32).to_le_bytes());
bmp[22..26].copy_from_slice(&(side as i32).to_le_bytes());
refused_as_implausible(Format::Bmp, &bmp);
let mut qoi = encoded(Format::Qoi);
// The qoi crate refuses more than 400 M pixels itself, so 20000 x 20000 (1.6 GB).
qoi[4..8].copy_from_slice(&20000u32.to_be_bytes());
qoi[8..12].copy_from_slice(&20000u32.to_be_bytes());
refused_as_implausible(Format::Qoi, &qoi);
let mut gif = encoded(Format::Gif);
gif[6..8].copy_from_slice(&(side as u16).to_le_bytes());
gif[8..10].copy_from_slice(&(side as u16).to_le_bytes());
refused_as_implausible(Format::Gif, &gif);
// The frame too. Descriptor: separator, left, top, width, height.
let frame = find(&gif, &[0x2C, 0, 0, 0, 0, 64, 0, 48, 0]);
gif[frame + 5..frame + 7].copy_from_slice(&(side as u16).to_le_bytes());
gif[frame + 7..frame + 9].copy_from_slice(&(side as u16).to_le_bytes());
refused_as_implausible(Format::Gif, &gif);
}
/// GIF89a with a two-colour global table and one frame at the top left holding no pixels or
/// one pixel (LZW minimum code size 2: clear, index 0, end of information).
fn tiny_gif(screen: (u16, u16), frame: (u16, u16)) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
for v in [screen.0, screen.1] {
b.extend_from_slice(&v.to_le_bytes());
}
b.extend_from_slice(&[0x80, 0, 0, 0, 0, 0, 255, 255, 255, 0x2C, 0, 0, 0, 0]);
for v in [frame.0, frame.1] {
b.extend_from_slice(&v.to_le_bytes());
}
b.extend_from_slice(&[0, 2, 2, 0x44, 0x01, 0, 0x3B]);
b
}
#[test]
fn a_gif_frame_much_smaller_than_its_screen_still_decodes() {
let img = decode(&tiny_gif((4000, 4000), (1, 1))).unwrap();
assert_eq!((img.width(), img.height()), (4000, 4000));
}
#[test]
fn a_tiny_gif_frame_does_not_admit_a_gigabyte_screen() {
refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (1, 1)));
// 324 MB of screen: past the 256 MiB that needs no data.
refused_as_implausible(Format::Gif, &tiny_gif((9000, 9000), (1, 1)));
refused_as_implausible(Format::Gif, &tiny_gif((30000, 30000), (0, 0)));
// A frame bigger than its screen is decoded at its own size.
refused_as_implausible(Format::Gif, &tiny_gif((100, 100), (40000, 40000)));
}
#[test]
fn an_rle_bmp_ending_early_still_decodes() {
// 4000x4000 RLE8 whose only data is the end-of-bitmap escape: every pixel is left at index 0.
let data = 14 + 40 + 1024;
let mut b = b"BM".to_vec();
for v in [data + 2, 0, data, 40, 4000, 4000] {
b.extend_from_slice(&(v as u32).to_le_bytes());
}
b.extend_from_slice(&1u16.to_le_bytes());
b.extend_from_slice(&8u16.to_le_bytes());
for v in [1, 2, 0, 0, 0, 0] {
b.extend_from_slice(&(v as u32).to_le_bytes());
}
b.resize(data, 0);
b.extend_from_slice(&[0, 1]);
let img = decode(&b).unwrap();
assert_eq!((img.width(), img.height()), (4000, 4000));
}
#[test]
fn pcx_header_declaring_gigabytes_needs_a_plausible_file_size() {
// 24-bit (three 8-bit planes) 65535 x 16384, with one row of data.
let mut b = vec![0u8; 128];
b[0] = 0x0a;
b[1] = 5;
b[2] = 1;
b[3] = 8;
b[8..10].copy_from_slice(&65534u16.to_le_bytes());
b[10..12].copy_from_slice(&16383u16.to_le_bytes());
b[65] = 3;
b[66..68].copy_from_slice(&65535u16.to_le_bytes());
b[68..70].copy_from_slice(&1u16.to_le_bytes());
b.extend_from_slice(&[0xff, 0]);
// PCX's own minimum-packet check refuses it before the output is allocated.
match decode(&b) {
Err(CodecError::Malformed { message, .. }) => assert!(message.contains("too short"), "{message}"),
other => panic!("expected a too-short refusal, got {:?}", other.map(|i| (i.width(), i.height()))),
}
}
#[test]
fn xpm_rows_shorter_than_the_header_declares_are_refused_before_allocating() {
let b = b"/* XPM */\nstatic char *x[] = {\n\"30000 30000 1 1\",\n\". c #000000\",\n\".\",\n};\n".to_vec();
match decode(&b) {
Err(CodecError::Malformed { .. }) => {}
other => panic!("expected a malformed-row error, got {:?}", other.map(|i| (i.width(), i.height()))),
}
}
#[test]
fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() {
let mut b = encoded(Format::OpenExr);
// dataWindow: name, type, size, then xMin, yMin, xMax, yMax (little-endian i32).
let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4;
b[at + 8..at + 12].copy_from_slice(&15999i32.to_le_bytes());
b[at + 12..at + 16].copy_from_slice(&15999i32.to_le_bytes());
refused_as_implausible(Format::OpenExr, &b);
}
#[test]
fn a_dwab_exr_gets_a_looser_file_size_bound() {
// DWA passes 2^16:1 (a flat 8K frame with 12 alpha-scheme mattes is about 30 KB), so a DWAB
// part may declare 4 times more than a ZIP part from the same file, and no more.
let img = synth(1, 1, ChannelLayout::Rgba, SampleType::U8, 1, 0.1);
let mut b = encode(&img, Format::OpenExr, &EncodeOptions::default()).unwrap();
let at = find(&b, b"dataWindow\0box2i\0") + b"dataWindow\0box2i\0".len() + 4;
let c = find(&b, b"compression\0compression\0") + b"compression\0compression\0".len() + 4;
// RGBA as f32: 16 bytes a pixel against a file of a few hundred bytes.
let size = |b: &mut Vec<u8>, side: i32| {
b[at + 8..at + 12].copy_from_slice(&(side - 1).to_le_bytes());
b[at + 12..at + 16].copy_from_slice(&(side - 1).to_le_bytes());
};
let refused = |b: &[u8]| matches!(exr_info(b, &Limits::default()), Err(CodecError::LimitExceeded(m)) if m.contains("cannot hold"));
size(&mut b, 2048);
b[c] = 3; // ZIP
assert!(refused(&b), "{} bytes", b.len());
for dwa in [8, 9] {
b[c] = dwa; // DWAA, DWAB
let parts = exr_info(&b, &Limits::default()).unwrap();
assert_eq!((parts[0].width, parts[0].height), (2048, 2048));
}
size(&mut b, 4096);
assert!(refused(&b), "{} bytes", b.len());
}
#[test]
fn highly_compressible_jpeg_and_gif_still_decode() {
let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap();
for f in [Format::Jpeg, Format::Gif, Format::Qoi, Format::OpenExr] {
let b = encode(&img, f, &EncodeOptions::default()).unwrap();
assert_eq!(decode(&b).unwrap().width(), 3000, "{f:?}");
}
}
+32 -15
View File
@@ -82,6 +82,7 @@ pub mod file_cmds;
pub mod fill_cmds;
pub mod fill_key_cmds;
pub mod float_cmds;
pub mod font_library_cmds;
pub(super) mod frame_cmds;
pub mod fx_view_cmds;
pub mod fx_visibility_cmds;
@@ -438,26 +439,41 @@ fn build() -> Vec<CommandSpec> {
"Layer…",
["Layer", "New"],
Some("Cmd+Shift+N"),
r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)}"##,
r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##,
has_doc,
crate::new_layer::run
),
cmd!("layer.new.group", "Group…", ["Layer", "New"], None, r##"{"name":str?}"##, has_doc, |s, p| {
let id = s.edit("New Group", |doc, active| {
let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| doc.next_layer_name("Group"));
let id = doc.insert_above(*active, Layer::group(name, vec![]));
*active = Some(id);
Ok(id)
})?;
crate::layer_multi_cmds::note_inert_insert(s, id);
Ok(json!({ "layer": id.0 }))
}),
cmd!(
"layer.new.group",
"Group…",
["Layer", "New"],
None,
r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##,
has_doc,
|s, p| {
let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?;
let below = crate::group_options::below("layer.new.group", p)?;
let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto };
let id = s.edit("New Group", |doc, active| {
let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group"));
let mut group = Layer::group(name, vec![]);
opts.apply(&mut group);
let bg = crate::background_cmds::background_id(doc);
let id = crate::layer_place::insert_new(doc, *active, group, place);
crate::background_cmds::keep_background_at_bottom(bg, doc)?;
*active = Some(id);
Ok(id)
})?;
crate::layer_multi_cmds::note_inert_insert(s, id);
Ok(json!({ "layer": id.0 }))
}
),
cmd!(
"layer.groupLayers",
"Group Layers",
["Layer"],
Some("Cmd+G"),
r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##,
r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##,
has_layer,
crate::layer_multi_cmds::group_layers
),
@@ -778,7 +794,7 @@ fn build() -> Vec<CommandSpec> {
let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?;
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
@@ -810,7 +826,7 @@ fn build() -> Vec<CommandSpec> {
.in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?;
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
@@ -902,7 +918,7 @@ fn build() -> Vec<CommandSpec> {
"Brush Stroke",
[],
None,
r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##,
r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##,
has_paintable,
crate::brush_cmds::paint_stroke
),
@@ -1277,6 +1293,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::distort_cmds::specs());
v.extend(crate::analysis_cmds::specs());
v.extend(crate::notes_cmds::specs());
v.extend(crate::font_library_cmds::specs());
v.extend(crate::history_cmds::specs());
v.extend(crate::history_options_cmds::specs());
v.extend(crate::history_menu_cmds::specs());
+1 -1
View File
@@ -9,7 +9,7 @@ pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &
let id = s.edit(&label, |doc, active| {
let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj));
mask_new_layer(doc, &mut l, p, cmd, true)?;
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
+2 -2
View File
@@ -313,7 +313,7 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
surf.write_region(area, px);
surf.prune();
}
below = doc.insert_above(Some(below), l);
below = crate::layer_place::insert_new(doc, Some(below), l, crate::layer_place::Place::Above);
below
});
let Some(px) = &blended else {
@@ -327,7 +327,7 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
surf.write_region(area, px);
surf.prune();
}
let nid = doc.insert_above(Some(below), l);
let nid = crate::layer_place::insert_new(doc, Some(below), l, crate::layer_place::Place::Above);
*active = Some(nid);
Ok((Some(nid), depth_id))
})?;
+28 -4
View File
@@ -320,12 +320,35 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
/// The layers' union bounds, or the canvas when they have none: the board Artboard from Layers
/// makes when no size is given.
fn union_bounds<'a>(layers: impl IntoIterator<Item = &'a Layer>, canvas: Rect) -> Rect {
layers.into_iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas)
}
/// What Artboard from Layers' dialog opens with, as in the reference application: the name the
/// board would get and the selected top-level layers' size (`None` without a document).
pub fn from_layers_defaults(s: &Session) -> Option<(String, [i64; 2])> {
let d = s.active()?;
let ids = crate::layer_multi_cmds::top_level(&d.doc, &crate::layer_multi_cmds::selected(s));
let [_, _, w, h] = xywh(union_bounds(ids.iter().filter_map(|id| d.doc.layer(*id)), d.doc.bounds()));
Some((next_artboard_name(&d.doc), [w, h]))
}
fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
let sel = crate::layer_multi_cmds::selected(s);
let d = s.active().ok_or(EngineError::NoDocument)?;
let canvas = d.doc.bounds();
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let background = background_param(p, "layer.new.artboardFromLayers")?.unwrap_or_default();
let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string);
let cmd = "layer.new.artboardFromLayers";
let background = background_param(p, cmd)?.unwrap_or_default();
// `int` rounds, so a small negative (-0.4) would pass as 0, "keep the bounds".
if ["width", "height"].iter().any(|k| p.get(*k).and_then(Value::as_f64).is_some_and(|v| v < 0.0)) {
return Err(bad(cmd, "the artboard width and height must not be negative"));
}
// A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps
// their bounds on that axis (#9087).
let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)];
let (gid, rect) = s.edit("Artboard from Layers", |doc, active| {
let ids = crate::layer_multi_cmds::top_level(doc, &sel);
if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) {
@@ -335,7 +358,8 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
}
let rect = children.iter().filter_map(crate::layer_multi_cmds::layer_bounds).reduce(|a, b| a.union(&b)).unwrap_or(canvas);
let [x, y, w, h] = xywh(union_bounds(&children, canvas));
let rect = board_rect(cmd, [x, y, size[0].unwrap_or(w), size[1].unwrap_or(h)])?;
let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children);
set_artboard(&mut g, Artboard { rect, background, preset: String::new() });
let gid = doc.insert_above(None, g);
@@ -687,7 +711,7 @@ pub fn specs() -> Vec<CommandSpec> {
"layer.new.artboardFromLayers",
"Artboard from Layers…",
&["Layer", "New"],
r##"{"name":str?,"background":…?} (the selected layers) → {layer, rect}"##,
r##"{"name":text,"background":"white|black|transparent|custom"="white","color":color,"width":px=0,"height":px=0} (the selected layers; name: empty gives Artboard N; color: for custom; width, height: the board's size from the layers' top left, 0 keeps their bounds) → {layer, rect}"##,
has_free_layers,
artboard_from_layers
),
@@ -690,3 +690,43 @@ fn new_document_with_an_artboard() {
assert!(doc(&s).artboards().is_empty());
assert!(s.execute("file.new", json!({"artboard": "yes"})).is_err());
}
/// #9087: Artboard from Layers takes a size of the user's own, from the layers' top left; 0 or
/// none keeps their bounds on that axis, and a negative size is refused.
#[test]
fn artboard_from_layers_takes_a_custom_size() {
for (params, want) in [
(json!({"width": 108, "height": 135}), [10, 10, 108, 135]),
(json!({"width": 0, "height": 0}), [10, 10, 20, 20]),
(json!({"width": 60}), [10, 10, 60, 20]),
] {
let mut s = session(8);
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
let r = s.execute("layer.new.artboardFromLayers", params.clone()).unwrap();
assert_eq!(r["rect"], json!(want), "{params}");
}
let mut s = session(8);
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
assert!(s.execute("layer.new.artboardFromLayers", json!({"width": -5})).is_err());
// `int` rounds -0.4 to 0, which would otherwise keep the bounds.
assert!(s.execute("layer.new.artboardFromLayers", json!({"height": -0.4})).is_err());
assert!(doc(&s).artboards().is_empty(), "a refused size changes nothing");
assert_eq!(s.execute("layer.new.artboardFromLayers", json!({"name": ""})).unwrap()["rect"], json!([10, 10, 20, 20]));
assert_eq!(doc(&s).artboards()[0].1, "Artboard 1", "an empty name gives Artboard N");
}
/// The dialog's defaults (#9087): the selected layers' size and the board's name, as the command
/// makes it with no size; the canvas when the layers have no pixels.
#[test]
fn from_layers_defaults_are_the_selected_layers_size() {
let mut s = session(8);
add_square(&mut s, Rect::new(10, 10, 30, 40), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [20, 30])));
s.execute("layer.new.artboardFromLayers", json!({})).unwrap();
add_square(&mut s, Rect::new(50, 5, 60, 10), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(from_layers_defaults(&s), Some(("Artboard 2".to_string(), [10, 5])));
let mut s = session(8);
s.execute("layer.new.layer", json!({})).unwrap();
assert_eq!(from_layers_defaults(&s), Some(("Artboard 1".to_string(), [100, 80])), "an empty layer: the canvas");
assert_eq!(from_layers_defaults(&Session::new()), None);
}
+84
View File
@@ -422,9 +422,93 @@ pub fn paint_stroke(s: &mut Session, p: &Value) -> Result<Value> {
let pts = parse_points(p, "paint.stroke")?;
let brush = with_blend_mode(resolve_brush(s, p, "paint.stroke")?, p);
let label = if brush.erase && !clear_mode(p) { "Eraser" } else { "Brush Tool" };
if flag(p, "fill", false) {
return fill_region(s, p, label, brush, pts);
}
stroke_with(s, "paint.stroke", p, label, brush, pts, false)
}
/// `paint.stroke {fill: true}`: fill the region enclosed by `points` (their polygon) with the
/// brush's colour and opacity, its edge anti-aliased and softened by the brush hardness, instead of
/// stamping the outline. A closed gesture then paints a filled dab, not a ring (#3659).
fn fill_region(s: &mut Session, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>) -> Result<Value> {
if clear_mode(p) {
// `clear` maps onto the eraser; a clear fill would erase the region the outline encloses,
// which a selection + delete does deliberately (#3659). Reject before the eraser check so
// the message names the real conflict.
return Err(bad("paint.stroke", "\"fill\" cannot be combined with \"mode\":\"clear\"; select the enclosed region and delete it instead"));
}
if brush.erase {
return Err(bad("paint.stroke", "\"fill\" does not support the Eraser"));
}
if pts.len() < 3 {
return Err(bad("paint.stroke", "\"fill\" needs at least three points (a closed region)"));
}
let (id, brush, _zoom) = stroke_target(s, p, brush)?;
// A hard brush (hardness 1) keeps the anti-aliased polygon edge; a soft one feathers it by half
// the brush width, the way its tip fades.
let feather_px = ((1.0 - brush.hardness.clamp(0.0, 1.0)) * brush.size * 0.5).max(0.0);
let (color, opacity, mode) = (brush.color, brush.opacity.clamp(0.0, 1.0), brush.mode);
// A colour picked as CMYK fills with its inks in a CMYK target where it covers fully, as
// Edit › Fill does (blend_color_mask blends partial coverage through the colour's RGB).
let picked = brush.color_cmyk.filter(|(rgb, _)| *rgb == [color[0], color[1], color[2]]).map(|(_, inks)| inks);
let cmyk = doc_cmyk_space(s);
let dmg = photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || {
s.edit(label, |doc, _| {
let sel = doc.selection.clone();
let canvas = doc.bounds();
let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
// The polygon's whole-pixel bounds, grown by the feather's reach (3σ) so a soft edge
// fades out instead of being clipped.
let (mut bx0, mut by0, mut bx1, mut by1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for sp in &pts {
if !(sp.x.is_finite() && sp.y.is_finite()) {
return Err(bad("paint.stroke", "non-finite point in a fill"));
}
bx0 = bx0.min(sp.x);
by0 = by0.min(sp.y);
bx1 = bx1.max(sp.x);
by1 = by1.max(sp.y);
}
let ix = |v: f64| v.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32;
let reach = photocraft_algo::selection::feather_reach(feather_px);
let pad = i32::try_from(reach).unwrap_or(i32::MAX).saturating_add(2);
let bounds = Rect::new(
ix(bx0.floor()).saturating_sub(pad),
ix(by0.floor()).saturating_sub(pad),
ix(bx1.ceil()).saturating_add(pad),
ix(by1.ceil()).saturating_add(pad),
)
.intersect(&canvas);
if bounds.is_empty() {
return Ok(Rect::new(0, 0, 0, 0));
}
let (w, h) = (bounds.width() as usize, bounds.height() as usize);
// The coverage, its feathered copy (and the blur's scratch), the selection read and
// the mask are each a buffer over the whole region, which can be the whole canvas:
// reserve that peak first, so a region too big for memory is an error, not an abort.
const FILL: &str = "filling a painted region";
let peak = w.checked_mul(h).and_then(|n| n.checked_mul(5)).ok_or_else(|| crate::allocation::error(FILL, "requested size overflowed"))?;
drop(crate::allocation::capacity::<f32>(peak, FILL)?);
let xy: Vec<(f32, f32)> = pts.iter().map(|sp| (sp.x as f32, sp.y as f32)).collect();
let mut cov = photocraft_algo::selection::polygon(&xy, bounds, true);
if feather_px > 0.01 {
cov = photocraft_algo::selection::feather(&cov, w, h, feather_px);
}
if let Some(sel) = sel.as_ref() {
let sv = crate::allocation::read_region(sel, bounds, FILL)?;
for (c, s) in cov.iter_mut().zip(&sv) {
*c *= s.clamp(0.0, 1.0);
}
}
let coverage = photocraft_algo::selection::mask_to_surface(&cov, bounds);
crate::fill_cmds::blend_color_mask(surf, bounds, color, picked, &coverage, mode, opacity, lock)?;
Ok(bounds)
})
})?;
Ok(damage_json(s, dmg))
}
/// A `paint.stroke` rendered while it is drawn, onto a copy of the active document, so the canvas
/// shows the real dabs before the stroke commits. Committing the same params and points with
/// `"seed": live.seed` gives the same pixels.
+104
View File
@@ -31,6 +31,93 @@ fn stroke_backwards_compatible() {
assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01);
}
#[test]
fn fill_fills_the_enclosed_region_not_the_outline() {
// #3659: a closed gesture with `fill` paints the interior, not a ring.
let mut s = session(60, 60);
s.execute(
"paint.stroke",
json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 4, "color": "#ff0000", "brush": {"hardness": 1.0}}),
)
.unwrap();
assert!(rgba(&s, 30, 30)[0] > 0.9 && rgba(&s, 30, 30)[3] > 0.9, "interior filled: {:?}", rgba(&s, 30, 30));
assert_eq!(rgba(&s, 5, 30)[3], 0.0, "outside untouched");
assert_eq!(rgba(&s, 30, 5)[3], 0.0, "outside untouched");
// A soft brush feathers the edge outside the polygon; a hard one keeps a crisp edge.
let mut soft = session(60, 60);
soft.execute(
"paint.stroke",
json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}),
)
.unwrap();
assert!(rgba(&soft, 8, 30)[3] > 0.0, "a soft edge paints outside the polygon: {:?}", rgba(&soft, 8, 30));
// Graceful failures: fewer than three points, and the Eraser.
assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10]], "fill": true})).is_err());
assert!(s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50]], "fill": true, "erase": true})).is_err());
// One history step, like a normal stroke.
let before = s.active().unwrap().history.past_len();
s.execute("paint.stroke", json!({"points": [[12, 12], [48, 12], [48, 48], [12, 48]], "fill": true, "color": "#0000ff"})).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "fill is one history step");
}
#[test]
fn fill_is_rejected_with_clear_mode() {
// #3659 review: `"mode":"clear"` maps onto the eraser, so a clear fill would erase the region
// the outline encloses. Reject it; a selection + delete does that deliberately.
let mut s = session(60, 60);
let poly = json!([[10, 10], [50, 10], [50, 50], [10, 50]]);
assert!(s.execute("paint.stroke", json!({"points": poly.clone(), "fill": true, "mode": "clear"})).is_err());
// `clear` without `fill` still erases along the outline (main's behaviour), unchanged.
s.execute("paint.stroke", json!({"points": poly, "fill": true, "size": 4, "color": "#ff0000"})).unwrap();
assert!(rgba(&s, 30, 30)[3] > 0.9, "the region is filled first");
s.execute("paint.stroke", json!({"points": [[30, 2], [30, 58]], "size": 10, "mode": "clear"})).unwrap();
assert!(rgba(&s, 30, 30)[3] < 0.01, "a clear stroke erased what it crossed");
assert!(rgba(&s, 12, 30)[3] > 0.9, "pixels the clear stroke missed remain");
}
#[test]
fn fill_soft_edge_has_no_step() {
// #3779: the feather (σ = 20 here) reaches 3σ = 60 px past the square; the fill's working
// bounds must reach as far, or the soft edge ends in a hard step where they clip it.
let mut s = session(200, 200);
s.execute(
"paint.stroke",
json!({"points": [[80, 80], [120, 80], [120, 120], [80, 120]], "fill": true, "size": 40, "color": "#ff0000", "brush": {"hardness": 0.0}}),
)
.unwrap();
assert!(rgba(&s, 57, 100)[3] > 0.0, "the fade continues past 1σ: {:?}", rgba(&s, 57, 100));
for x in 0..199 {
let (a, b) = (rgba(&s, x, 100)[3], rgba(&s, x + 1, 100)[3]);
assert!((a - b).abs() < 0.03, "step between x={x} ({a}) and x={} ({b})", x + 1);
}
}
#[test]
fn fill_paints_a_cmyk_pick_with_the_picked_inks() {
// #3779: like a plain stroke (#4344), a fill paints a colour picked as CMYK as its inks.
let cyan = [1.0f32, 0.0, 0.0, 0.0];
let mut s = session(16, 16);
s.execute("image.mode.cmyk", json!({})).unwrap();
let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0));
s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap();
s.execute("paint.stroke", json!({"points": [[2, 2], [14, 2], [14, 14], [2, 14]], "fill": true, "hardness": 1.0})).unwrap();
let st = s.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
let got: Vec<f32> = surf.read_region(Rect::new(8, 8, 9, 9)).into_iter().take(4).collect();
assert!(got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02), "{got:?}");
}
#[test]
fn fill_works_on_cmyk_and_16_and_32_bit() {
for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 60, "height": 30, "mode": mode, "depth": depth})).unwrap();
s.execute("paint.stroke", json!({"points": [[10, 5], [50, 5], [50, 25], [10, 25]], "fill": true, "color": "#000000", "hardness": 1.0})).unwrap();
assert!(rgba(&s, 30, 15)[0] < 0.2, "{mode}/{depth}: {:?}", rgba(&s, 30, 15));
assert!(rgba(&s, 5, 15)[0] > 0.8, "{mode}/{depth} outside: {:?}", rgba(&s, 5, 15));
}
}
#[test]
fn stroke_accepts_full_points_brush_and_preset() {
let mut s = session(200, 100);
@@ -493,6 +580,23 @@ fn define_brush_from_selection() {
assert!(rgba(&s, 30, 32)[3] > 0.9);
}
#[test]
fn fill_survives_allocation_failure() {
// CodeRabbit on #9775: a fill's buffers span the region, up to the whole canvas. Their peak is
// reserved through the fallible allocator before any of them is built, so running out of
// memory is the fill's own error, leaving the pixels and history alone, never an abort.
let mut s = session(60, 60);
let pixels_before = surface(&s);
let history_before = s.active().unwrap().history.past_len();
crate::allocation::fail_next_for_test();
let result = s.execute("paint.stroke", json!({"points": [[10, 10], [50, 10], [50, 50], [10, 50]], "fill": true, "color": "#ff0000"}));
let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
let err = result.expect_err("an allocation failure must be reported, not panic").to_string();
assert!(err.contains("filling a painted region"), "the fill reserves its buffers first: {err}");
assert_eq!(surface(&s), pixels_before, "no pixels changed");
assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded");
}
#[test]
fn define_brush_from_selection_survives_allocation_failure() {
// The sampled tip is one f32 buffer over the whole selection, and the selection mask is a
+7 -3
View File
@@ -403,7 +403,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {
let id = s.edit("Paste", |doc, active| {
let mut l = Layer::raster(doc.next_layer_name("Layer"), target);
*crate::pixels_mut(&mut l)? = surf;
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable);
*active = Some(id);
doc.selection = None;
Ok(id)
@@ -445,9 +445,13 @@ fn paste_layers(s: &mut Session, layers: &Document, dx: i32, dy: i32) -> Result<
let id = s.edit("Paste", |doc, active| {
doc.patterns.extend(patterns);
doc.metadata.psd_global_blocks.extend(linked);
// The first pasted layer goes where a new layer would; the rest stack above it.
let mut place = crate::layer_place::Place::AutoEditable;
for l in copies.layers {
*active = Some(doc.insert_above(*active, l));
*active = Some(crate::layer_place::insert_new(doc, *active, l, place));
place = crate::layer_place::Place::Above;
}
crate::cmd::layer_multi_cmds::check_group_depth(doc, "Paste")?;
doc.selection = None;
active.ok_or(EngineError::Other("nothing to paste".into()))
})?;
@@ -587,7 +591,7 @@ fn layer_via(s: &mut Session, cut: bool) -> Result<Value> {
}
let mut l = Layer::raster(doc.next_layer_name("Layer"), clip.surface.format());
*crate::pixels_mut(&mut l)? = clip.surface;
let nid = doc.insert_above(Some(id), l);
let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above);
*active = Some(nid);
// Photoshop deselects: a following Free Transform moves the whole new layer (#1096).
doc.selection = None;
@@ -503,7 +503,7 @@ fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &
s.write_region(window, &px);
s.prune();
}
let nid = doc.insert_above(Some(id), l);
let nid = crate::layer_place::insert_new(doc, Some(id), l, crate::layer_place::Place::Above);
*active = Some(nid);
return Ok(nid);
}
+19 -4
View File
@@ -138,12 +138,16 @@ pub(crate) fn process_tree(
/// The extension a batch output takes with Format "Same": the input's own, except for formats
/// PhotoCraft opens but can't write, camera raws above all (#5799: a folder of ARWs failed on
/// every file). Those are saved as PSD, the format Photoshop's Save As offers for a raw. An input
/// whose file name has no extension (a dot in a folder name doesn't count) is saved as PNG.
/// every file), GIMP files (`gz` is the last extension of `.xcf.gz`), Photoshop templates and the
/// codec formats without a writer in this build. Those are saved as PSD, the format Photoshop's
/// Save As offers for a raw. An input whose file name has no extension (a dot in a folder name
/// doesn't count) is saved as PNG.
pub(super) fn same_format(path: &str) -> String {
const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm"];
const IMPORT_ONLY: &[&str] =
&["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt"];
let ext = extension(path).unwrap_or_else(|| "png".into());
if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) { "psd".into() } else { ext }
let no_writer = photocraft_codecs::from_extension(&ext).is_some_and(|f| !f.caps().write);
if photocraft_io::raw::EXTENSIONS.contains(&ext.as_str()) || IMPORT_ONLY.contains(&ext.as_str()) || no_writer { "psd".into() } else { ext }
}
#[cfg(test)]
@@ -155,6 +159,17 @@ fn same_format_takes_the_file_names_extension() {
assert_eq!(same_format("/in/IMG_0001.HEIC"), "psd");
assert_eq!(same_format("/in/logo.svg"), "psd");
assert_eq!(same_format("/in/scan.cin"), "psd");
// Formats PhotoCraft opens and does not write are saved as PSD.
for name in ["/in/scan.dcm", "/in/scan.DICOM", "/in/scan.dc3", "/in/page.xcf", "/in/page.xcf.gz", "/in/page.xcfgz", "/in/card.psdt"] {
assert_eq!(same_format(name), "psd", "{name}");
}
for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read && !f.caps().write) {
for ext in f.extensions() {
assert_eq!(same_format(&format!("/in/a.{ext}")), "psd", "{f:?} .{ext}");
}
}
assert_eq!(same_format("/in/a.pam"), "pam");
assert_eq!(same_format("/in/a.dds"), "dds");
// No extension in the file name: PNG, not the path after a dot in a folder name.
assert_eq!(same_format("/in/v1.2/scan"), "png");
assert_eq!(same_format("C:\\in.d\\scan"), "png");
+1 -1
View File
@@ -202,7 +202,7 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec<u8>, linked: Option<S
} else {
Layer::new(layer_name, LayerContent::Raster(px))
};
let id = doc.insert_above(*active, layer);
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
*active = Some(id);
Ok(id)
})?;
+13 -7
View File
@@ -55,20 +55,26 @@ pub fn list_images(dir: &str) -> Result<Vec<String>> {
Err(EngineError::Other(format!("cannot list {dir}: no file system on the web")))
}
/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's
/// gzipped `.xcf.gz`, whose last extension alone says nothing.
/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, an extension
/// of a format `photocraft-codecs` reads in this build, or GIMP's gzipped `.xcf.gz`, whose last
/// extension alone says nothing.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn openable_name(path: &str) -> bool {
let lower = file_name(path).to_ascii_lowercase();
lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext))
lower.ends_with(".xcf.gz")
|| lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext) || photocraft_codecs::from_extension(ext).is_some_and(|f| f.caps().read))
}
/// Extensions the batch commands pick up from a folder.
/// Extensions the batch commands pick up from a folder besides the codec formats: the document
/// and vector formats `photocraft_io::import` reads outside `photocraft-codecs`, and the camera
/// raws whose usual files `photocraft_raw::decode` develops. Not CR3, ORF, RAF, RW2, SRF or SR2:
/// CR3, compressed ORF and RAF and RW2 raw formats other than 3, 4 and 5 aren't decoded yet, and
/// import falls back to the embedded JPEG preview with only a warning, which a batch must not
/// process silently.
#[cfg(not(target_arch = "wasm32"))]
const OPENABLE: &[&str] = &[
"pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi",
"ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign",
"afphoto", "afpub",
"pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "psdt", "pcraft", "svg", "svgz", "af", "afdesign", "afphoto", "afpub", "dng", "cr2", "nef",
"nrw", "arw", "pef",
];
pub(crate) fn file_name(path: &str) -> String {
+44
View File
@@ -1835,6 +1835,50 @@ fn folder_listing_recognises_gzipped_xcf_by_its_double_extension() {
assert!(!super::openable_name("notes.txt"));
}
/// A folder batch picks up every extension that the codecs open: Cineon, DICOM, Amiga IFF, PCX,
/// XPM, DDS, the Netpbm family, and Photoshop templates. Not the raws whose usual files open only
/// as the embedded JPEG preview (CR3, compressed ORF and RAF, RW2 other than raw formats 3, 4 and
/// 5): a batch would process the thumbnail without a word.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn folder_listing_takes_every_format_photocraft_opens() {
let codecs = ["a.cin", "a.dcm", "a.dicom", "a.dc3", "a.iff", "a.lbm", "a.ilbm", "a.pcx", "a.xpm", "a.dds", "a.pbm", "a.pam", "a.pfm", "a.psdt", "A.PCX"];
let raws = ["a.dng", "IMG_0001.CR2", "a.nef", "a.nrw", "a.arw", "a.pef"];
for name in codecs.into_iter().chain(raws) {
assert!(super::openable_name(name), "{name}");
}
for f in photocraft_codecs::Format::ALL.into_iter().filter(|f| f.caps().read) {
for ext in f.extensions() {
assert!(super::openable_name(&format!("a.{ext}")), "{f:?} .{ext}");
}
}
for name in ["a.cr3", "IMG_0001.CR3", "a.orf", "a.raf", "a.rw2", "a.srf", "a.sr2"] {
assert!(!super::openable_name(name), "{name}");
}
// PhotoCraft does not read AVIF.
assert!(!super::openable_name("a.avif"));
}
/// A batch over a folder processes PAM, PFM and DDS files instead of skipping them.
#[test]
fn batch_folder_processes_netpbm_and_dds_files() {
let dir = tmp("batch-folder-formats");
let src = join(&dir, "in");
std::fs::create_dir_all(&src).unwrap();
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ff0000"})).unwrap();
for name in ["a.pam", "b.pfm", "c.dds"] {
save_doc(doc(&s), &join(&src, name), None).unwrap();
}
std::fs::write(join(&src, "notes.txt"), b"not an image").unwrap();
let out = join(&dir, "out");
let r = Session::new().execute("file.automate.batch", json!({"steps": [], "input": src, "output": out, "format": "png"})).unwrap();
assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
let mut files: Vec<String> = r["files"].as_array().unwrap().iter().map(|f| file_name(f.as_str().unwrap())).collect();
files.sort();
assert_eq!(files, ["a.png", "b.png", "c.png"], "{r}");
}
/// The Compression tag (259) of a TIFF's first directory.
fn tiff_compression_tag(b: &[u8]) -> Option<u16> {
let le = b.get(..2)? == b"II";
+105
View File
@@ -0,0 +1,105 @@
//! The font menu's favourite font families: the star beside each font, kept until un-starred. They
//! live in the preferences, so they survive a restart, and are plain family names: a favourite
//! whose font is uninstalled is kept, though the menu lists installed fonts only, and shows it
//! again once the font is back (`type.font.favorite` with `"on": false` removes it). (The
//! recently used fonts are the shell's, `PhotocraftApp::note_recent_font`.)
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
/// The most favourites kept (a hand-edited preferences file can't grow the menu without bound).
pub const MAX_FAVORITE_FONTS: usize = 1000;
/// The longest family name accepted, in characters.
const MAX_FAMILY_CHARS: usize = 256;
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
/// The `family` param: a non-empty name without control characters, trimmed.
fn family(p: &Value, cmd: &str) -> Result<String> {
let name = p.get("family").and_then(Value::as_str).ok_or_else(|| bad(cmd, "pass `family`, a font family name"))?.trim();
if name.is_empty() {
return Err(bad(cmd, "`family` is empty"));
}
if name.chars().count() > MAX_FAMILY_CHARS {
return Err(bad(cmd, format!("`family` is longer than {MAX_FAMILY_CHARS} characters")));
}
if name.chars().any(char::is_control) {
return Err(bad(cmd, "`family` contains control characters"));
}
Ok(name.to_string())
}
/// The favourites as the menu shows them: valid names, once each, at most [`MAX_FAVORITE_FONTS`].
pub fn favorite_fonts(s: &Session) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for f in &s.prefs().type_.favorite_fonts {
if out.len() >= MAX_FAVORITE_FONTS {
break;
}
if !f.trim().is_empty() && !out.contains(f) {
out.push(f.clone());
}
}
out
}
/// Star or un-star a family (`on` sets it; without it the star toggles).
fn favorite(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "type.font.favorite";
let name = family(p, CMD)?;
let mut list = favorite_fonts(s);
let on = match p.get("on") {
None => !list.contains(&name),
Some(v) => v.as_bool().ok_or_else(|| bad(CMD, "`on` must be true or false"))?,
};
list.retain(|f| *f != name);
if on {
if list.len() >= MAX_FAVORITE_FONTS {
return Err(bad(CMD, format!("at most {MAX_FAVORITE_FONTS} favourite fonts")));
}
list.push(name.clone());
}
let stored = list.clone();
s.prefs.edit(|p| p.type_.favorite_fonts = stored);
Ok(json!({"family": name, "favorite": on, "favorites": list}))
}
fn library(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"favorites": favorite_fonts(s)}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: "type.font.favorite",
label: "Add to Favorites",
menu: &[],
shortcut: None,
params: r#"{"family":str,"on":bool?=toggle} → family, favorite, favorites"#,
enabled: always,
run: favorite,
journal: false,
},
CommandSpec {
id: "type.font.library",
label: "Font Library",
menu: &[],
shortcut: None,
params: "{} → favorites",
enabled: always,
run: library,
journal: false,
},
]
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,79 @@
use serde_json::json;
use super::*;
fn session() -> Session {
Session::new()
}
#[test]
fn starring_toggles_and_on_sets_a_favourite() {
let mut s = session();
s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap();
s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap();
assert_eq!(favorite_fonts(&s), ["Arial", "Bebas Neue"]);
// Toggling again removes it; `on` sets it either way.
let r = s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap();
assert_eq!(r["favorite"], false);
s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": true})).unwrap();
assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "on: true doesn't duplicate");
s.execute("type.font.favorite", json!({"family": "Bebas Neue", "on": false})).unwrap();
assert!(favorite_fonts(&s).is_empty());
}
#[test]
fn resetting_the_type_preferences_keeps_the_favourites() {
let mut s = session();
s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap();
s.execute("prefs.set", json!({"path": "type.smartQuotes", "value": false})).unwrap();
s.execute("prefs.reset", json!({"path": "type"})).unwrap();
assert!(s.prefs().type_.smart_quotes, "the Type settings are reset");
assert_eq!(favorite_fonts(&s), ["Bebas Neue"], "the favourites are the user's library, not a setting");
// Asked for by name, or with everything, they go.
s.execute("prefs.reset", json!({"path": "type.favoriteFonts"})).unwrap();
assert!(favorite_fonts(&s).is_empty());
s.execute("type.font.favorite", json!({"family": "Bebas Neue"})).unwrap();
s.execute("prefs.reset", json!({})).unwrap();
assert!(favorite_fonts(&s).is_empty());
}
#[test]
fn the_library_survives_a_preferences_round_trip_and_hostile_lists_are_tidied() {
let mut s = session();
s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap();
let saved = serde_json::to_value(s.prefs()).unwrap();
assert_eq!(saved["type"]["favoriteFonts"], json!(["Arial"]));
let mut t = session();
let prefs = serde_json::from_value(saved).unwrap();
t.prefs.edit(|p| *p = prefs);
let lib = t.execute("type.font.library", json!({})).unwrap();
assert_eq!(lib, json!({"favorites": ["Arial"]}));
// Duplicates, blanks and an oversized list from a hand-edited file are tidied on read.
t.prefs.edit(|p| p.type_.favorite_fonts = (0..5000).map(|i| format!("F{}", i % 1200)).chain([String::new()]).collect());
assert_eq!(favorite_fonts(&t).len(), MAX_FAVORITE_FONTS);
}
#[test]
fn bad_params_are_errors_and_change_nothing() {
let mut s = session();
s.execute("type.font.favorite", json!({"family": "Arial"})).unwrap();
for (id, p) in [
("type.font.favorite", json!({})),
("type.font.favorite", json!({"family": 42})),
("type.font.favorite", json!({"family": " "})),
("type.font.favorite", json!({"family": "a\u{0}b"})),
("type.font.favorite", json!({"family": "x".repeat(300)})),
("type.font.favorite", json!({"family": "Arial", "on": "yes"})),
] {
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
}
assert_eq!(favorite_fonts(&s), ["Arial"]);
}
#[test]
fn font_library_edits_are_not_recorded_into_actions() {
// Playing an action back must not rewrite the user's favourite fonts.
for id in ["type.font.favorite", "type.font.library"] {
assert!(!crate::actions_cmds::replayable(id), "{id}");
}
}
+8 -2
View File
@@ -146,9 +146,15 @@ fn new_frame(s: &mut Session, p: &Value) -> Result<Value> {
crate::layer_multi_cmds::check_group_depth(doc, "New Frame")?;
gid
}
None => doc.insert_above(*active, Layer::group(name, vec![])),
None => crate::layer_place::insert_new(doc, *active, Layer::group(name, vec![]), crate::layer_place::Place::AutoEditable),
};
doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask);
let frame = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?;
frame.mask = Some(mask);
// A frame is one row, as in Photoshop: closed, so the next new layer goes above it rather
// than into it.
if let LayerContent::Group(g) = &mut frame.content {
g.expanded = false;
}
*active = Some(gid);
Ok(gid)
})?;
+1 -1
View File
@@ -322,7 +322,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
new_layer(s, &d.doc, p)?
};
let id = s.edit("New Gradient Fill Layer", |doc, active| {
let id = doc.insert_above(*active, layer);
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::AutoEditable);
*active = Some(id);
Ok(id)
})?;
+4 -1
View File
@@ -216,8 +216,11 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result<Value> {
doc.patterns.extend(patterns);
let mut above = *active;
let mut new = Vec::with_capacity(copies.layers.len());
// The first copy goes where a new layer would; the rest stack above it.
let mut place = crate::layer_place::Place::AutoEditable;
for l in copies.layers {
let id = doc.insert_above(above, l);
let id = crate::layer_place::insert_new(doc, above, l, place);
place = crate::layer_place::Place::Above;
above = Some(id);
new.push(id);
}
+1 -1
View File
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Group from Layers…",
&["Layer", "New"],
None,
r##"{"layer":id?,"name":str?} (no layer: every selected layer)"##,
r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##,
has_layer,
group_layers
),
@@ -97,7 +97,7 @@ pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> {
/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves
/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is
/// preserved.
/// preserved. The New Group dialog's colour, mode and opacity are set in the same history step.
pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
let ids = match crate::commands::explicit_layer(s, p)? {
Some(id) => vec![id],
@@ -106,11 +106,15 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(EngineError::Other("no layer selected".into()));
}
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let opts = crate::group_options::GroupOptions::parse("layer.groupLayers", p)?;
let gid = s.edit("Group Layers", |doc, active| {
let ids = top_level(doc, &ids);
// Artboards stay at the top level: inside a group they would stop being boards.
if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {
return Err(EngineError::Other("artboards can't go into a group".into()));
}
let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?;
let name = name.unwrap_or_else(|| doc.next_layer_name("Group"));
let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group"));
// Photoshop creates the group collapsed, so the panel shows one row in place of the layers.
let mut group = Layer::group(name, vec![]);
if let LayerContent::Group(g) = &mut group.content {
@@ -121,7 +125,9 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
}
*doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children;
let group = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?;
*group.children_mut().ok_or(EngineError::NoLayer(gid))? = children;
opts.apply(group);
check_group_depth(doc, "Group Layers")?;
*active = Some(gid);
Ok(gid)
@@ -918,6 +918,31 @@ fn group_from_layers_preserves_order() {
assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded));
}
/// Artboards are top-level groups; grouping them (now a plain click on the Layers panel's New
/// Group button with two boards selected) is refused and leaves them as they were.
#[test]
fn grouping_artboards_is_refused() {
let mut s = session(8);
let a = LayerId(s.execute("layer.new.artboard", json!({"rect": [0, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap());
let b = LayerId(s.execute("layer.new.artboard", json!({"rect": [120, 0, 100, 80]})).unwrap()["layer"].as_u64().unwrap());
select_all(&mut s, &[a, b]);
let before = doc(&s).clone();
let err = s.execute("layer.groupLayers", json!({})).unwrap_err();
assert!(err.to_string().contains("artboards"), "{err}");
assert!(s.execute("layer.groupLayers", json!({"layer": a.0})).is_err(), "one board is refused too");
assert_eq!(doc(&s).layers.iter().map(|l| l.id).collect::<Vec<_>>(), before.layers.iter().map(|l| l.id).collect::<Vec<_>>());
assert_eq!(doc(&s).artboards().len(), 2);
// A layer inside a board still groups, inside its board. (Made with no layer selected: a
// new layer with a board selected goes into that board, as in Photoshop.)
s.execute("select.deselectLayers", json!({})).unwrap();
let inner = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
select_all(&mut s, &[inner]);
let c = LayerId(s.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(doc(&s).artboard_of(inner), Some(c));
let g = LayerId(s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().unwrap());
assert_eq!(doc(&s).artboard_of(g), Some(c));
}
#[test]
fn grouping_is_capped_at_the_document_nesting_limit() {
let mut s = session(8);
+3 -1
View File
@@ -118,8 +118,10 @@ mod tests {
s.execute("layer.select", json!({"layer": c.0, "mode": "add"})).unwrap();
s.execute("layer.groupLayers", json!({})).unwrap();
let group = s.active().unwrap().doc.layers.iter().find(|l| l.is_group()).unwrap().id;
s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap();
// D goes above the closed group (an open one would take it inside, as in Photoshop).
let d = id(&mut s, "layer.new.layer", json!({"name": "D"}));
// Group Layers makes a collapsed group; open it so the panel shows B and C.
s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": true})).unwrap();
(s, [bg, a, group, b, c, d])
}
+20 -2
View File
@@ -6,7 +6,8 @@
//!
//! Every command targets a path like `path.transform`: `"name":"work"` (default), a saved path's
//! name, or `"layer"` with `"layer":id?` for a shape layer's path (re-rendered; it stops being a
//! live shape) or a layer's vector mask. Knots are addressed by `subpath` and `knot` index, as
//! live shape), a layer's vector mask, or type on a path's Type Path (`"typePath":true` when the
//! type layer also has a vector mask). Knots are addressed by `subpath` and `knot` index, as
//! listed by `path.info`, and the result is `{name, path}` in the compact JSON form.
use photocraft_doc::{LayerContent, Path};
@@ -49,6 +50,23 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> {
fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned();
let layer = if name == "layer" { Some(layer_id(s, p)?) } else { None };
// Type on a path: its own path, the text laid along it again (#9114). A vector mask on the
// layer stays what `"layer"` edits, as with `path.info`, unless `"typePath": true`.
let type_path = p.get("typePath").and_then(Value::as_bool).unwrap_or(false);
let typed = layer.filter(|id| {
s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| {
matches!(&l.content, LayerContent::Text(t) if crate::type_extra_cmds::type_path(t).is_some()) && (type_path || l.vector_mask.is_none())
})
});
if let Some(id) = typed {
let path = crate::type_extra_cmds::with_text(s, &json!({"layer": id.0}), label, |t, _| {
let mut path = crate::type_extra_cmds::type_path(t).ok_or_else(|| bad(cmd, "the type layer is not on a path"))?;
f(&mut path).map_err(|e| bad(cmd, e))?;
crate::type_extra_cmds::set_type_path(t, &path)?;
Ok(path_json(&path))
})?;
return Ok(json!({ "name": name, "path": path }));
}
let shape = layer.filter(|id| s.active().and_then(|d| d.doc.layer(*id)).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))));
let path = match shape {
Some(id) => with_shape(s, id, label, |sh, _| {
@@ -149,7 +167,7 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result<Value> {
}
pub fn specs() -> Vec<CommandSpec> {
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#;
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path, a vector mask, or else type on a path's Type Path),"typePath":bool=false (with "layer": the Type Path even when the type layer has a vector mask)"#;
let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result<Value>| CommandSpec {
id,
label,
+1 -1
View File
@@ -348,7 +348,7 @@ pub(crate) fn insert_fill_layer(
let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };
let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));
crate::commands::mask_new_layer(doc, &mut l, p, "layer.newFillLayer.pattern", default_mask)?;
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
}
+4 -2
View File
@@ -508,8 +508,10 @@ fn pdf_string(s: &str) -> String {
}
fn deflate(data: &[u8]) -> Vec<u8> {
// Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default.
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
// Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static
// Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger
// than miniz's level 1 was, at about twice its time.
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3));
let _ = e.write_all(data);
e.finish().unwrap_or_default()
}
+1 -1
View File
@@ -109,7 +109,7 @@ fn draw(s: &mut Session, label: &str, p: &Value, prims: Vec<Prim>, extra: Value)
let raster = id.and_then(|i| doc.layer(i)).is_some_and(|l| matches!(l.content, LayerContent::Raster(_)));
let (id, created) = if want_new || !raster {
let l = Layer::new(label.trim_end_matches('…'), LayerContent::Raster(Surface::new(doc.pixel_format())));
let nid = doc.insert_above(*active, l);
let nid = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable);
*active = Some(nid);
(nid, true)
} else {
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
r#","strokes":[[[x,y,pressure?],…],…]? (several strokes removed together, as one job and one undo step; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"#
r#","strokes":[[[x,y,pressure?],…]|{"points":[…],"size"?,"hardness"?,"spacing"?},…]? (several strokes removed together, as one job and one undo step, each with its own size, hardness and spacing when given; else "points"),"closeLoops":bool=true (a stroke around an object removes what it encloses),"sampleAllLayers":bool=false,"newLayer":bool=false (the fill goes to a new layer above the target, which stays as it was) → {"damage","layer"?} (a background job)"#
),
enabled: has_pixel_layer,
run: remove::remove,
+22 -6
View File
@@ -74,17 +74,32 @@ fn parse_strokes(s: &Session, p: &Value) -> Result<(Vec<Stroke>, Option<LayerId>
reject_huge_stroke(CMD, &stroke)?;
return Ok((vec![stroke], id));
};
let list = list.as_array().ok_or_else(|| bad(CMD, "`strokes` is a list of point lists"))?;
const ENTRY: &str = "each `strokes` entry is a point list or {\"points\", \"size\"?, \"hardness\"?, \"spacing\"?}";
let list = list.as_array().ok_or_else(|| bad(CMD, ENTRY))?;
if list.is_empty() {
return Err(bad(CMD, "`strokes` is empty"));
}
let mut strokes = Vec::with_capacity(list.len());
let mut id = None;
for points in list {
for entry in list {
let mut one = p.clone();
if let Some(o) = one.as_object_mut() {
o.remove("strokes");
o.insert("points".into(), points.clone());
let Some(o) = one.as_object_mut() else { return Err(bad(CMD, "params must be an object")) };
o.remove("strokes");
match entry {
// A stroke drawn with another brush than the rest (the waiting strokes of Remove after
// each stroke off keep the size, hardness and spacing each was drawn with).
Value::Object(e) => {
let points = e.get("points").ok_or_else(|| bad(CMD, ENTRY))?;
o.insert("points".into(), points.clone());
for k in ["size", "hardness", "spacing"] {
if let Some(v) = e.get(k) {
o.insert(k.into(), v.clone());
}
}
}
points => {
o.insert("points".into(), points.clone());
}
}
let (stroke, layer) = parse_brush(s, &one, CMD)?;
reject_huge_stroke(CMD, &stroke)?;
@@ -201,7 +216,8 @@ fn fill_to_new_layer(doc: &mut Document, id: Option<LayerId>, out: &Region, hole
}
let mut l = Layer::raster(doc.next_layer_name("Layer"), fmt);
crate::pixels_mut(&mut l)?.write_region(out.rect, &data);
let nid = doc.insert_above(id, l);
// Above the sampled layer and in its clipping mask, like Layer via Copy.
let nid = crate::layer_place::insert_new(doc, id, l, crate::layer_place::Place::Above);
Ok((out.rect, nid))
}
@@ -2156,6 +2156,27 @@ fn remove_several_strokes_apply_as_one_job_and_one_undo_step() {
}
}
/// A `strokes` entry may carry its own size, hardness and spacing: the Remove Tool's waiting
/// strokes keep the brush each was drawn with, whatever the brush is when they are applied.
#[test]
fn remove_strokes_each_keep_their_own_brush() {
let entry = |pts: Value, size: f64| json!({"points": pts, "size": size, "hardness": 100, "spacing": 25});
let removed = |strokes: Value, size: f64| {
let mut s = square_session(8, "rgb");
let bg = rgba(&s, 10, 10);
s.execute("paint.remove", json!({"strokes": strokes, "size": size})).unwrap();
[(41, 30), (46, 30), (51, 30)].iter().all(|&(x, y)| near(rgba(&s, x, y), bg, 0.03))
};
let (a, b) = (json!([[38, 30], [45, 30]]), json!([[47, 30], [54, 30]]));
assert!(removed(json!([entry(a.clone(), 16.0), entry(b.clone(), 16.0)]), 2.0), "each entry's 16 px, not the 2 px of the call");
assert!(!removed(json!([entry(a.clone(), 2.0), entry(b.clone(), 2.0)]), 16.0), "each entry's 2 px, not the 16 px of the call");
assert!(removed(json!([entry(a, 16.0), b]), 16.0), "a plain point list takes the call's brush");
let mut s = square_session(8, "rgb");
for strokes in [json!([{"size": 16}]), json!([{"points": "x"}]), json!([{"points": []}]), json!([7])] {
assert!(s.execute("paint.remove", json!({"strokes": strokes, "size": 16})).is_err(), "{strokes}");
}
}
#[test]
fn remove_to_a_new_layer_leaves_the_target_untouched() {
let mut s = square_session(8, "rgb");
+2 -2
View File
@@ -74,7 +74,7 @@ fn stamp_visible(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(empty);
}
let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?;
let id = doc.insert_above(*active, layer);
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Above);
*active = Some(id);
Ok(id)
})?;
@@ -156,7 +156,7 @@ fn stamp_selected(s: &mut Session, sel: &[LayerId]) -> Result<Value> {
}
let name = format!("{} (merged)", doc.layer(top).map_or("Layer", |l| l.name.as_str()));
let layer = stamp_layer(&solo, name)?;
let id = doc.insert_above(Some(top), layer);
let id = crate::layer_place::insert_new(doc, Some(top), layer, crate::layer_place::Place::Above);
*active = Some(id);
Ok(id)
})?;
+1 -1
View File
@@ -906,7 +906,7 @@ pub fn specs() -> Vec<CommandSpec> {
let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| layer_name(&t.text));
let id = s.edit("New Type Layer", |doc, active| {
refresh(doc, &mut t);
let id = doc.insert_above(*active, Layer::new(name, LayerContent::Text(t)));
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable);
*active = Some(id);
Ok(id)
})?;
+32
View File
@@ -415,6 +415,38 @@ fn attach_to_path(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"layer": id.0, "start": start, "flip": flip}))
}
/// Type on a path's own path in document space (#9114): what the Direct Selection tool shows and
/// edits, as Photoshop's Type Path. `None` unless `t` is type on a path.
pub fn type_path(t: &TextLayer) -> Option<Path> {
let TextShape::Path { path, .. } = &t.shape else { return None };
let map = |q: Point| t.transform.apply(q);
let knots = path.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect();
Some(Path::new(vec![Subpath { closed: path.closed, knots, op: path.op }]))
}
/// Puts an edited [`type_path`] back into `t` (its text space), keeping where the type starts and
/// which side it runs on. It must still be one subpath with two or more points.
pub(crate) fn set_type_path(t: &mut TextLayer, edited: &Path) -> Result<()> {
let TextShape::Path { start, flip, .. } = &t.shape else { return Err(EngineError::Other("the type layer is not on a path".into())) };
let (start, flip) = (*start, *flip);
let [sub] = edited.subpaths.as_slice() else { return Err(EngineError::Other("type on a path follows one path".into())) };
if sub.knots.len() < 2 {
return Err(EngineError::Other("type on a path needs a path of two or more points".into()));
}
if sub.knots.len() > MAX_TYPE_PATH_KNOTS {
return Err(EngineError::Other("the type path has too many anchor points".into()));
}
let inv = t.transform.inverse().ok_or_else(|| EngineError::Other("the type layer's transform cannot be inverted".into()))?;
let map = |q: Point| inv.apply(q);
let knots: Vec<Knot> =
sub.knots.iter().map(|k| Knot { anchor: map(k.anchor), in_ctrl: map(k.in_ctrl), out_ctrl: map(k.out_ctrl), smooth: k.smooth }).collect();
if !knots.iter().all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|q| q.x.is_finite() && q.y.is_finite())) {
return Err(EngineError::Other("the path cannot be mapped into the type layer".into()));
}
t.shape = TextShape::Path { path: Subpath { closed: sub.closed, knots, op: sub.op }, start, flip };
Ok(())
}
fn is_path_text(s: &Session) -> std::result::Result<(), String> {
match active_text(s)?.shape {
TextShape::Path { .. } | TextShape::Area { .. } => Ok(()),
@@ -314,6 +314,80 @@ fn type_attaches_to_a_path_and_releases_it() {
assert!(matches!(text(&s, id).shape, TextShape::Path { .. }));
}
/// #9114: type on a path follows its own path when the path is edited (Direct Selection's
/// `path.*` commands with `"name": "layer"`), as Photoshop's Type Path does; the Paths list names
/// it, an edit is one undo step, and an edit that leaves no path is refused.
#[test]
fn type_follows_its_path_when_the_path_is_edited() {
let mut s = session(8);
let id = text_layer(&mut s, "Hello path");
s.edit("path", |doc, _| {
doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])]));
Ok(())
})
.unwrap();
s.execute("type.attachToPath", json!({"start": 4})).unwrap();
// In document space, the type path is where the work path was.
let path = crate::type_extra_cmds::type_path(text(&s, id)).unwrap();
let ends: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect();
assert!(ends.iter().zip([(150.0, 10.0), (150.0, 110.0)]).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6), "{ends:?}");
let listed = s.execute("path.list", json!({})).unwrap();
assert_eq!(listed["typePath"]["kind"], "typePath", "{listed}");
// Swing the path's end to the right: the type now runs down and to the right.
let before = ink(&s, id);
let r = s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 1]], "move": [120, 0]})).unwrap();
assert_eq!(r["name"], "layer");
let after = ink(&s, id);
assert!(after.width() > before.width() + 20, "{before:?} → {after:?}");
assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0), "where the type starts is kept");
// The work path it came from is untouched; Undo puts the type path back.
assert_eq!(s.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor.x, 150.0);
assert!(s.undo());
assert_eq!(ink(&s, id), before);
// An edit that would leave fewer than two points is refused and changes nothing.
assert!(s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id.0, "subpath": 0, "knot": 0})).is_err());
assert_eq!(ink(&s, id), before);
}
/// #9114: a type-on-a-path layer's vector mask is still what `"name": "layer"` edits, as on main
/// and as `path.info` reads it; `"typePath": true` edits the Type Path; `path.list` reports both.
#[test]
fn a_vector_mask_on_type_on_a_path_is_edited_not_the_type_path() {
let mut s = session(8);
let id = text_layer(&mut s, "Hello path");
s.edit("path", |doc, _| {
doc.work_path = Some(Path::new(vec![Subpath::polyline(&[(150.0, 10.0), (150.0, 110.0)])]));
Ok(())
})
.unwrap();
s.execute("type.attachToPath", json!({})).unwrap();
let rect = json!({"subpaths": [{"closed": true, "knots": [[10, 10], [200, 10], [200, 100], [10, 100]]}]});
s.execute("layer.vectorMask.add", json!({"layer": id.0, "path": rect})).unwrap();
let listed = s.execute("path.list", json!({})).unwrap();
assert_eq!((listed["layerPath"]["kind"].as_str(), listed["typePath"]["kind"].as_str()), (Some("vectorMask"), Some("typePath")), "{listed}");
let type_path = |s: &Session| crate::type_extra_cmds::type_path(text(s, id)).unwrap();
let before = type_path(&s);
let mask = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path.subpaths[0].knots[0].anchor;
s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "anchors": [[0, 0]], "move": [10, 0]})).unwrap();
assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask's corner moved");
assert_eq!(type_path(&s), before, "the Type Path stays");
s.execute("path.moveAnchors", json!({"name": "layer", "layer": id.0, "typePath": true, "anchors": [[0, 1]], "move": [20, 0]})).unwrap();
assert!((type_path(&s).subpaths[0].knots[1].anchor.x - before.subpaths[0].knots[1].anchor.x - 20.0).abs() < 1e-6, "the Type Path moved");
assert_eq!(mask(&s), photocraft_geom::Point::new(20.0, 10.0), "the mask stays");
}
/// An edit can't grow the Type Path past the cap `type.attachToPath` keeps.
#[test]
fn an_edited_type_path_keeps_the_knot_cap() {
let mut s = session(8);
let id = text_layer(&mut s, "Hi");
let knots: Vec<(f64, f64)> = (0..=MAX_TYPE_PATH_KNOTS).map(|i| (i as f64 * 0.001, 50.0)).collect();
let mut t = text(&s, id).clone();
t.shape = TextShape::Path { path: Subpath::polyline(&knots[..2]), start: 0.0, flip: false };
assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots[..MAX_TYPE_PATH_KNOTS])])).is_ok());
assert!(set_type_path(&mut t, &Path::new(vec![Subpath::polyline(&knots)])).is_err());
}
/// The Type tool's click on a path: `"at"` starts the type where the path passes nearest the
/// click, and the paragraph alignment is kept about that point, as in Photoshop.
#[test]
@@ -243,3 +243,14 @@ fn preview_options_validates_without_mutating_source() {
assert_ne!(shown.text_styles, before);
assert_eq!(doc.text_styles, before);
}
#[test]
fn style_options_take_a_family_with_the_style_picked_under_it() {
// The font menu's ">" picks a family in one of its styles: Style Options sends both.
let (mut s, _) = session("Hello");
let cs = s.execute("type.characterStyle.new", json!({"attrs": {"size": 20}, "fromSelection": false})).unwrap()["id"].as_u64().unwrap();
s.execute("type.characterStyle.set", json!({"id": cs, "attrs": {"font": "Arial", "fontStyle": "Bold Italic"}})).unwrap();
let attrs = s.execute("type.characterStyle.list", json!({})).unwrap()["styles"][1]["attrs"].clone();
assert_eq!(attrs["font_family"], "Arial", "{attrs}");
assert_eq!(attrs["font_style"], "Bold Italic", "{attrs}");
}
+1 -1
View File
@@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "List Paths",
menu: &[],
shortcut: None,
params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask)}"##,
params: r##"{} → {paths:[{name,knots,subpaths}],workPath,clippingPath,layerPath (active layer's shape path / vector mask),typePath (active type layer's Type Path, if it is on a path)}"##,
enabled: has_doc,
run: |s, _| paths_list(s),
journal: false,
+8 -1
View File
@@ -49,7 +49,8 @@ pub(super) fn paths_list(s: &Session) -> Result<Value> {
let d = s.active().ok_or(EngineError::NoDocument)?;
let doc = &d.doc;
let knots = |p: &Path| p.subpaths.iter().map(|s| s.knots.len()).sum::<usize>();
let layer = d.active_layer.and_then(|id| doc.layer(id)).and_then(|l| match &l.content {
let active = d.active_layer.and_then(|id| doc.layer(id));
let layer = active.and_then(|l| match &l.content {
LayerContent::Shape(sh) => Some(json!({ "kind": "shape", "layer": l.id.0, "name": format!("{} Shape Path", l.name), "knots": knots(&sh.path) })),
_ => {
l.vector_mask.as_ref().map(|v| json!({ "kind": "vectorMask", "layer": l.id.0, "name": format!("{} Vector Mask", l.name), "knots": knots(&v.path) }))
@@ -60,6 +61,12 @@ pub(super) fn paths_list(s: &Session) -> Result<Value> {
"workPath": doc.work_path.as_ref().map(|p| json!({ "knots": knots(p), "subpaths": p.subpaths.len() })),
"clippingPath": doc.clipping_path.as_ref().map(|c| json!({ "name": c.name, "flatness": c.flatness })),
"layerPath": layer,
// Type on a path: Photoshop's Type Path, which Direct Selection edits (#9114).
"typePath": active.and_then(|l| match &l.content {
LayerContent::Text(t) => crate::type_extra_cmds::type_path(t)
.map(|p| json!({ "kind": "typePath", "layer": l.id.0, "name": format!("{} Type Path", l.name), "knots": knots(&p) })),
_ => None,
}),
}))
}
+1 -1
View File
@@ -338,7 +338,7 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result<Value> {
let id = s.edit("New Shape Layer", |doc, active| {
refresh_shape(doc, &mut sh);
let name = name.unwrap_or_else(|| doc.next_layer_name(default_name(kind)));
let id = doc.insert_above(*active, Layer::new(name, LayerContent::Shape(sh)));
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Shape(sh)), crate::layer_place::Place::AutoEditable);
*active = Some(id);
Ok(id)
})?;
+10 -3
View File
@@ -127,7 +127,7 @@ fn new_blank(s: &mut Session, _p: &Value) -> Result<Value> {
let name = doc.next_layer_name("Video Layer");
let mut l = Layer::raster(name, fmt);
l.video = Some(VideoData::new(frames, fps));
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable);
*active = Some(id);
sync(doc);
Ok(id)
@@ -366,8 +366,13 @@ fn new_from_file(s: &mut Session, p: &Value) -> Result<Value> {
let mut v = VideoData::new(frames, fps);
v.original_frames = Some(v.frames.clone());
v.source = photocraft_doc::VideoSource::File { path: path.clone() };
// The first frame is the layer's content before it is placed: an active artboard takes
// the layer only when its content is on the board, as `frames_to_layers` does.
if let (Some(first), LayerContent::Raster(surf)) = (v.frames.first(), &mut l.content) {
*surf = first.clone();
}
l.video = Some(v);
let id = doc.insert_above(*active, l);
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::AutoEditable);
*active = Some(id);
sync(doc);
Ok(id)
@@ -438,12 +443,14 @@ fn frames_to_layers(s: &mut Session, p: &Value) -> Result<Value> {
let n = frames.len();
s.edit("Video Frames to Layers", |doc, active| {
let mut above = *active;
let mut place = crate::layer_place::Place::AutoEditable;
for (i, f) in frames.into_iter().enumerate() {
let mut l = Layer::raster(format!("Frame {}", i + 1), fmt);
if let LayerContent::Raster(surf) = &mut l.content {
*surf = f;
}
above = Some(doc.insert_above(above, l));
above = Some(crate::layer_place::insert_new(doc, above, l, place));
place = crate::layer_place::Place::Above;
}
*active = above;
Ok(())
+15
View File
@@ -83,6 +83,21 @@ fn new_video_layer_from_image_sequence() {
assert!(s.active().unwrap().doc.timeline.as_ref().unwrap().duration >= 3);
}
/// CodeRabbit on #9775: footage that isn't on the active artboard stays out of it, as a placed
/// image does; the board would clip it. Before, the layer was placed while still empty.
#[test]
fn footage_off_the_active_artboard_stays_out_of_it() {
let dir = tmpdir("board");
write_png(&format!("{dir}/f01.png"), 16, 12, "#ff0000");
write_png(&format!("{dir}/f02.png"), 16, 12, "#00ff00");
let mut s = session();
let board = s.execute("layer.new.artboard", json!({"rect": [0, 0, 4, 4]})).unwrap();
assert!(board["layer"].as_u64().is_some(), "{board}");
let r = s.execute("layer.videoLayers.newVideoLayerFromFile", json!({"path": dir})).unwrap();
let id = LayerId(r["layer"].as_u64().unwrap());
assert_eq!(s.active().unwrap().doc.artboard_of(id), None, "the footage is centred off the board");
}
#[test]
fn frames_to_layers_and_render_video() {
let dir = tmpdir("ftl");
+1 -1
View File
@@ -252,7 +252,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result<Value> {
let on = layer.or(*active);
let id = if new_layer {
let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format());
let nid = doc.insert_above(on, l);
let nid = crate::layer_place::insert_new(doc, on, l, crate::layer_place::Place::AutoEditable);
*active = Some(nid);
nid
} else {
+264
View File
@@ -0,0 +1,264 @@
//! The options of Photoshop's New Group dialog (Name, Color, Mode, Opacity), shared by
//! Layer › New › Group… (`layer.new.group`) and Group from Layers (`layer.new.groupFromLayers`,
//! `layer.groupLayers`), so the dialog's OK is a single history step.
use photocraft_color::BlendMode;
use photocraft_doc::{LabelColor, Layer};
use serde_json::Value;
use crate::{EngineError, Result};
/// New Group options parsed from command params; an absent (or `null`) key keeps the default.
#[derive(Debug, Default)]
pub(crate) struct GroupOptions {
/// `None` (or an empty name) takes the next "Group N".
pub name: Option<String>,
color: Option<LabelColor>,
blend: Option<BlendMode>,
opacity: Option<f32>,
}
impl GroupOptions {
/// Parses `name`, `color` (a layer colour id), `mode` (a blend mode, Pass Through included)
/// and `opacity` (percent, clamped to 0..100). Validates everything before any edit runs.
pub(crate) fn parse(cmd: &str, p: &Value) -> Result<Self> {
let bad = |msg: &str| EngineError::BadParams { cmd: cmd.into(), msg: msg.into() };
let get = |key: &str| p.get(key).filter(|v| !v.is_null());
let name = match get("name") {
None => None,
Some(v) => Some(v.as_str().ok_or_else(|| bad("`name` must be a string"))?.to_string()).filter(|n| !n.trim().is_empty()),
};
let color = match get("color") {
None => None,
Some(v) => Some(v.as_str().and_then(LabelColor::from_id).ok_or_else(|| {
bad("`color` must be a layer colour id (none, red, orange, yellow, green, seafoam, blue, indigo, magenta, fuchsia, violet, gray)")
})?),
};
let blend = match get("mode") {
None => None,
Some(v) => Some(
v.as_str()
.and_then(crate::commands::blend_from_str)
.ok_or_else(|| bad("`mode` must be a blend mode such as \"passThrough\" or \"multiply\""))?,
),
};
let opacity = match get("opacity") {
None => None,
Some(v) => {
let o = v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad("`opacity` must be a number (percent, 0..100)"))?;
Some((o.clamp(0.0, 100.0) / 100.0) as f32)
}
};
Ok(Self { name, color, blend, opacity })
}
/// Sets the mode, opacity and colour of a new `group`. A colour also reaches every layer inside
/// it, as Layer › Layer Color does on a group; "No Color" leaves the layers' own colours alone.
pub(crate) fn apply(&self, group: &mut Layer) {
if let Some(blend) = self.blend {
group.blend = blend;
}
if let Some(opacity) = self.opacity {
group.opacity = opacity;
}
match self.color {
Some(LabelColor::None) | None => {}
Some(color) => {
// Explicit stack: documents can nest groups deeply.
let mut stack = vec![group];
while let Some(l) = stack.pop() {
l.label = color;
if let Some(children) = l.children_mut() {
stack.extend(children.iter_mut());
}
}
}
}
}
}
/// `layer.new.group`'s `position`: `below` (the Layers panel's ⌘/Ctrl-click) or `above` (the default).
pub(crate) fn below(cmd: &str, p: &Value) -> Result<bool> {
match p.get("position").filter(|v| !v.is_null()) {
None => Ok(false),
Some(v) => match v.as_str() {
Some("above") => Ok(false),
Some("below") => Ok(true),
_ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "`position` must be above or below".into() }),
},
}
}
#[cfg(test)]
mod tests {
use photocraft_color::BlendMode;
use photocraft_doc::{Document, LabelColor, Layer, LayerContent, LayerId};
use serde_json::{Value, json};
use crate::Session;
/// Background, then `A` and `B` (`B` active).
fn session() -> (Session, LayerId, LayerId) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap());
let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap());
(s, a, b)
}
fn id(v: Value) -> LayerId {
LayerId(v["layer"].as_u64().unwrap())
}
fn doc(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn layer(s: &Session, id: LayerId) -> &Layer {
doc(s).layer(id).unwrap()
}
fn expanded(s: &Session, id: LayerId) -> bool {
matches!(&layer(s, id).content, LayerContent::Group(g) if g.expanded)
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.entries().len()
}
fn top(s: &Session) -> Vec<LayerId> {
doc(s).layers.iter().map(|l| l.id).collect()
}
#[test]
fn new_group_defaults_and_dialog_options() {
let (mut s, _, _) = session();
let g = id(s.execute("layer.new.group", json!({})).unwrap());
let l = layer(&s, g);
assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Group 1", BlendMode::PassThrough, 1.0, LabelColor::None));
assert!(expanded(&s, g), "an empty new group stays open");
let before = steps(&s);
let g = id(s.execute("layer.new.group", json!({"name": "Sky", "color": "red", "mode": "multiply", "opacity": 40})).unwrap());
let l = layer(&s, g);
assert_eq!((l.name.as_str(), l.blend, l.label), ("Sky", BlendMode::Multiply, LabelColor::Red));
assert!((l.opacity - 0.4).abs() < 1e-6);
assert_eq!(steps(&s), before + 1, "the dialog's OK is one history step");
// Labels as shown in the dialog work too; opacity is clamped to 0..100 %, a blank name is "Group N".
let g = id(s.execute("layer.new.group", json!({"name": " ", "mode": "Linear Dodge (Add)", "opacity": 250})).unwrap());
let l = layer(&s, g);
assert_eq!((l.name.as_str(), l.blend, l.opacity), ("Group 2", BlendMode::LinearDodge, 1.0));
let g = id(s.execute("layer.new.group", json!({"opacity": -5, "name": null, "color": null, "mode": null, "position": null})).unwrap());
assert_eq!(layer(&s, g).opacity, 0.0);
}
#[test]
fn group_from_layers_is_collapsed_and_takes_the_dialog_options() {
let (mut s, a, b) = session();
s.execute("layer.setLabelColor", json!({"layer": a.0, "color": "red"})).unwrap();
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
let before = steps(&s);
let g = id(s.execute("layer.new.groupFromLayers", json!({"name": "Pair", "color": "none", "mode": "normal", "opacity": 50})).unwrap());
assert_eq!(steps(&s), before + 1, "one history step");
let l = layer(&s, g);
assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Pair", BlendMode::Normal, 0.5, LabelColor::None));
assert!(!expanded(&s, g), "Photoshop shows a group made from layers closed");
assert_eq!(layer(&s, a).label, LabelColor::Red, "No Color leaves the layers' own colours alone");
let inspect = s.execute("document.inspect", json!({})).unwrap();
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == json!(g.0)).unwrap().clone();
assert_eq!(row["expanded"], false, "document.inspect reports it");
// Undo removes the group; redo brings it back closed.
s.undo();
assert!(doc(&s).layer(g).is_none());
s.redo();
assert!(!expanded(&s, g));
// ⌘G with a colour labels the group and every layer in it, like Layer › Layer Color.
s.undo();
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
let g = id(s.execute("layer.groupLayers", json!({"color": "green"})).unwrap());
assert!(!expanded(&s, g));
for l in [g, a, b] {
assert_eq!(layer(&s, l).label, LabelColor::Green);
}
}
#[test]
fn below_puts_the_new_group_under_the_active_layer() {
let (mut s, a, b) = session();
let bg = top(&s)[0];
let g = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap());
assert_eq!(top(&s), vec![bg, a, g, b]);
// Inside a group it stays inside, under the active layer.
s.execute("layer.select", json!({"layer": b.0})).unwrap();
let outer = id(s.execute("layer.groupLayers", json!({})).unwrap());
s.execute("layer.select", json!({"layer": b.0})).unwrap();
let inner = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap());
let children: Vec<LayerId> = layer(&s, outer).children().unwrap().iter().map(|l| l.id).collect();
assert_eq!(children, vec![inner, b]);
// Nothing goes under the Background: the group goes above it instead.
s.execute("layer.select", json!({"layer": bg.0})).unwrap();
let g2 = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap());
assert_eq!(top(&s)[..2], [bg, g2]);
// With no active layer it goes to the top, like a plain New Group.
s.execute("select.deselectLayers", json!({})).unwrap();
let g3 = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap());
assert_eq!(top(&s).last(), Some(&g3));
}
/// A group added inside a clipping mask (⌘-click under a clipped layer, or a plain New Group
/// on the base) joins the mask, as in Photoshop: the clipped layers keep their base and stay
/// visible, and nothing needs recompositing.
#[test]
fn a_group_added_inside_a_clipping_mask_joins_it() {
let (mut s, a, b) = session();
s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap();
s.execute("layer.select", json!({"layer": b.0})).unwrap();
let g = id(s.execute("layer.new.group", json!({"position": "below"})).unwrap());
assert_eq!(top(&s)[1..], [a, g, b]);
assert!(layer(&s, g).clipped, "under a clipped layer the group is clipped too");
assert_eq!(s.active().unwrap().last_damage, Some(photocraft_geom::Rect::EMPTY), "B still clips to A");
// On the base itself: the new group goes between A and its clipped layers.
s.undo();
s.execute("layer.select", json!({"layer": a.0})).unwrap();
let g = id(s.execute("layer.new.group", json!({})).unwrap());
assert_eq!(top(&s)[1..], [a, g, b]);
assert!(layer(&s, g).clipped);
// Outside a clipping mask nothing changes.
s.execute("layer.select", json!({"layer": b.0})).unwrap();
let g = id(s.execute("layer.new.group", json!({})).unwrap());
assert!(!layer(&s, g).clipped);
}
#[test]
fn bad_options_fail_without_touching_the_document() {
let (mut s, a, b) = session();
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
for cmd in ["layer.new.group", "layer.new.groupFromLayers", "layer.groupLayers"] {
let mut bad = vec![
json!({"name": 7}),
json!({"color": 5}),
json!({"color": "pink"}),
json!({"color": "Red"}),
json!({"mode": ""}),
json!({"mode": 3}),
json!({"mode": "sparkle"}),
json!({"opacity": "x"}),
json!({"opacity": [50]}),
];
if cmd == "layer.new.group" {
bad.push(json!({"position": "yes"}));
}
for p in bad {
let before = (doc(&s).clone(), s.active().unwrap().revision, steps(&s));
assert!(s.execute(cmd, p.clone()).is_err(), "{cmd} {p} must be refused");
assert_eq!((doc(&s).clone(), s.active().unwrap().revision, steps(&s)), before, "{cmd} {p} changed nothing");
}
// A huge but finite opacity clamps to 100 % instead of failing.
let g = id(s.execute(cmd, json!({"opacity": f64::MAX})).unwrap());
assert_eq!(layer(&s, g).opacity, 1.0);
s.undo();
}
}
}
+29 -16
View File
@@ -331,14 +331,25 @@ fn independent_of_document(id: &str) -> bool {
}
#[cfg(not(target_arch = "wasm32"))]
fn read_path(path: &str) -> Result<Vec<u8>> {
// Bounded reads, and a clear error for a file larger than memory (#375).
photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
fn import_path(
name: &str,
path: &str,
opts: &photocraft_io::ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> {
// Bounded reads, and a clear error for a file larger than memory (#375); a PSD/PSB is
// parsed from the open file instead of being read whole.
photocraft_io::import_file_for_open_with(name, std::path::Path::new(path), opts, ctl)
}
#[cfg(target_arch = "wasm32")]
fn read_path(path: &str) -> Result<Vec<u8>> {
Err(EngineError::Other(format!("cannot open paths on the web: {path}")))
fn import_path(
_: &str,
path: &str,
_: &photocraft_io::ImportOptions,
_: &photocraft_raster::Interrupt,
) -> std::result::Result<(photocraft_io::ImportResult, bool), photocraft_io::IoError> {
Err(photocraft_io::IoError::Read(format!("cannot open paths on the web: {path}")))
}
/// Run a job-capable command's heavy part. `work` runs on a worker thread when the command was
@@ -555,17 +566,19 @@ impl Session {
false,
move |ctx| {
ctx.progress(0.0, "Reading");
let bytes = match source {
OpenSource::Bytes(b) => b,
OpenSource::Path(p) => Arc::new(read_path(&p)?),
};
ctx.check()?;
ctx.progress(0.02, "Decoding");
let imported =
ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl)).map_err(|e| match e {
photocraft_io::IoError::Cancelled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
})?;
let imported = match source {
OpenSource::Bytes(bytes) => {
ctx.check()?;
ctx.progress(0.02, "Decoding");
ctx.stage(0.02, 0.95, "Decoding", |ctl| photocraft_io::import_for_open_with(&name_w, &bytes, &opts, ctl))
}
// A PSD/PSB is decoded straight from the file, which is never read whole.
OpenSource::Path(p) => ctx.stage(0.0, 0.95, "Decoding", |ctl| import_path(&name_w, &p, &opts, ctl)),
}
.map_err(|e| match e {
photocraft_io::IoError::Cancelled => EngineError::Cancelled,
e => EngineError::Other(e.to_string()),
})?;
ctx.progress(0.95, "Preparing layers");
warm_layer_bounds(&imported.0.document, || ctx.check())?;
// Type layers need the shared text engine, whose first use waits for the
+113
View File
@@ -0,0 +1,113 @@
//! Where a new layer goes, as in Photoshop. Above the active layer, or as the top layer inside the
//! active group when that group is open (an artboard, open or closed, when the layer's content is
//! on the board); with nothing active, at the top of the stack. A layer that lands inside a clipping mask joins it: it is clipped when the layer
//! just above its slot is clipped, the rule Photoshop follows on every insert (#2203), so a new
//! layer (or group) between a base and its clipped layers never becomes their (empty) base.
//! Artboards are never nested or clipped: a new one goes to the top level.
use photocraft_doc::{Document, Layer, LayerContent, LayerId, LayerPath, MAX_GROUP_DEPTH};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Place {
/// New Layer, New Group, new adjustment and fill layers: inside the anchor when it is an open
/// group (or an artboard the content is on), else directly above it. A locked group takes the
/// layer too, as in Photoshop (checked with Lock All): the layer is locked through it.
Auto,
/// [`Place::Auto`] for a layer that is edited right after it is made (Type, Shape, Place's
/// transform box, Paste, the Gradient tool's live gradient, video layers, Render and Vanishing
/// Point drawing, a new frame): never inside a group with a lock of its own (all, pixels,
/// transparency or position) that would refuse that edit; the layer goes above the group.
AutoEditable,
/// Directly above the anchor, never inside it: a layer made from another layer, or the second
/// and later of several new layers.
Above,
/// Directly below the anchor (⌘-click on the Layers panel's New Layer or New Group button). Never
/// under the Background, where it goes above instead.
Below,
}
/// The slot `layer` would take: its parent's path (empty for the root) and its index among the
/// parent's children (bottom to top). A missing or stale `anchor` means the top of the stack.
pub fn insertion_point(doc: &Document, anchor: Option<LayerId>, layer: &Layer, place: Place) -> (LayerPath, usize) {
let root_top = (Vec::new(), doc.layers.len());
let Some(path) = anchor.and_then(|a| doc.path_of(a)) else { return root_top };
// An artboard stays at the top level: beside the anchor's top-level layer.
let path = if layer.artboard().is_some() { path.get(..1).map(<[usize]>::to_vec).unwrap_or_default() } else { path };
let (Some((&k, parent)), Some(target)) = (path.split_last(), doc.layer_at(&path)) else { return root_top };
let locks = &target.locks;
let editable = !(locks.all || locks.pixels || locks.transparency || locks.position);
match place {
Place::Auto | Place::AutoEditable if takes_new_layers(target, path.len(), layer) && (place == Place::Auto || editable) => {
(path.clone(), target.children().map_or(0, <[Layer]>::len))
}
Place::Below if crate::background_cmds::background_id(doc) != Some(target.id) => (parent.to_vec(), k),
_ => (parent.to_vec(), k + 1),
}
}
/// Inserts `layer` at its [`insertion_point`], clipped when it lands inside a clipping mask (a
/// flag it already has is kept unless nothing is below it to clip to; an artboard is never
/// clipped); returns its id. Never fails: a slot that can't be reached puts
/// the layer on top of the stack.
pub fn insert_new(doc: &mut Document, anchor: Option<LayerId>, mut layer: Layer, place: Place) -> LayerId {
let id = layer.id;
let (parent, index) = insertion_point(doc, anchor, &layer, place);
let sib = if parent.is_empty() { Some(&mut doc.layers) } else { doc.layer_at_mut(&parent).and_then(Layer::children_mut) };
if let Some(sib) = sib {
let mut index = index.min(sib.len());
if layer.artboard().is_some() {
// Past the clipped layers above the slot, so their clipping mask stays whole.
while sib.get(index).is_some_and(|above| above.clipped) {
index += 1;
}
layer.clipped = false;
} else if sib.get(index).is_some_and(|above| above.clipped) {
layer.clipped = true;
} else if index == 0 {
// Nothing below to clip to (a copied clipped layer pasted into an empty group).
layer.clipped = false;
}
sib.insert(index, layer);
} else {
doc.layers.push(layer);
}
id
}
/// Does the group `target` at depth `depth` (its path length) take a new `layer` as its top
/// child? An open group or an artboard does, locked or not (Photoshop puts a new layer inside a
/// group locked with Lock All), unless nesting would pass [`MAX_GROUP_DEPTH`]. An artboard
/// takes a layer with content only when that content is centred on the board, as callers place
/// it for the canvas (Place, Paste, a Type or Shape click): elsewhere the board would clip it.
fn takes_new_layers(target: &Layer, depth: usize, layer: &Layer) -> bool {
let LayerContent::Group(g) = &target.content else { return false };
let on_board = |rect: photocraft_geom::Rect| {
crate::layer_multi_cmds::layer_bounds(layer).is_none_or(|b| {
let (cx, cy) = (b.x0 / 2 + b.x1 / 2, b.y0 / 2 + b.y1 / 2);
rect.contains(cx, cy)
})
};
let open = match &g.artboard {
Some(board) => on_board(board.rect),
None => g.expanded,
};
open && layer.artboard().is_none() && depth + subtree_depth(layer) <= MAX_GROUP_DEPTH
}
/// Group nesting inside `layer` itself: 0 for a layer or an empty group, as
/// [`Document::max_group_depth`] counts it. Explicit stack: pasted groups can be deep.
fn subtree_depth(layer: &Layer) -> usize {
let mut max = 0;
let mut stack: Vec<(&Layer, usize)> = vec![(layer, 0)];
while let Some((l, depth)) = stack.pop() {
if let Some(children) = l.children().filter(|c| !c.is_empty()) {
max = max.max(depth + 1);
stack.extend(children.iter().map(|c| (c, depth + 1)));
}
}
max
}
#[cfg(test)]
#[path = "layer_place_tests.rs"]
mod tests;
+357
View File
@@ -0,0 +1,357 @@
use photocraft_doc::{Document, Layer, LayerContent, LayerId, MAX_GROUP_DEPTH};
use serde_json::{Value, json};
use super::*;
use crate::Session;
/// Background, then `A` and `B` (`B` active).
fn session() -> (Session, LayerId, LayerId) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
let a = id(s.execute("layer.new.layer", json!({"name": "A"})).unwrap());
let b = id(s.execute("layer.new.layer", json!({"name": "B"})).unwrap());
(s, a, b)
}
fn id(v: Value) -> LayerId {
LayerId(v["layer"].as_u64().unwrap())
}
fn doc(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn top(s: &Session) -> Vec<LayerId> {
doc(s).layers.iter().map(|l| l.id).collect()
}
fn children(s: &Session, group: LayerId) -> Vec<LayerId> {
doc(s).layer(group).unwrap().children().unwrap().iter().map(|l| l.id).collect()
}
fn set_expanded(s: &mut Session, group: LayerId, expanded: bool) {
s.execute("layer.setExpanded", json!({"layer": group.0, "expanded": expanded})).unwrap();
}
fn select(s: &mut Session, layer: LayerId) {
s.execute("layer.select", json!({"layer": layer.0})).unwrap();
}
#[test]
fn a_new_layer_goes_inside_an_open_active_group_and_above_a_closed_one() {
let (mut s, a, b) = session();
select(&mut s, a);
let g = id(s.execute("layer.groupLayers", json!({})).unwrap());
// A group made from layers starts closed: the new layer goes above it.
let above = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(top(&s)[1..], [g, above, b]);
assert_eq!(children(&s, g), vec![a]);
// Opened, it takes the new layer as its top layer.
select(&mut s, g);
set_expanded(&mut s, g, true);
let inside = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(children(&s, g), vec![a, inside]);
// A new empty group is open, so the next new layer goes into it (New Group, then New Layer).
s.execute("select.deselectLayers", json!({})).unwrap();
let empty = id(s.execute("layer.new.group", json!({})).unwrap());
let first = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(children(&s, empty), vec![first]);
// The same goes for the other new layers: adjustment, fill, type and shape layers.
select(&mut s, empty);
for (cmd, p) in [
("layer.newAdjustmentLayer.invert", json!({})),
("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})),
("type.create", json!({"x": 2, "y": 10, "text": "Hi"})),
("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})),
] {
select(&mut s, empty);
let l = id(s.execute(cmd, p).unwrap());
assert_eq!(children(&s, empty).last(), Some(&l), "{cmd} goes inside the open group");
}
}
#[test]
fn artboards_and_locked_groups_take_new_layers() {
let (mut s, _, b) = session();
let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 16, 16]})).unwrap());
set_expanded(&mut s, board, false);
select(&mut s, board);
let l = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(doc(&s).artboard_of(l), Some(board), "an artboard takes the layer even when closed");
// Photoshop puts a new layer inside an open group locked with Lock All too; the layer is
// locked through the group.
select(&mut s, b);
let g = id(s.execute("layer.new.group", json!({})).unwrap());
s.execute("layer.setProps", json!({"layer": g.0, "locks": {"all": true}})).unwrap();
select(&mut s, g);
let inside = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(children(&s, g), vec![inside]);
assert!(doc(&s).effective_locks(inside).all);
}
#[test]
fn below_puts_the_new_layer_under_the_active_layer() {
let (mut s, a, b) = session();
let bg = top(&s)[0];
let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap());
assert_eq!(top(&s), vec![bg, a, l, b]);
// Never under the Background, and never inside an open group.
select(&mut s, bg);
let l2 = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap());
assert_eq!(top(&s)[..2], [bg, l2]);
let g = id(s.execute("layer.new.group", json!({})).unwrap());
let l3 = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap());
assert!(children(&s, g).is_empty());
let root = top(&s);
assert_eq!(root.iter().position(|x| *x == l3).unwrap() + 1, root.iter().position(|x| *x == g).unwrap());
assert!(s.execute("layer.new.layer", json!({"position": "yes"})).is_err());
}
/// The clipping rule Photoshop follows on every insert (#2203): a new layer is clipped exactly
/// when the layer just above its slot is clipped.
#[test]
fn a_new_layer_joins_the_clipping_mask_it_lands_in() {
let (mut s, base, c1) = session();
let c2 = id(s.execute("layer.new.layer", json!({"name": "C2"})).unwrap());
for c in [c1, c2] {
s.execute("layer.setProps", json!({"layer": c.0, "clipped": true})).unwrap();
}
let clipped = |s: &Session, l: LayerId| doc(s).layer(l).unwrap().clipped;
// On the base: between the base and its clipped layers.
select(&mut s, base);
let on_base = id(s.execute("layer.new.layer", json!({})).unwrap());
assert!(clipped(&s, on_base));
// In the middle of the chain.
select(&mut s, c1);
let mid = id(s.execute("layer.new.layer", json!({})).unwrap());
assert!(clipped(&s, mid));
// Above the top clipped layer it is outside the mask.
select(&mut s, c2);
let above = id(s.execute("layer.new.layer", json!({})).unwrap());
assert!(!clipped(&s, above));
// ⌘-click New Layer under a clipped layer joins it too; under the base it does not.
select(&mut s, c2);
let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap());
assert!(clipped(&s, l));
select(&mut s, base);
let l = id(s.execute("layer.new.layer", json!({"position": "below"})).unwrap());
assert!(!clipped(&s, l));
// A group joins as well (Photoshop clips groups too), and so do the other new layers.
select(&mut s, base);
let l = id(s.execute("layer.new.group", json!({})).unwrap());
assert!(clipped(&s, l));
select(&mut s, base);
let l = id(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap());
assert!(clipped(&s, l));
// A layer made from a clipped layer (Layer via Copy) stays in its mask.
select(&mut s, c1);
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();
s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
let l = id(s.execute("layer.new.layerViaCopy", json!({})).unwrap());
assert!(clipped(&s, l));
}
#[test]
fn a_pasted_layer_goes_into_an_open_group() {
let (mut s, a, _) = session();
// A whole pixel layer on the clipboard (no selection).
select(&mut s, a);
s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
s.execute("edit.copy", json!({})).unwrap();
let into = id(s.execute("layer.new.group", json!({"name": "Into"})).unwrap());
let pasted = id(s.execute("edit.paste", json!({})).unwrap());
assert_eq!(children(&s, into), vec![pasted]);
}
/// The second and later of several new layers stack above the first, even when the first is an
/// open group: it must not swallow them.
#[test]
fn later_layers_of_a_batch_go_above_the_first() {
let (s, _, b) = session();
let mut d = doc(&s).clone();
let first = insert_new(&mut d, Some(b), Layer::group("open", vec![]), Place::Auto);
let next = Layer::raster("next", d.pixel_format());
let second = insert_new(&mut d, Some(first), next, Place::Above);
let root: Vec<LayerId> = d.layers.iter().map(|l| l.id).collect();
assert_eq!(root[root.len() - 2..], [first, second]);
assert!(d.layer(first).unwrap().children().unwrap().is_empty());
}
#[test]
fn nesting_stops_at_the_group_depth_limit() {
let mut doc = Document::new("deep", photocraft_doc::Size::new(8, 8), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
// A chain of open groups as deep as allowed, with a layer at the bottom.
let mut inner = Layer::raster("deep", doc.pixel_format());
let deep_id = inner.id;
let mut ids = Vec::new();
for i in 0..MAX_GROUP_DEPTH {
let g = Layer::group(format!("g{i}"), vec![inner]);
ids.push(g.id);
inner = g;
}
doc.layers.push(inner);
assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH);
let innermost = *ids.first().unwrap();
// A plain layer fits beside `deep`, inside the innermost group (the depth stays the same)…
let layer = Layer::raster("fits", doc.pixel_format());
let l = insert_new(&mut doc, Some(innermost), layer, Place::Auto);
assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH);
assert!(doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == l));
// …but a group with a layer in it would go one deeper: it goes beside the group instead.
let nested = Layer::group("nested", vec![Layer::raster("x", doc.pixel_format())]);
let n = insert_new(&mut doc, Some(innermost), nested, Place::Auto);
assert_eq!(doc.max_group_depth(), MAX_GROUP_DEPTH);
assert!(!doc.layer(innermost).unwrap().children().unwrap().iter().any(|c| c.id == n));
assert!(doc.layer(deep_id).is_some());
}
#[test]
fn a_missing_or_stale_anchor_means_the_top_of_the_stack() {
let (s, _, _) = session();
let mut d = doc(&s).clone();
for anchor in [None, Some(LayerId(u64::MAX))] {
for place in [Place::Auto, Place::Above, Place::Below] {
let layer = Layer::raster("x", d.pixel_format());
let l = insert_new(&mut d, anchor, layer, place);
assert_eq!(d.layers.last().map(|x| x.id), Some(l), "{anchor:?} {place:?}");
}
}
assert!(matches!(d.layers.last().unwrap().content, LayerContent::Raster(_)));
}
/// Any lock on an open group still lets New Layer, New Group and new adjustment and fill layers in,
/// as in Photoshop (checked with Lock All). A layer that is edited right after it is made (Type,
/// Shape, Paste, Render…) goes above a group whose lock would refuse that edit,
/// so it never comes out locked.
#[test]
fn locked_groups_take_new_layers_but_not_the_ones_edited_at_once() {
for locks in [json!({"all": true}), json!({"pixels": true}), json!({"transparency": true}), json!({"position": true})] {
let (mut s, _, b) = session();
select(&mut s, b);
s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
s.execute("select.all", json!({})).unwrap();
s.execute("edit.copy", json!({})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
let g = id(s.execute("layer.new.group", json!({})).unwrap());
s.execute("layer.setProps", json!({"layer": g.0, "locks": locks})).unwrap();
for (cmd, p) in [
("layer.new.layer", json!({})),
("layer.new.group", json!({})),
("layer.newAdjustmentLayer.invert", json!({})),
("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})),
] {
select(&mut s, g);
let l = id(s.execute(cmd, p).unwrap());
assert_eq!(children(&s, g).last(), Some(&l), "{cmd} goes inside the group locked with {locks}");
}
for (cmd, p) in [
("type.create", json!({"x": 2, "y": 10, "text": "Hi"})),
("shape.create", json!({"kind": "rect", "rect": [1, 1, 5, 5]})),
("edit.paste", json!({})),
("filter.render.tree", json!({})),
("gradient.fill.create", json!({"from": [0, 0], "to": [16, 16]})),
] {
select(&mut s, g);
let l = id(s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd} with {locks}: {e}")));
assert!(!children(&s, g).contains(&l), "{cmd} stays out of the group locked with {locks}");
assert_eq!(top(&s).iter().position(|x| *x == l), top(&s).iter().position(|x| *x == g).map(|i| i + 1), "{cmd} directly above the group");
assert!(!doc(&s).effective_locks(l).any(), "{cmd}: the new layer is not locked");
if cmd == "filter.render.tree" {
assert!(doc(&s).layer(l).unwrap().surface().unwrap().tile_count() > 0, "Render drew the tree with {locks}");
}
}
}
// An open group inside a locked one still takes New Layer (the lock reaches it through the outer group).
let (mut s, _, b) = session();
select(&mut s, b);
let outer = id(s.execute("layer.new.group", json!({})).unwrap());
let inner = id(s.execute("layer.new.group", json!({})).unwrap());
assert_eq!(children(&s, outer), vec![inner]);
s.execute("layer.setProps", json!({"layer": outer.0, "locks": {"pixels": true}})).unwrap();
select(&mut s, inner);
let plain = id(s.execute("layer.new.layer", json!({})).unwrap());
assert_eq!(children(&s, inner), vec![plain]);
}
/// Stamp Visible goes directly above an open active group, never inside it: the stamp is the
/// composite already, and inside it the group's opacity, mode or mask would apply to it again.
/// With a layer inside a group active, it still lands above that layer, inside the group.
#[test]
fn stamp_visible_goes_above_an_open_group() {
let (mut s, a, b) = session();
select(&mut s, a);
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
let g = id(s.execute("layer.groupLayers", json!({})).unwrap());
set_expanded(&mut s, g, true);
s.execute("layer.setProps", json!({"layer": g.0, "opacity": 0.5})).unwrap();
select(&mut s, g);
let stamp = id(s.execute("layer.stampVisible", json!({})).unwrap());
assert_eq!(children(&s, g), vec![a], "the stamp stays out of the group");
assert_eq!(top(&s)[1..], [g, stamp, b]);
// A layer inside the group active: the stamp goes above it, inside the group.
select(&mut s, a);
let inside = id(s.execute("layer.stampVisible", json!({})).unwrap());
assert_eq!(children(&s, g), vec![a, inside]);
}
/// An artboard takes a new layer whose content is centred on it, and a new empty layer; content
/// placed elsewhere (Place and Paste centre on the canvas) stays at the top level instead of
/// being clipped away by the board.
#[test]
fn an_artboard_takes_only_content_that_is_on_it() {
let (mut s, _, _) = session();
let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap());
let mut d = doc(&s).clone();
let raster = |d: &Document, r: photocraft_geom::Rect| {
let mut l = Layer::raster("content", d.pixel_format());
l.surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]);
l
};
let on = raster(&d, photocraft_geom::Rect::new(1, 1, 5, 5));
let on = insert_new(&mut d, Some(board), on, Place::Auto);
assert_eq!(d.artboard_of(on), Some(board));
let off = raster(&d, photocraft_geom::Rect::new(10, 10, 16, 16));
let off = insert_new(&mut d, Some(board), off, Place::Auto);
assert_eq!(d.artboard_of(off), None);
let root: Vec<LayerId> = d.layers.iter().map(|l| l.id).collect();
assert_eq!(root.iter().position(|x| *x == off), root.iter().position(|x| *x == board).map(|i| i + 1));
}
/// An artboard is never nested or clipped: a copied board goes beside the anchor's top-level
/// layer, even after a first copy went into a group, and never joins a clipping mask.
#[test]
fn artboards_stay_at_the_top_level_and_unclipped() {
let (mut s, a, b) = session();
let board = id(s.execute("layer.new.artboard", json!({"rect": [0, 0, 8, 8]})).unwrap());
s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap();
let mut d = doc(&s).clone();
let copy = d.layer(board).unwrap().duplicate();
// On a clipping base: at the top level above its clipping mask (B keeps A as its base), not
// clipped.
let c = insert_new(&mut d, Some(a), copy.duplicate(), Place::Auto);
let root: Vec<LayerId> = d.layers.iter().map(|l| l.id).collect();
let at = |id: LayerId| root.iter().position(|x| *x == id).unwrap();
assert_eq!((at(b), at(c)), (at(a) + 1, at(a) + 2));
assert!(!d.layer(c).unwrap().clipped);
// After a layer that went into an open group: beside the group, not inside it.
let g = insert_new(&mut d, Some(a), Layer::group("open", vec![]), Place::Above);
let first = Layer::raster("first", d.pixel_format());
let first = insert_new(&mut d, Some(g), first, Place::Auto);
assert!(d.layer(g).unwrap().children().unwrap().iter().any(|l| l.id == first));
let second = insert_new(&mut d, Some(first), copy, Place::Above);
assert!(d.layers.iter().any(|l| l.id == second), "the board is not nested in the group");
assert_eq!(d.artboards().len(), 3);
}
/// A copied clipped layer pasted into an empty group has nothing below it to clip to.
#[test]
fn a_clipped_layer_with_nothing_below_is_released() {
let (s, _, b) = session();
let mut d = doc(&s).clone();
let g = insert_new(&mut d, Some(b), Layer::group("empty", vec![]), Place::Auto);
let mut l = Layer::raster("was clipped", d.pixel_format());
l.clipped = true;
let l = insert_new(&mut d, Some(g), l, Place::Auto);
assert!(d.layer(g).unwrap().children().unwrap().iter().any(|c| c.id == l));
assert!(!d.layer(l).unwrap().clipped);
}
+3
View File
@@ -18,12 +18,14 @@ pub mod display_color;
pub mod doc_path;
pub mod filters;
pub mod filters_ext;
mod group_options;
pub mod guide_layout;
pub mod hidden_target;
pub mod inspect;
pub mod installed_profiles;
pub mod jobs;
pub mod kys;
pub mod layer_place;
pub mod layer_style;
pub mod link_watch;
pub mod new_layer;
@@ -88,6 +90,7 @@ pub use cmd::file_cmds;
pub use cmd::fill_cmds;
pub use cmd::fill_key_cmds;
pub use cmd::float_cmds;
pub use cmd::font_library_cmds;
use cmd::frame_cmds;
pub use cmd::fx_view_cmds;
pub use cmd::fx_visibility_cmds;
+5 -7
View File
@@ -35,10 +35,12 @@ pub(crate) struct NewLayer {
name: Option<String>,
}
/// `layer.new.layer`: a pixel layer above the active one (below it with `position: below`, the
/// Layers panel's ⌘/Ctrl-click), joining the clip group it lands in.
/// `layer.new.layer`: a pixel layer where Photoshop puts a new one ([`crate::layer_place`]: above
/// the active layer, inside it when it is an open group, below it with `position: below`, the Layers
/// panel's ⌘/Ctrl-click), joining the clip group it lands in.
pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let NewLayer { clip, mode, opacity, label, neutral, below, name } = parse(p)?;
let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto };
let id = s.edit("New Layer", |doc, active| {
let name = name.clone().unwrap_or_else(|| doc.next_layer_name("Layer"));
let mut layer = Layer::raster(name, doc.pixel_format());
@@ -51,11 +53,7 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let px = photocraft_raster::from_rgba(&surface.format(), [rgb[0], rgb[1], rgb[2], 1.0]);
surface.fill_rect(bounds, &px);
}
// Nothing may sit under the Background: below it the layer lands above it instead.
let id = match *active {
Some(a) if below && doc.layer(a).is_some() && !doc.is_background(a) => doc.insert_below(Some(a), layer),
_ => doc.insert_above(*active, layer),
};
let id = crate::layer_place::insert_new(doc, *active, layer, place);
crate::clip_group::settle(doc, &[id], &Default::default(), clip);
*active = Some(id);
Ok(id)
+10
View File
@@ -870,6 +870,9 @@ pub struct TypePrefs {
pub font_preview: FontPreview,
pub fill_new_type_layers_with_placeholder: bool,
pub recent_fonts: u32,
/// Favourite font families, starred in the font menu (`type.font.favorite`), in the order
/// they were added.
pub favorite_fonts: Vec<String>,
}
impl Default for TypePrefs {
@@ -883,6 +886,7 @@ impl Default for TypePrefs {
font_preview: FontPreview::Medium,
fill_new_type_layers_with_placeholder: true,
recent_fonts: 10,
favorite_fonts: Vec::new(),
}
}
}
@@ -1242,9 +1246,15 @@ impl Preferences {
self.shortcuts.clear();
return Ok(());
}
// The favourite fonts are the user's library, not a Type setting: resetting the Type
// section keeps them (only `type.favoriteFonts` itself, or Reset All, clears them).
let favorites = (path == "type").then(|| self.type_.favorite_fonts.clone());
let mut root = self.to_json();
set_path(&mut root, path, def)?;
*self = serde_json::from_value(root).map_err(|e| e.to_string())?;
if let Some(favorites) = favorites {
self.type_.favorite_fonts = favorites;
}
Ok(())
}
+2 -1
View File
@@ -254,7 +254,8 @@ pub fn encode_tip(t: &GrayTile) -> Vec<u8> {
out.push(if eight { 8 } else { 16 });
out.extend_from_slice(&t.width.to_le_bytes());
out.extend_from_slice(&t.height.to_le_bytes());
let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::fast());
// Level 3: zlib-rs level 1 writes static Huffman blocks only, 13-30% bigger than miniz's level 1.
let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3));
let mut buf = Vec::with_capacity(8192);
let mut ok = true;
for chunk in t.data.chunks(4096) {
+2 -1
View File
@@ -641,7 +641,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
let id = s.edit("New Gradient Fill Layer", |doc, active| {
let fill = Fill::gradient(stops, angle, scale, style, reverse).in_mode(doc.mode);
let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));
let layer = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
let id = crate::layer_place::insert_new(doc, *active, layer, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
+6
View File
@@ -69,6 +69,12 @@ impl Session {
if id == "layer.new.layer" {
crate::new_layer::parse(params)?;
}
if id == "layer.new.group" {
crate::group_options::below(id, params)?;
}
if id == "layer.new.group" || id == "layer.new.groupFromLayers" {
crate::group_options::GroupOptions::parse(id, params)?;
}
// A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the
// document doesn't have.
if spec.params.contains("\"layer\":id")
+2 -1
View File
@@ -1160,7 +1160,8 @@ fn move_selected_layers_keeps_selected_group_children_and_supports_above_below()
let b = s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap();
let c = s.execute("layer.new.layer", json!({"name": "C"})).unwrap()["layer"].as_u64().unwrap();
let group = s.execute("layer.new.group", json!({"name": "G"})).unwrap()["layer"].as_u64().unwrap();
// Made before B moves into G: a new group goes above the active layer, which would then be inside G.
// Made from C, not from G: like Photoshop a new group goes inside an open active group.
s.execute("layer.select", json!({"layer": c})).unwrap();
let target = s.execute("layer.new.group", json!({"name": "Target"})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.moveTo", json!({"layer": b, "target": group, "position": "into"})).unwrap();
@@ -20,8 +20,10 @@ fn shift_range_follows_visible_rows_on_both_sides_of_an_expanded_group() {
select(&mut s, b, "replace");
select(&mut s, c, "add");
let group = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap();
// D goes above the closed group (an open one would take it inside, as in Photoshop).
let d = s.execute("layer.new.layer", json!({"name": "D"})).unwrap()["layer"].as_u64().unwrap();
// Group Layers makes a collapsed group, as in Photoshop; open it so B and C are visible rows.
s.execute("layer.setExpanded", json!({"layer": group, "expanded": true})).unwrap();
for (anchor, target, wanted) in
[(d, group, vec![d, group]), (group, d, vec![d, group]), (group, b, vec![group, c, b]), (b, group, vec![group, c, b]), (c, b, vec![c, b])]
+10 -3
View File
@@ -952,13 +952,20 @@ impl PcraftWriter {
let (p, mut fresh) = prepared?;
let previews = previews?;
let mut stats = p.stats;
let mut z = ZipWriter::new();
let mut next = HashMap::with_capacity(p.objects.len());
let mut cached_bytes = 0usize;
// The archive is sized for every entry up front (#7689): previews, then reused and fresh
// objects at their compressed sizes.
let entries =
std::iter::once((MANIFEST, p.manifest.len())).chain(previews.iter().map(|(name, data)| (*name, data.len()))).chain(p.objects.keys().map(|path| {
let size = self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |data| data.len());
(path.as_str(), size)
}));
let mut z = ZipWriter::with_entries(entries)?;
z.add(MANIFEST, &p.manifest)?;
for (name, data) in &previews {
z.add(name, data)?;
}
let mut next = HashMap::with_capacity(p.objects.len());
let mut cached_bytes = 0usize;
for (path, obj) in &p.objects {
let (key, data) = match self.compressed.remove_entry(path) {
Some((key, data)) => {
+153 -18
View File
@@ -3,6 +3,7 @@
//! unzipped and re-zipped by another tool still loads). No ZIP64, no
//! encryption, no multi-disk archives.
use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Read;
@@ -31,18 +32,41 @@ impl Default for ZipWriter {
}
impl ZipWriter {
/// Creates an empty archive of STORE entries.
pub fn new() -> Self {
ZipWriter { out: Vec::new(), central: Vec::new(), count: 0 }
}
/// Reserves the complete archive from its entry names and payload sizes.
pub(crate) fn with_entries<'a>(entries: impl IntoIterator<Item = (&'a str, usize)>) -> Result<Self, FormatError> {
let (size, directory) = entries.into_iter().try_fold((22usize, 0usize), |(size, directory), (name, bytes)| {
let directory = directory.checked_add(46 + name.len());
let size = size.checked_add(76).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(name.len())).and_then(|n| n.checked_add(bytes));
size.zip(directory).ok_or_else(|| FormatError::Unsupported("zip size overflow".into()))
})?;
let mut writer = Self::new();
writer.out.try_reserve_exact(size).map_err(|_| FormatError::LimitExceeded("not enough memory for zip".into()))?;
writer.central.try_reserve_exact(directory).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?;
Ok(writer)
}
/// Adds a STORE entry, rejecting names or data that exceed ZIP field limits.
/// The entry path has a 16-bit byte length, independent of filesystem limits.
pub fn add(&mut self, name: &str, data: &[u8]) -> Result<(), FormatError> {
if self.count == u16::MAX {
return Err(FormatError::Unsupported("more than 65535 zip entries (ZIP64 not supported)".into()));
}
let size = u32::try_from(data.len()).map_err(|_| FormatError::Unsupported("zip entry over 4 GiB".into()))?;
let offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;
let crc = crc32(data);
let name_b = name.as_bytes();
let name_len = u16::try_from(name_b.len()).map_err(|_| FormatError::Unsupported("zip entry path exceeds the 65535-byte format limit".into()))?;
let local_len = 30usize
.checked_add(name_b.len())
.and_then(|n| n.checked_add(data.len()))
.ok_or_else(|| FormatError::Unsupported("zip entry size overflow".into()))?;
self.out.try_reserve(local_len).map_err(|_| FormatError::LimitExceeded("not enough memory for zip entry".into()))?;
self.central.try_reserve(46 + name_b.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for zip directory".into()))?;
let crc = crc32(data);
// Local file header.
let o = &mut self.out;
o.extend_from_slice(&LOCAL_SIG.to_le_bytes());
@@ -54,7 +78,7 @@ impl ZipWriter {
o.extend_from_slice(&crc.to_le_bytes());
o.extend_from_slice(&size.to_le_bytes());
o.extend_from_slice(&size.to_le_bytes());
o.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
o.extend_from_slice(&name_len.to_le_bytes());
o.extend_from_slice(&0u16.to_le_bytes());
o.extend_from_slice(name_b);
o.extend_from_slice(data);
@@ -70,7 +94,7 @@ impl ZipWriter {
c.extend_from_slice(&crc.to_le_bytes());
c.extend_from_slice(&size.to_le_bytes());
c.extend_from_slice(&size.to_le_bytes());
c.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
c.extend_from_slice(&name_len.to_le_bytes());
c.extend_from_slice(&[0; 8]); // extra len, comment len, disk, internal attrs
c.extend_from_slice(&0u32.to_le_bytes()); // external attrs
c.extend_from_slice(&offset.to_le_bytes());
@@ -79,9 +103,11 @@ impl ZipWriter {
Ok(())
}
/// Appends the central directory and returns the complete archive.
pub fn finish(mut self) -> Result<Vec<u8>, FormatError> {
let cd_offset = u32::try_from(self.out.len()).map_err(|_| FormatError::Unsupported("zip over 4 GiB".into()))?;
let cd_size = self.central.len() as u32;
let cd_size = u32::try_from(self.central.len()).map_err(|_| FormatError::Unsupported("zip directory over 4 GiB".into()))?;
self.out.try_reserve(self.central.len().saturating_add(22)).map_err(|_| FormatError::LimitExceeded("not enough memory to finish zip".into()))?;
self.out.extend_from_slice(&self.central);
self.out.extend_from_slice(&EOCD_SIG.to_le_bytes());
self.out.extend_from_slice(&[0; 4]); // disk numbers
@@ -112,7 +138,7 @@ pub struct ZipReader<'a> {
pub entries: Vec<Entry>,
/// Name -> index of the first entry with that name, so `find` is O(1)
/// instead of a scan per lookup (a bundle reads one entry per tile).
by_name: HashMap<String, usize>,
by_name: HashMap<Cow<'a, str>, usize>,
}
fn u16_at(b: &[u8], o: usize) -> Result<u16, FormatError> {
@@ -123,6 +149,7 @@ fn u32_at(b: &[u8], o: usize) -> Result<u32, FormatError> {
}
impl<'a> ZipReader<'a> {
/// Checks ZIP record bounds and indexes the first entry for each name.
pub fn new(bytes: &'a [u8]) -> Result<Self, FormatError> {
if bytes.len() < 22 {
return Err(FormatError::corrupt("not a zip archive (too short)"));
@@ -150,7 +177,8 @@ impl<'a> ZipReader<'a> {
let cd_size = u32_at(bytes, eocd + 12)? as usize;
let cd_off = u32_at(bytes, eocd + 16)? as usize;
let cd_end = cd_off.checked_add(cd_size).filter(|end| *end <= eocd).ok_or_else(|| FormatError::corrupt("zip central directory out of range"))?;
let mut entries = Vec::with_capacity(count.min(bytes.len() / 46));
let mut entries = Vec::with_capacity(count.min(cd_size / 46));
let mut by_name = HashMap::with_capacity(entries.capacity());
let mut p = cd_off;
for _ in 0..count {
let header_end = p.checked_add(46).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("truncated zip central directory entry"))?;
@@ -168,7 +196,7 @@ impl<'a> ZipReader<'a> {
let local = u32_at(bytes, p + 42)? as usize;
let name_end = header_end.checked_add(nlen).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("zip entry name out of range"))?;
let name = bytes.get(header_end..name_end).ok_or_else(|| FormatError::corrupt("truncated zip name"))?;
let name = String::from_utf8_lossy(name).into_owned();
let name = String::from_utf8_lossy(name);
if flags & 1 != 0 {
return Err(FormatError::Unsupported("encrypted zip entries".into()));
}
@@ -194,14 +222,11 @@ impl<'a> ZipReader<'a> {
if data_offset.checked_add(compressed).is_none_or(|end| end > bytes.len()) {
return Err(FormatError::corrupt(format!("zip entry `{name}` out of range")));
}
entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset });
// The index borrows valid UTF-8 names; duplicate names keep the first entry.
by_name.entry(name.clone()).or_insert(entries.len());
entries.push(Entry { name: name.into_owned(), method, crc, compressed, uncompressed, data_offset });
p = entry_end;
}
let mut by_name = HashMap::with_capacity(entries.len());
for (i, e) in entries.iter().enumerate() {
// Duplicate names: the first entry wins, as with a front-to-back scan.
by_name.entry(e.name.clone()).or_insert(i);
}
Ok(ZipReader { bytes, entries, by_name })
}
@@ -227,8 +252,9 @@ impl<'a> ZipReader<'a> {
// small forged archive must not reserve gigabytes up front, so the
// preallocation is capped (DEFLATE expands at most ~1032x).
let mut out = Vec::with_capacity(e.uncompressed.min(raw.len().saturating_mul(1032)).min(64 << 20));
flate2::read::DeflateDecoder::new(raw)
.take((max as u64).saturating_add(1))
// One surplus byte proves a false size without expanding to the caller's larger budget.
flate2::bufread::DeflateDecoder::new(raw)
.take((e.uncompressed as u64).saturating_add(1))
.read_to_end(&mut out)
.map_err(|err| FormatError::corrupt(format!("zip entry `{}`: {err}", e.name)))?;
out
@@ -261,6 +287,20 @@ mod tests {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
}
/// ZIP entry paths have a format limit even when each component is short.
#[test]
fn entry_path_length_is_checked_before_writing() {
let mut writer = ZipWriter::new();
for name in ["dir/".repeat(16384), "é/".repeat(21846)] {
assert!(matches!(writer.add(&name, b"invalid"), Err(FormatError::Unsupported(_))));
assert!(writer.out.is_empty() && writer.central.is_empty());
}
let name = "dir/".repeat(16383) + "end";
writer.add(&name, b"valid").unwrap();
let bytes = writer.finish().unwrap();
assert_eq!(ZipReader::new(&bytes).unwrap().read_by_name(&name, 5).unwrap(), b"valid");
}
#[test]
fn roundtrip() {
let mut w = ZipWriter::new();
@@ -274,6 +314,7 @@ mod tests {
assert_eq!(r.read_by_name("dir/b.bin", 100).unwrap(), [0, 1, 2, 3]);
assert!(r.read_by_name("empty", 0).unwrap().is_empty());
assert!(matches!(r.read_by_name("a.txt", 3), Err(FormatError::LimitExceeded(_))));
assert!(r.by_name.keys().all(|name| matches!(name, Cow::Borrowed(_))));
}
fn archive_with_comment(comment: &[u8]) -> Vec<u8> {
@@ -379,6 +420,46 @@ mod tests {
assert_eq!(r.read_by_name("b", 100).unwrap(), b"other");
}
/// Reservation changes neither entry bytes nor final output, and avoids growth.
#[test]
fn whole_archive_reservation_preserves_output() {
let entries = [("层/é.png", &b"image"[..]), ("empty", &b""[..]), ("empty", &b"duplicate"[..])];
for entries in [&entries[..0], &entries[..]] {
let mut previous = ZipWriter::new();
let mut reserved = ZipWriter::with_entries(entries.iter().map(|(name, data)| (*name, data.len()))).unwrap();
let (capacity, directory) = (reserved.out.capacity(), reserved.central.capacity());
for (name, data) in entries {
previous.add(name, data).unwrap();
reserved.add(name, data).unwrap();
}
assert_eq!(reserved.central.capacity(), directory);
let bytes = reserved.finish().unwrap();
assert_eq!(bytes.capacity(), capacity);
assert_eq!(bytes, previous.finish().unwrap());
}
assert!(matches!(ZipWriter::with_entries([("x", usize::MAX)]), Err(FormatError::Unsupported(_))));
assert!(matches!(ZipWriter::with_entries([("x", isize::MAX as usize)]), Err(FormatError::LimitExceeded(_))));
}
/// Invalid UTF-8 names retain their lossy spelling and first-entry lookup.
#[test]
fn name_index_borrows_unicode_and_owns_lossy_names() {
let mut writer = ZipWriter::new();
for name in ["层/é.png", "a", "b"] {
writer.add(name, name.as_bytes()).unwrap();
}
let mut bytes = writer.finish().unwrap();
let mut p = u32_at(&bytes, bytes.len() - 6).unwrap() as usize;
p += 46 + "层/é.png".len();
bytes[p + 46] = 0xff;
bytes[p + 47 + 46] = 0xfe;
let reader = ZipReader::new(&bytes).unwrap();
assert_eq!(reader.read_by_name("层/é.png", 100).unwrap(), "层/é.png".as_bytes());
assert!(matches!(reader.by_name.get_key_value("层/é.png").unwrap().0, Cow::Borrowed(_)));
assert!(matches!(reader.by_name.get_key_value("�").unwrap().0, Cow::Owned(_)));
assert_eq!(reader.read_by_name("�", 1).unwrap(), b"a");
}
#[test]
fn crc_mismatch_detected() {
let mut w = ZipWriter::new();
@@ -390,9 +471,63 @@ mod tests {
assert!(r.read_by_name("a", 100).is_err());
}
/// A valid DEFLATE-compressed bundle may be read with an effectively
/// unlimited caller budget (e.g. corruption/round-trip checks). On 64-bit
/// targets `usize::MAX as u64 + 1` overflows, so the decoder must saturate.
#[test]
fn slice_deflate_matches_buffered_reader_and_preserves_checks() {
use std::io::Write as _;
let content = b"PhotoCraft ZIP payload".repeat(5000);
let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::none());
encoder.write_all(&content).unwrap();
let compressed = encoder.finish().unwrap();
assert!(compressed.len() > 32 * 1024);
let mut previous = Vec::new();
flate2::read::DeflateDecoder::new(compressed.as_slice()).read_to_end(&mut previous).unwrap();
let mut writer = ZipWriter::new();
writer.add("payload", &compressed).unwrap();
let bytes = writer.finish().unwrap();
let reader = ZipReader::new(&bytes).unwrap();
let mut entry = reader.entries[0].clone();
entry.method = 8;
entry.uncompressed = content.len();
entry.crc = crc32(&content);
assert_eq!(reader.read(&entry, content.len()).unwrap(), previous);
assert!(matches!(reader.read(&entry, content.len() - 1), Err(FormatError::LimitExceeded(_))));
entry.crc ^= 1;
assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_))));
entry.crc ^= 1;
entry.compressed /= 2;
assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_))));
}
/// A false small size must stop expansion before decoding the rest of the stream.
#[test]
fn deflate_surplus_stops_before_a_corrupt_suffix() {
// Exceed miniz's internal 32 KiB output buffer before the corrupt block.
let raw = [&[0, 0xff, 0xff, 0, 0][..], &[b'x'; 65535], &[7]].concat();
let reader = ZipReader { bytes: &raw, entries: Vec::new(), by_name: HashMap::new() };
for declared in [0, 7] {
let entry = Entry { name: "surplus".into(), method: 8, crc: 0, compressed: raw.len(), uncompressed: declared, data_offset: 0 };
let err = reader.read(&entry, usize::MAX).unwrap_err();
assert!(err.to_string().contains("wrong size"), "{err}");
}
}
/// Correct output length and CRC do not replace the final DEFLATE block.
#[test]
fn deflate_requires_a_complete_stream_including_empty_entries() {
for (raw, content) in [(&[0, 1, 0, 0xfe, 0xff, b'x', 1, 0, 0, 0xff, 0xff][..], &b"x"[..]), (&[3, 0][..], &b""[..])] {
let reader = ZipReader { bytes: raw, entries: Vec::new(), by_name: HashMap::new() };
let mut entry =
Entry { name: "complete".into(), method: 8, crc: crc32(content), compressed: raw.len(), uncompressed: content.len(), data_offset: 0 };
assert_eq!(reader.read(&entry, content.len()).unwrap(), content);
for cut in 0..raw.len() {
entry.compressed = cut;
assert!(matches!(reader.read(&entry, content.len()), Err(FormatError::Corrupt(_))), "cut at {cut}");
}
}
}
/// An unlimited caller budget still checks a DEFLATE entry's declared size.
#[test]
fn deflated_entry_with_unbounded_limit_round_trips() {
use std::io::Write as _;
+4 -2
View File
@@ -280,10 +280,11 @@ fn text_run_baseline_roundtrips() {
fn zip_incremental_only_new_tiles() {
let mut doc = rich_doc(ColorMode::Rgb, SampleType::U16);
let mut w = PcraftWriter::new();
let (_, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
let (first, s1) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
assert!(s1.tiles_total > 5);
assert_eq!(s1.tiles_written, s1.tiles_total);
let (_, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
let (cached, s2) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
assert_eq!(first, cached);
assert_eq!(s2.tiles_written, 0);
assert_eq!(s2.tiles_reused, s2.tiles_total);
assert_eq!(s2.blobs_written, 0);
@@ -293,6 +294,7 @@ fn zip_incremental_only_new_tiles() {
let (bytes, s3) = w.save_zip(&doc, &SaveOptions::default()).unwrap();
assert_eq!(s3.tiles_written, 1);
assert_eq!(load_from_bytes(&bytes).unwrap(), doc);
assert_eq!(bytes, PcraftWriter::new().save_zip(&doc, &SaveOptions::default()).unwrap().0);
}
#[test]
+1
View File
@@ -49,6 +49,7 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste
resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
[dev-dependencies]
miniz_oxide = "0.9"
crc32fast = "1.5"
photocraft-affinity = { workspace = true, features = ["synth"] }
flate2 = { workspace = true }
+56
View File
@@ -0,0 +1,56 @@
//! Opens a file the way the app's background open does and reports the time. Run it under
//! `/usr/bin/time -l` for the peak memory. `--read` reads the whole file first and imports the
//! bytes, as opens did before `import_file` (to compare).
//!
//! `cargo run --release -p photocraft-io --example psd_open_mem -- <file.psd> [--read]`
fn main() {
let Some(path) = std::env::args().nth(1).filter(|a| a != "--read") else {
eprintln!("usage: psd_open_mem <file.psd>");
std::process::exit(2);
};
if std::env::args().any(|a| a == "--read") {
read_then_import(&path);
return;
}
let t = std::time::Instant::now();
let res =
match photocraft_io::import_file(&path, std::path::Path::new(&path), &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE) {
Ok(r) => r,
Err(e) => {
eprintln!("{path}: open failed: {e}");
std::process::exit(1);
}
};
report(&path, &format!("open {:.2}s", t.elapsed().as_secs_f64()), &res);
}
fn read_then_import(path: &str) {
let t = std::time::Instant::now();
let bytes = match photocraft_format::read_file(std::path::Path::new(path)) {
Ok(b) => b,
Err(e) => {
eprintln!("{path}: read failed: {e}");
std::process::exit(1);
}
};
let read_s = t.elapsed().as_secs_f64();
let t = std::time::Instant::now();
let res = match photocraft_io::import_with(path, &bytes, &photocraft_raster::Interrupt::NONE) {
Ok(r) => r,
Err(e) => {
eprintln!("{path}: open failed: {e}");
std::process::exit(1);
}
};
drop(bytes);
report(path, &format!("read {read_s:.2}s, import {:.2}s", t.elapsed().as_secs_f64()), &res);
}
fn report(path: &str, times: &str, res: &photocraft_io::ImportResult) {
let doc = &res.document;
println!("{path}: {times}, {} layers ({} top level)", doc.walk().len(), doc.layers.len());
for w in &res.warnings {
println!(" warning: {w}");
}
}
+69 -10
View File
@@ -126,6 +126,9 @@ pub enum IoError {
/// An SVG that does not parse (or is too large to rasterise).
#[error("SVG: {0}")]
Svg(String),
/// The file could not be read.
#[error("{0}")]
Read(String),
/// A background import or save was cancelled ([`import_with`], [`export_with`]).
#[error("cancelled")]
Cancelled,
@@ -374,26 +377,82 @@ pub fn import_for_open_with(name: &str, bytes: &[u8], opts: &ImportOptions, ctl:
Ok((result, damaged))
}
fn import_psd(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, damaged: &mut bool) -> Result<ImportResult, IoError> {
/// The PSD/PSB part of an import, from a parse that takes [`PsdFile::from_bytes_and_merged_recovering`]'s
/// `want` and `recover`: of the file's bytes, or of the file itself ([`import_file_for_open_with`]).
fn import_psd(
name: &str,
ctl: &photocraft_raster::Interrupt,
damaged: &mut bool,
parse: impl FnOnce(&dyn Fn(&PsdFile) -> bool, &dyn Fn(&PsdFile) -> bool) -> photocraft_psd::Result<(PsdFile, Option<photocraft_psd::Result<Vec<u8>>>)>,
) -> Result<ImportResult, IoError> {
// A merged image the import reads is decoded with the parse: a ZIP one is inflated once.
let (file, merged) = PsdFile::from_bytes_and_merged_recovering(
bytes,
|f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f),
psd_import::can_recover_layers,
)?;
// A failed read of the file (one parsed from its source) is a read error, as reading the
// whole file first would report it.
let (file, merged) =
parse(&|f| psd_import::check_group_depth(f).is_ok() && psd_import::merged_needed(f), &psd_import::can_recover_layers).map_err(|e| match e {
photocraft_psd::PsdError::Read(msg) => IoError::Read(msg),
e => e.into(),
})?;
// Nesting past the document model's cap could never be saved; reject the file with the
// actionable limit.
psd_import::check_group_depth(&file)?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
let (mut document, warnings, psd_damaged) = psd_import::psd_to_document_decoded_integrity(&file, ctl, merged).ok_or(IoError::Cancelled)?;
// Read before the conversion, which moves the global blocks into the document.
let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data));
let (mut document, warnings, psd_damaged, read_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?;
// The file became unreadable while its layers were read from it (`import_file_for_open_with`):
// the open fails, rather than opening with those layers empty.
if let Some(e) = read_error {
return Err(IoError::Read(e));
}
*damaged = psd_damaged;
document.name = name.to_string();
let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data));
text_import::prepare(&mut document, txt2.as_ref());
Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false })
}
/// [`import_for_open_with`] for the file at `path`. A PSD/PSB is parsed from the open file
/// ([`PsdFile::from_source`]) rather than read whole: its channel data is read layer by layer as
/// it is decoded, so opening it needs memory for the document, not for the document plus the
/// file. A read that fails meanwhile (the file is truncated or rewritten, its drive goes away)
/// fails the open. Other formats are read whole.
#[cfg(any(unix, windows))]
pub fn import_file_for_open_with(
name: &str,
path: &std::path::Path,
opts: &ImportOptions,
ctl: &photocraft_raster::Interrupt,
) -> Result<(ImportResult, bool), IoError> {
let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display()));
ctl.check().map_err(|_| IoError::Cancelled)?;
let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?;
let mut magic = [0u8; 4];
let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic);
if !psd {
drop(source);
let bytes = photocraft_format::read_file(path).map_err(read_failed)?;
return import_for_open_with(name, &bytes, opts, ctl);
}
import_source_for_open_with(name, photocraft_psd::Source::new(source), ctl)
}
/// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source.
pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> {
ctl.check().map_err(|_| IoError::Cancelled)?;
let mut damaged = false;
let r = import_psd(name, ctl, &mut damaged, |want, recover| PsdFile::from_source_and_merged_recovering(source, want, recover))?;
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(1.0);
Ok((r, damaged))
}
/// [`import_file_for_open_with`] without the damage flag.
#[cfg(any(unix, windows))]
pub fn import_file(name: &str, path: &std::path::Path, opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result<ImportResult, IoError> {
import_file_for_open_with(name, path, opts, ctl).map(|(result, _)| result)
}
/// Dispatches format-specific importers and propagates a structured PSD damage
/// flag alongside the ordinary best-effort import result.
fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, damaged: &mut bool) -> Result<ImportResult, IoError> {
@@ -405,7 +464,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
// Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus
// preview_never_saves_back_to_its_native_or_renamed_source).
if is_psd(bytes) {
return import_psd(name, bytes, ctl, damaged);
return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover));
}
if affinity::is_affinity(bytes) || affinity::has_extension(name) {
return affinity::import(name, bytes);
@@ -438,7 +497,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o
// A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of
// `codec: unrecognized image format` (#5258). Magic already returned above.
if is_psd_input(name, bytes) {
return import_psd(name, bytes, ctl, damaged);
return import_psd(name, ctl, damaged, |want, recover| PsdFile::from_bytes_and_merged_recovering(bytes, want, recover));
}
flat::import_flat(name, bytes)
}
+26 -3
View File
@@ -118,7 +118,30 @@ pub fn find_in_blocks<'a>(blocks: impl IntoIterator<Item = (&'a [u8; 4], &'a [u8
if uuid.is_empty() {
return None;
}
blocks.into_iter().filter(|(k, _)| matches!(*k, b"lnk2" | b"lnk3" | b"lnkD")).flat_map(|(_, d)| parse_linked_files(d)).find(|f| f.uuid == uuid)
let (uuid, file_name, bytes) = find_slice_in_blocks(blocks, uuid)?;
Some(LinkedFile { uuid, file_name, bytes: bytes.to_vec() })
}
/// [`find_in_blocks`] without copying: the uuid, file name and bytes of the embedded file, as a
/// slice of the block. Only the matching item's header is parsed beyond the uuid, and no other
/// embedded file is copied (a `lnk2` block can hold gigabytes of them).
fn find_slice_in_blocks<'a>(blocks: impl IntoIterator<Item = (&'a [u8; 4], &'a [u8])>, uuid: &str) -> Option<(String, String, &'a [u8])> {
if uuid.is_empty() {
return None;
}
blocks.into_iter().filter(|(k, _)| matches!(*k, b"lnk2" | b"lnk3" | b"lnkD")).find_map(|(_, d)| {
let mut r = Rd { d, p: 0 };
while let Some(len) = r.u64() {
let Ok(len) = usize::try_from(len) else { return None };
let item = r.take(len)?;
let found = item_header(item).filter(|h| h.0 == uuid).and_then(|(id, name, start, n)| Some((id, name, item.get(start..start.checked_add(n)?)?)));
if found.is_some() {
return found;
}
r.p = r.p.next_multiple_of(4);
}
None
})
}
/// The size of embedded file `uuid` among PSD global blocks given as (key, data), when it is there
@@ -128,11 +151,11 @@ pub(crate) fn source_size_in_blocks<'a>(
uuid: &str,
ctl: &photocraft_raster::Interrupt,
) -> Option<(f64, f64)> {
let f = find_in_blocks(blocks, uuid)?;
let (_, _, bytes) = find_slice_in_blocks(blocks, uuid)?;
if ctl.cancelled() {
return None;
}
source_size_probe(&f.bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0)
source_size_probe(bytes).filter(|(w, h)| *w > 0.0 && *h > 0.0)
}
/// Pixel size of an embedded source file from its header: PSD/PSB, TIFF (the default page's
+1 -1
View File
@@ -115,7 +115,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: Optio
let header = Header::new(version, doc.size.width, doc.size.height, channels.len().max(1) as u16, psd_depth(sample), PsdMode::Multichannel);
let image_data = ImageData::encode(Compression::Rle, &planes, &header)
.or_else(|_| ImageData::encode(Compression::Raw, &planes, &header))
.unwrap_or(ImageData { compression: Compression::Raw, data: planes });
.unwrap_or(ImageData::new(Compression::Raw, planes));
let mut resources = vec![
ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()),
ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),
+1 -1
View File
@@ -45,7 +45,7 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool, size_limit: Optio
let header = Header::new(version, doc.size.width, doc.size.height, 1, depth, mode);
let image_data = ImageData::encode(Compression::Rle, &plane, &header)
.or_else(|_| ImageData::encode(Compression::Raw, &plane, &header))
.unwrap_or(ImageData { compression: Compression::Raw, data: plane });
.unwrap_or(ImageData::new(Compression::Raw, plane));
let mut resources = vec![
ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()),
ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),
+4 -2
View File
@@ -59,8 +59,10 @@ fn pdf_string(s: &str) -> String {
}
fn deflate(data: &[u8]) -> Vec<u8> {
// Fast: print PDFs are transient and large; level 1 is ~4× quicker than the default.
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
// Fast: print PDFs are transient and large. Level 3, not 1: zlib-rs level 1 writes static
// Huffman blocks only (13-30% bigger on photos); level 3 is the lowest that is never bigger
// than miniz's level 1 was, at about twice its time.
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(3));
let _ = e.write_all(data);
e.finish().unwrap_or_default()
}
+1 -1
View File
@@ -188,7 +188,7 @@ impl Ex {
let compression = if w == 0 || h == 0 { Compression::Raw } else { self.compression() };
ChannelData::encode(id, compression, plane, w, h, depth, self.version)
.or_else(|_| ChannelData::encode(id, Compression::Raw, plane, w, h, depth, self.version))
.unwrap_or(ChannelData { id, compression: Some(Compression::Raw), data: plane.to_vec() })
.unwrap_or(ChannelData::new(id, Some(Compression::Raw), plane.to_vec()))
}
fn empty_channels(&self) -> Vec<ChannelData> {
+1 -1
View File
@@ -208,7 +208,7 @@ pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, dep
let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression };
let image_data = ImageData::encode(mcomp, &planes, &header)
.or_else(|_| ImageData::encode(Compression::Raw, &planes, &header))
.unwrap_or(ImageData { compression: Compression::Raw, data: planes });
.unwrap_or(ImageData::new(Compression::Raw, planes));
ctl.progress(1.0);
// Resources.
+132 -44
View File
@@ -4,7 +4,8 @@ use std::sync::Arc;
use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{
AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,
AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, PsdGlobalBlock, ShapeLayer, SmartContentsId, SmartObject, SmartSource,
TextLayer,
};
use photocraft_geom::{Rect, Size, TILE_SIZE};
use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK};
@@ -46,6 +47,8 @@ pub(crate) const REGENERATED: [&[u8; 4]; 9] = [b"luni", b"lyid", b"lsct", b"lsdk
pub(crate) struct Ctx<'a> {
pub file: &'a PsdFile,
/// The file's global blocks, as the document keeps them.
pub global: Vec<PsdGlobalBlock>,
pub fmt: PixelFormat,
pub mask_fmt: PixelFormat,
pub cc: usize,
@@ -53,6 +56,9 @@ pub(crate) struct Ctx<'a> {
pub warnings: Vec<String>,
/// Decoding encountered damaged PSD data; interactive opens ask whether to continue.
pub damaged: bool,
/// Reading the file's channel data failed (it is read as it is decoded: see
/// `PsdFile::from_source`): the open fails with it, rather than leaving layers empty.
pub read_error: Option<String>,
/// Document resolution (type sizes are converted to points with it).
pub dpi: f32,
/// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning).
@@ -74,9 +80,35 @@ pub(crate) struct Ctx<'a> {
pub ctl: photocraft_raster::Interrupt<'a>,
/// Layer records decoded so far, out of `total` (progress).
pub done: usize,
/// Tiles of one pixel value, shared by every surface the import decodes.
pub uniform: photocraft_raster::TileInterner,
pub total: usize,
}
/// Bytes of interleaved pixels a band decoded into tiles at once aims at: whole layers up to this
/// size decode in one band, larger ones in bands of whole tile rows.
const BAND_BYTES: usize = 32 << 20;
/// Row ranges (`0..h`, relative to a layer whose first row is at document row `top`) to decode a
/// layer in: each ends on a tile row boundary, so no tile is written by two bands, and holds
/// about [`BAND_BYTES`] of `row_bytes`-byte rows.
fn band_rows(top: i32, h: usize, row_bytes: usize) -> Vec<(usize, usize)> {
let tile = TILE_SIZE as usize;
let rows = (BAND_BYTES / row_bytes.max(1)).max(tile) / tile * tile;
// The first band ends at the first tile boundary at least `rows` rows in.
let into_tile = usize::try_from(top.rem_euclid(TILE_SIZE)).unwrap_or(0);
let mut out = Vec::new();
let mut r0 = 0;
let mut r1 = rows - into_tile;
while r0 < h {
let end = r1.min(h);
out.push((r0, end));
r0 = end;
r1 = end + rows;
}
out
}
fn doc_mode(m: PsdMode) -> Option<ColorMode> {
Some(match m {
PsdMode::Bitmap => ColorMode::Bitmap,
@@ -148,6 +180,17 @@ impl Ctx<'_> {
self.warn(s);
}
/// A channel that failed to decode: a failed read of the file is kept to fail the open
/// (`true`); damaged data is warned about, its layer left empty (`false`).
fn channel_failed(&mut self, name: &str, id: i16, e: &photocraft_psd::PsdError) -> bool {
if let photocraft_psd::PsdError::Read(msg) = e {
self.read_error.get_or_insert_with(|| format!("layer \"{name}\": {msg}"));
return true;
}
self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty"));
false
}
/// Source id, transform, (Distort/Perspective) projective placement and warp of a placed
/// layer that has only a `PlLd` block, as Photoshop CS2 and older write it (#2465). `PlLd`
/// stores the placed corners but not the source size, which comes from the embedded file.
@@ -168,11 +211,11 @@ impl Ctx<'_> {
return Placement::default();
}
};
let (file, ctl) = (self.file, self.ctl);
let (global, ctl) = (&self.global, self.ctl);
let size = *self
.plld_sizes
.entry(id.clone())
.or_insert_with(|| crate::linked::source_size_in_blocks(file.global_blocks.iter().map(|b| (&b.key, b.data.as_slice())), &id, &ctl));
.or_insert_with(|| crate::linked::source_size_in_blocks(global.iter().map(|(_, k, d)| (k, d.as_slice())), &id, &ctl));
// Without the source (missing or unreadable), it is taken as placed at 100 %.
let (transform, perspective) = blocks::plld_transform(&p, size, warp.as_ref());
Placement { id, transform, perspective, warp }
@@ -181,72 +224,83 @@ impl Ctx<'_> {
/// Decodes a PSD layer channel, marking the document damaged if its data is unreadable.
fn channel_plane(&mut self, rec: &LayerRecord, id: i16, name: &str) -> Option<Vec<u8>> {
rec.channel(id)?;
if self.read_error.is_some() {
return None;
}
match rec.decode_channel(id, self.file.header.depth, self.file.header.version) {
Ok(p) => Some(p),
Err(e) => {
self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded ({e}); treated as empty"));
self.channel_failed(name, id, &e);
None
}
}
}
/// [`Self::channel_plane`] without the warnings sink, so a layer's channels decode
/// concurrently (their RLE rows are the bulk of the open time on full-canvas layers).
fn channel_plane_decoded(&self, rec: &LayerRecord, id: i16) -> Option<Vec<u8>> {
rec.channel(id)?;
rec.decode_channel(id, self.file.header.depth, self.file.header.version).ok()
}
/// Builds a raster surface from the layer channels, leaving the surface empty if
/// any present channel fails to decode rather than inventing replacement pixels.
fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface {
let r = rec.rect;
if r.is_empty() || r.size().is_err() {
// Once the file couldn't be read the open fails: nothing more is decoded.
if r.is_empty() || r.size().is_err() || self.read_error.is_some() {
return Surface::new(self.fmt);
}
let (w, h) = r.size().unwrap_or((0, 0));
let s = self.fmt.sample;
let (depth, version) = (self.file.header.depth, self.file.header.version);
let ids: Vec<i16> = (0..self.cc as i16).chain([CHANNEL_TRANSPARENCY]).collect();
let planes: Vec<Option<Vec<u8>>> = if cfg!(target_arch = "wasm32") {
ids.iter().map(|&id| self.channel_plane(rec, id, name)).collect()
} else {
// The channels decode independently; their RLE rows are the bulk of the open
// time for full-canvas layers, so they run side by side and the warnings land
// in the same order afterwards.
// par_map reuses the crate's worker pool (one OS thread per channel per layer
// would spawn thousands on a file with many layers).
let decoded: Vec<Option<Vec<u8>>> = crate::pixels::par_map(ids.to_vec(), |id| self.channel_plane_decoded(rec, id));
let mut planes: Vec<Option<Vec<u8>>> = Vec::with_capacity(decoded.len());
for (&id, p) in ids.iter().zip(decoded) {
if p.is_none() && rec.channel(id).is_some() {
self.warn_unreadable_data(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty"));
}
planes.push(p);
// A decoder per channel present (a ZIP channel is inflated here, the channels side by
// side); the rows are then decoded and interleaved a band at a time straight into the
// tiles, so no buffer of the whole layer (planes or interleaved) is ever held.
// par_map reuses the crate's worker pool (one OS thread per channel per layer would
// spawn thousands on a file with many layers).
let decoders: Vec<Option<photocraft_psd::Result<photocraft_psd::RowDecoder<'_>>>> =
crate::pixels::par_map(ids.to_vec(), |id| rec.channel(id).map(|ch| ch.row_decoder(w, h, depth, version)));
let mut failed = false;
for (&id, d) in ids.iter().zip(&decoders) {
if let Some(Err(e)) = d {
self.channel_failed(name, id, e);
failed = true;
}
planes
};
}
// A channel that is in the file but could not be decoded leaves the layer empty, as the
// warning says. Filling in for it would paint an opaque black layer over the document.
if ids.iter().zip(planes.iter()).any(|(&id, p)| p.is_none() && rec.channel(id).is_some()) {
if failed {
return Surface::new(self.fmt);
}
// Only decoded channel data justifies a buffer: the decoders bound their output by the
// bytes in the file, but a bare rectangle can declare 300000² pixels in a few bytes (#755).
if planes.iter().all(Option::is_none) {
if decoders.iter().all(Option::is_none) {
self.warn_unreadable_data(format!("layer \"{name}\": no channel data for its {w}x{h} bounds; treated as empty"));
return Surface::new(self.fmt);
}
let refs: Vec<Option<&[u8]>> = planes.iter().map(|p| p.as_deref()).collect();
let mut fill: Vec<Vec<u8>> = vec![zero_sample(s); self.cc];
fill.push(max_sample(s));
let mut invert = vec![self.cmyk; self.cc];
invert.push(false);
let mut bytes = interleave(&refs, &fill, w * h, s, &invert);
if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 {
crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true);
let mut surf = Surface::new(self.fmt);
for (b0, b1) in band_rows(r.top, h, w * (self.cc + 1) * s.bytes()) {
let planes: Vec<Option<photocraft_psd::Result<Vec<u8>>>> =
crate::pixels::par_map(decoders.iter().collect(), |d| d.as_ref().and_then(|d| d.as_ref().ok()).map(|d| d.rows(b0, b1)));
let mut refs: Vec<Option<&[u8]>> = Vec::with_capacity(planes.len());
for (&id, p) in ids.iter().zip(&planes) {
match p {
Some(Err(e)) => {
self.channel_failed(name, id, e);
return Surface::new(self.fmt);
}
Some(Ok(p)) => refs.push(Some(p)),
None => refs.push(None),
}
}
let mut bytes = interleave(&refs, &fill, w * (b1 - b0), s, &invert);
if self.fmt.mode == ColorMode::Lab && s == SampleType::U16 {
crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, true);
}
surf.write_interleaved(Rect::new(r.left, r.top + b0 as i32, r.right, r.top + b1 as i32), &bytes);
}
let mut surf = Surface::from_interleaved(self.fmt, Rect::new(r.left, r.top, r.right, r.bottom), &bytes);
surf.prune();
// A white background, a solid fill's cache: one tile per value, shared across layers.
surf.share_uniform_tiles(&mut self.uniform);
surf
}
@@ -270,6 +324,7 @@ impl Ctx<'_> {
let bytes = interleave(&[Some(&plane)], &[zero_sample(s)], w * h, s, &[false]);
surface.write_interleaved(Rect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes);
surface.prune();
surface.share_uniform_tiles(&mut self.uniform);
}
let params = m.parameters;
Some(LayerMask {
@@ -982,6 +1037,38 @@ pub(crate) fn psd_to_document_decoded_integrity(
ctl: &photocraft_raster::Interrupt,
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
) -> Option<(Document, Vec<String>, bool)> {
let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect();
psd_to_document_global(file, ctl, decoded, global).map(|(document, warnings, damaged, _)| (document, warnings, damaged))
}
/// [`psd_to_document_decoded_integrity`] taking the file: its global blocks move into the
/// document rather than being copied (an embedded smart object's `lnk2` block can be most of a
/// file). The file's channel data may still be in its source ([`PsdFile::from_source`]): the
/// fourth value is a failure to read it, which fails the open (a layer is never left empty
/// because its file became unreadable while it opened).
pub(crate) fn psd_to_document_owned(
mut file: PsdFile,
ctl: &photocraft_raster::Interrupt,
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
) -> Option<(Document, Vec<String>, bool, Option<String>)> {
let global = file
.global_blocks
.iter_mut()
.map(|b| {
// A layer block is still read by `unreadable_layer_block` (to say why it failed).
let data = if matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr") { b.data.clone() } else { std::mem::take(&mut b.data) };
(b.signature, b.key, Arc::new(data))
})
.collect();
psd_to_document_global(&file, ctl, decoded, global)
}
fn psd_to_document_global(
file: &PsdFile,
ctl: &photocraft_raster::Interrupt,
decoded: Option<photocraft_psd::Result<Vec<u8>>>,
global: Vec<PsdGlobalBlock>,
) -> Option<(Document, Vec<String>, bool, Option<String>)> {
let h = &file.header;
let mut warnings = Vec::new();
let mode = doc_mode(h.color_mode).unwrap_or_else(|| {
@@ -1046,9 +1133,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
}
}
crate::guides_map::apply_colors(&mut doc);
for b in &file.global_blocks {
doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone())));
}
doc.metadata.psd_global_blocks.extend(global.iter().cloned());
// A 16/32-bit file whose layer block can't be parsed would otherwise open as a flattened
// file without a word (#2700). The raw block is kept, but a PSD save writes the document's
// own layers in its place (see `psd_export`).
@@ -1074,14 +1159,16 @@ pub(crate) fn psd_to_document_decoded_integrity(
let cc = fmt.mode.color_channels();
let mut cx = Ctx {
file,
global: global.clone(),
fmt,
mask_fmt: PixelFormat::new(ColorMode::Grayscale, depth, false),
cc,
cmyk: fmt.mode == ColorMode::Cmyk,
warnings,
damaged,
read_error: None,
dpi: doc.resolution_dpi,
txt2: file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)),
txt2: global.iter().find(|(_, k, _)| k == b"Txt2").and_then(|(_, _, d)| photocraft_text::psd::parse_txt2(d)),
filter_effects: Vec::new(),
filter_masks: Default::default(),
unfiltered: Default::default(),
@@ -1090,16 +1177,17 @@ pub(crate) fn psd_to_document_decoded_integrity(
plld_sizes: Default::default(),
ctl: *ctl,
done: 0,
uniform: Default::default(),
total: file.layers().len(),
};
for b in file.global_blocks.iter().filter(|b| matches!(&b.key, b"FEid" | b"FXid")) {
for (_, key, data) in cx.global.clone().iter().filter(|(_, k, _)| matches!(k, b"FEid" | b"FXid")) {
// Smart-filter caches can be large: a cancelled open stops between blocks.
if ctl.cancelled() {
return None;
}
match photocraft_psd::filter_effects::FilterEffects::parse(&b.data) {
match photocraft_psd::filter_effects::FilterEffects::parse(data) {
Ok(fx) => cx.filter_effects.extend(fx.items),
Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", b.key_str())),
Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", String::from_utf8_lossy(key))),
}
}
if ctl.cancelled() {
@@ -1331,7 +1419,7 @@ pub(crate) fn psd_to_document_decoded_integrity(
return None;
}
ctl.progress(1.0);
Some((doc, cx.warnings, cx.damaged))
Some((doc, cx.warnings, cx.damaged, cx.read_error))
}
#[cfg(test)]
+21
View File
@@ -367,3 +367,24 @@ fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() {
assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's");
assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted");
}
#[test]
fn layer_bands_end_on_tile_rows_and_cover_the_layer() {
let t = TILE_SIZE as usize;
for (top, h, row_bytes) in [(0, 2000, 8000), (-37, 15000, 80_000), (100, 5, 4), (255, 1, 4), (-256, 40_000, 1 << 20), (7, 0, 4)] {
let bands = band_rows(top, h, row_bytes);
let mut next = 0;
for &(a, b) in &bands {
assert_eq!(a, next);
assert!(b > a);
if b < h {
assert_eq!((top + b as i32).rem_euclid(TILE_SIZE), 0, "{top} {h}: band ends inside a tile row");
assert!((b - a) * row_bytes <= BAND_BYTES + t * row_bytes || b - a <= t);
}
next = b;
}
assert_eq!(next, h);
}
// A small layer is one band.
assert_eq!(band_rows(0, 2000, 8000), vec![(0, 2000)]);
}
+4
View File
@@ -37,6 +37,10 @@ use serde_json::{Map, Value as J, json};
use crate::blocks::{enum_of, get_desc, num};
#[cfg(test)]
#[path = "smart_map/halftone_tests.rs"]
mod halftone_tests;
#[path = "camera_raw_map.rs"]
mod camera_raw;
#[path = "displace_map.rs"]
+1 -1
View File
@@ -37,7 +37,7 @@ pub(super) fn pi(p: &J, key: &str, default: f64) -> Value {
/// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction
/// has no PSD equivalent (Photoshop stores these as integers).
fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result<Value, String> {
pub(super) fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result<Value, String> {
if v.fract() != 0.0 {
return Err(format!("{what} ({v}) is not a whole number"));
}
+207
View File
@@ -0,0 +1,207 @@
//! Halftone Pattern descriptors with the keys from the reference application's Filter Gallery plug-in terminology (#8940):
//! `HlSz` size, `Cntr` contrast and a `ScrT` enum (`ScrD` dot, `ScrC` circle, `ScrL` line).
use super::import::{GALLERY_CLASS, GALLERY_COMMAND, colour_rgbc};
use super::*;
/// Builds an editable Halftone Pattern filter with explicit foreground/background colours.
fn filter(pattern: &str, size: i32, contrast: i32) -> SmartFilter {
SmartFilter {
command: GALLERY_COMMAND.into(),
params: json!({
"effects": [{"filter": "halftonePattern", "params": {"size": size, "contrast": contrast, "patternType": pattern}, "visible": true}],
"foreground": [0.2, 0.4, 0.6, 1.0], "background": [0.8, 0.6, 0.4, 1.0],
}),
blend: BlendMode::Normal,
opacity: 1.0,
visible: true,
}
}
/// Builds the inline Halftone descriptor as the reference application writes it.
fn native_effect(pattern: &str, size: i32, contrast: i32) -> Descriptor {
let mut d = Descriptor::new("GEfc")
.with("GEfk", enumv("GEft", "HlfS"))
.with("HlSz", Value::Integer(size))
.with("Cntr", Value::Integer(contrast))
.with("ScrT", enumv("ScrT", pattern));
d.name = UnicodeString::new_nul("Filter Gallery");
d
}
/// Wraps a Gallery descriptor in a Photoshop smart-filter item.
fn native_item(effect: Descriptor) -> Descriptor {
let f = filter("dot", 2, 5);
Descriptor::new("filterFX")
.with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery...")))
.with("blendOptions", blend_options(&f))
.with("enab", Value::Boolean(true))
.with("hasoptions", Value::Boolean(true))
.with("FrgC", colour_rgbc(f.params.get("foreground"), 0.0).unwrap())
.with("BckC", colour_rgbc(f.params.get("background"), 1.0).unwrap())
.with("Fltr", Value::Descriptor(effect))
.with("filterID", Value::Integer(code(b"GEfc")))
}
/// Checks the pattern enums and editable settings in both mapping directions.
#[test]
fn halftone_pattern_reads_and_writes_photoshop_inline_descriptors() {
for (pattern, native) in [("dot", "ScrD"), ("circle", "ScrC"), ("line", "ScrL")] {
for (size, contrast) in [(1, 0), (2, 5), (7, 31), (12, 50)] {
let expected = filter(pattern, size, contrast);
let native = native_item(native_effect(native, size, contrast));
assert_eq!(filter_from_item(&native), expected);
let written = item_for_filter(&expected).unwrap();
assert_eq!(get_desc(&written, "Fltr"), get_desc(&native, "Fltr"));
assert_eq!(filter_from_item(&Descriptor::from_bytes(&written.to_bytes()).unwrap()), expected);
}
}
}
/// Keeps defaults, hidden effects, stack order, and blending intact on round trip.
#[test]
fn halftone_pattern_defaults_and_mixed_hidden_stack_round_trip() {
let defaults = SmartFilter { params: json!({"effects": [{"filter": "halftonePattern"}]}), ..filter("dot", 1, 5) };
assert_eq!(filter_from_item(&item_for_filter(&defaults).unwrap()).params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"}));
let mut f = filter("circle", 8, 22);
f.params["effects"][0]["visible"] = json!(false);
f.params["effects"].as_array_mut().unwrap().push(json!({"filter": "chrome", "params": {"detail": 4, "smoothness": 7}, "visible": true}));
f.opacity = 0.5;
f.blend = BlendMode::Multiply;
f.visible = false;
let item = item_for_filter(&f).unwrap();
assert!(get_desc(&item, "Fltr").unwrap().get("GEfs").is_some());
assert_eq!(filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()), f);
}
/// A default Halftone Pattern as the reference application saves it (size 1, contrast 5, Dot) opens editable.
#[test]
fn halftone_pattern_photoshop_default_imports_editable() {
let f = filter_from_item(&native_item(native_effect("ScrD", 1, 5)));
assert_eq!(f.command, GALLERY_COMMAND);
assert_eq!(f.params["effects"][0]["filter"], json!("halftonePattern"));
assert_eq!(f.params["effects"][0]["params"], json!({"size": 1, "contrast": 5, "patternType": "dot"}));
}
/// Keys the reference application's Filter Gallery doesn't use (`Sz `, `Ptrn` of type `HlfT`) are not taken for
/// Halftone settings: the item stays opaque and is written back as it was read.
#[test]
fn halftone_pattern_foreign_keys_stay_verbatim() {
for (pattern, shape) in [("Dt ", "dot"), ("Crc ", "circle"), ("Ln ", "line")] {
let mut d = Descriptor::new("GEfc")
.with("GEfk", enumv("GEft", "HlfS"))
.with("Sz ", Value::Integer(2))
.with("Cntr", Value::Integer(5))
.with("Ptrn", enumv("HlfT", pattern));
d.name = UnicodeString::new_nul("Filter Gallery");
let item = native_item(d);
let f = filter_from_item(&item);
assert_eq!(f.command, UNSUPPORTED_FILTER, "{shape}");
assert_eq!(item_for_filter(&f).unwrap(), item, "{shape}");
}
}
/// Preserves unfamiliar and malformed settings instead of substituting editable defaults.
#[test]
fn halftone_pattern_unknown_or_malformed_descriptors_stay_verbatim() {
let valid = native_effect("ScrD", 2, 5);
let mut invalid = vec![
valid.clone().with("futureSetting", Value::Integer(1)),
valid.clone().with("HlSz", Value::Integer(3)), // repeated key
];
for (key, value) in [
("GEfk", enumv("wrong", "HlfS")),
("ScrT", enumv("ScrT", "????")),
("ScrT", enumv("wrong", "ScrD")),
("ScrT", Value::Integer(0)),
("HlSz", Value::Integer(0)),
("HlSz", Value::Integer(13)),
("HlSz", Value::Double(2.0)),
("Cntr", Value::Integer(-1)),
("Cntr", Value::Integer(51)),
("GELv", Value::Integer(1)),
] {
let mut effect = valid.clone();
effect.items.retain(|(id, _)| !id.is(key));
effect.items.push((Id::new(key), value));
invalid.push(effect);
}
for missing in ["HlSz", "Cntr", "ScrT"] {
let mut effect = valid.clone();
effect.items.retain(|(id, _)| !id.is(missing));
invalid.push(effect);
}
for effect in invalid {
let item = native_item(effect);
let f = filter_from_item(&item);
assert_eq!(f.command, UNSUPPORTED_FILTER);
assert_eq!(item_for_filter(&f).unwrap(), item);
}
}
/// Keeps a whole Gallery stack opaque when a Halftone entry has an unfamiliar class ID.
#[test]
fn halftone_pattern_unknown_nested_class_stays_verbatim() {
let valid = native_effect("ScrD", 2, 5);
let mut unknown = valid.clone();
unknown.class_id = Id::new("Xxxx");
for effects in [vec![unknown.clone()], vec![valid.clone(), unknown.clone()], vec![unknown, valid]] {
let gallery = Descriptor::new(GALLERY_CLASS).with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect()));
let item = native_item(gallery);
let parsed = Descriptor::from_bytes(&item.to_bytes()).unwrap();
let filter = filter_from_item(&parsed);
assert_eq!(filter.command, UNSUPPORTED_FILTER);
assert_eq!(item_for_filter(&filter).unwrap().to_bytes(), item.to_bytes());
}
}
/// Rejects unsupported export values instead of silently changing their meaning.
#[test]
fn halftone_pattern_invalid_export_settings_are_reported() {
for (key, value) in [
("patternType", json!("triangle")),
("patternType", json!(2)),
("size", json!(0)),
("size", json!(13)),
("size", json!("2")),
("size", json!(2.5)),
("contrast", json!(-1)),
("contrast", json!(51)),
("contrast", json!(1e100)),
("contrast", json!(5.5)),
("futureSetting", json!(1)),
] {
let mut f = filter("dot", 2, 5);
f.params["effects"][0]["params"][key] = value;
assert!(item_for_filter(&f).is_err(), "{key}: {}", f.params);
}
}
/// Checks complete PSD/PSB round trips for every pattern at 8-, 16-, and 32-bit depth.
#[test]
fn halftone_pattern_survives_complete_psd_and_psb_export() {
use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource};
use photocraft_geom::Size;
use std::sync::Arc;
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for pattern in ["dot", "circle", "line"] {
let mut source = Document::new("synthetic contents", Size::new(2, 2), ColorMode::Rgb, sample);
let mut pixels = Surface::new(source.pixel_format());
pixels.fill_rect(source.bounds(), &[0.5, 0.5, 0.5, 1.0]);
source.layers.push(Layer::new("pixels", LayerContent::Raster(pixels.clone())));
let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap();
let mut smart =
SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, Some(pixels));
smart.smart_filters.push(filter(pattern, 2, 5));
let mut doc = Document::new("halftone", Size::new(2, 2), ColorMode::Rgb, sample);
doc.layers.push(Layer::new("halftone", LayerContent::Smart(smart)));
for ext in ["psd", "psb"] {
let out = crate::export(&doc, ext, &crate::ExportOptions::default()).unwrap();
assert!(!out.warnings.iter().any(|w| w.contains("smart filter")), "{ext}: {:?}", out.warnings);
let back = crate::import(ext, &out.bytes).unwrap().document;
let LayerContent::Smart(smart) = &back.layers[0].content else { panic!("smart object lost") };
assert_eq!(smart.smart_filters, vec![filter(pattern, 2, 5)], "{ext} {sample:?} {pattern}");
}
}
}
}
+39 -7
View File
@@ -1,4 +1,4 @@
use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc};
use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc, whole};
use super::placed::enumv;
use super::*;
@@ -596,7 +596,7 @@ pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descripto
// `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are
// mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`].
const GALLERY_CLASS: &str = "GEfc";
pub(super) const GALLERY_CLASS: &str = "GEfc";
pub(super) const GALLERY_COMMAND: &str = "filter.filterGallery";
@@ -609,7 +609,13 @@ pub(super) struct GalleryCode {
pub(super) settings: &'static [(&'static str, &'static str)],
}
pub(super) const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }];
pub(super) const GALLERY_EFFECTS: [GalleryCode; 2] = [
GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] },
GalleryCode { key: "halftonePattern", code: "HlfS", settings: &[("HlSz", "size"), ("Cntr", "contrast")] },
];
// Halftone Pattern's shape is a `ScrT` enum (Filter Gallery terminology: Dot, Circle, Line).
const HALFTONE_PATTERNS: [(&[u8; 4], &str); 3] = [(b"ScrD", "dot"), (b"ScrC", "circle"), (b"ScrL", "line")];
/// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1.
fn rgbc_colour(d: &Descriptor) -> Option<J> {
@@ -669,8 +675,22 @@ fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option<J> {
let code = enum_of(e, "GEfk")?;
let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?;
let mut params = Map::new();
if g.key == "halftonePattern" {
// Do not turn an unfamiliar shape or malformed setting into the engine's defaults:
// keeping the whole item opaque preserves it through a subsequent save.
if !e.class_id.is(GALLERY_CLASS)
|| !only_keys(e, &["GEfk", "HlSz", "Cntr", "ScrT", "GELv"])
|| !matches!(e.get("GEfk"), Some(Value::Enumerated { type_id, .. }) if type_id.is("GEft"))
|| e.get("GELv").is_some_and(|v| !matches!(v, Value::Boolean(_)))
{
return None;
}
int_in(e, "HlSz", 1, 12)?;
int_in(e, "Cntr", 0, 50)?;
params.insert("patternType".into(), json!(enum_name(e, "ScrT", "ScrT", &HALFTONE_PATTERNS)?));
}
for (k, v) in &e.items {
if k.is("GEfk") || k.is("GELv") {
if k.is("GEfk") || k.is("GELv") || g.key == "halftonePattern" && k.is("ScrT") {
continue;
}
let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?;
@@ -723,13 +743,25 @@ pub(super) fn gallery_item(f: &SmartFilter) -> Result<Descriptor, String> {
let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?;
let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e);
if let Some(k) = params.as_object().and_then(|o| {
o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k))
o.keys().find(|k| {
!is_meta(k)
&& !["filter", "params", "visible"].contains(&k.as_str())
&& !g.settings.iter().any(|(_, ours)| ours == k)
&& !(key == "halftonePattern" && *k == "patternType")
})
}) {
return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent"));
}
let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new);
let settings: Vec<(&str, Value)> =
g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect();
let settings: Vec<(&str, Value)> = if key == "halftonePattern" {
vec![
("HlSz", whole(pf_range(params, "size", 1.0, 1.0, 12.0)?, (1, 12), "size")?),
("Cntr", whole(pf_range(params, "contrast", 5.0, 0.0, 50.0)?, (0, 50), "contrast")?),
("ScrT", enum_param(params, "patternType", "dot", "ScrT", &HALFTONE_PATTERNS)?),
]
} else {
g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect()
};
out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true)));
}
let gallery = || {
+1 -1
View File
@@ -376,7 +376,7 @@ fn inflate(bytes: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, IoError> {
return Ok(std::borrow::Cow::Borrowed(bytes));
}
let mut out = Vec::new();
let mut reader = flate2::read::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1));
let mut reader = flate2::bufread::MultiGzDecoder::new(bytes).take(MAX_INFLATED_BYTES.saturating_add(1));
reader.read_to_end(&mut out).map_err(|e| IoError::Svg(format!("the compressed SVG couldn't be inflated: {e}")))?;
if u64::try_from(out.len()).unwrap_or(u64::MAX) > MAX_INFLATED_BYTES {
return Err(IoError::Svg(format!("the compressed SVG inflates past {} MB", MAX_INFLATED_BYTES >> 20)));
+1 -1
View File
@@ -118,7 +118,7 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<I
}
let channels = u16::try_from(img.layout().channels().saturating_add(added)).map_err(|_| IoError::Unsupported("too many channels".into()))?;
let header = Header::new(isd.version, w, h, channels, depth, mode);
let image_data = ImageData { compression: Compression::Raw, data };
let image_data = ImageData::new(Compression::Raw, data);
let mut file = isd.into_psd(header, resources, image_data);
// Empty `Patt` and the default filter mask are written so Photoshop's block list matches
// a file it saved. They carry nothing the document stores, so they are not kept: a
+145
View File
@@ -0,0 +1,145 @@
//! Backend compatibility, including native-format tile data rather than ZIP assembly alone.
use crate::common;
use std::io::Read;
use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CodecSample};
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, LayerContent};
use photocraft_format::{SaveOptions, load_from_bytes, read_thumbnail, save_to_bytes};
use photocraft_geom::Size;
use photocraft_io::{PsdExportOptions, document_to_psd_with, import};
use photocraft_psd::Compression;
use photocraft_raster::Rgba8Image;
fn document(depth: SampleType, size: Size) -> Document {
let mut doc = Document::new("compatibility", size, ColorMode::Rgb, depth);
doc.layers.push(Layer::new("pixels", LayerContent::Raster(common::pattern(doc.pixel_format(), doc.bounds(), 3, false))));
doc
}
/// Compare both decoders and generate a legacy stream without flate2 compression.
fn old_and_new_inflate(bytes: &[u8]) -> (Vec<u8>, Vec<u8>) {
let old = miniz_oxide::inflate::decompress_to_vec_zlib(bytes)
.unwrap_or_else(|e| panic!("old decoder: {:?}, header {:?}", e.status, &bytes[..bytes.len().min(8)]));
let legacy = miniz_oxide::deflate::compress_to_vec_zlib(&old, 6);
for stream in [bytes, legacy.as_slice()] {
let mut new = Vec::new();
flate2::read::ZlibDecoder::new(stream).read_to_end(&mut new).unwrap();
assert_eq!(new, old);
}
(old, legacy)
}
/// Read new PNGs and PNGs with legacy-miniz IDAT data through the codec.
fn check_png(bytes: &[u8], image: &Image) {
assert_eq!(photocraft_codecs::decode(bytes).unwrap().data(), image.data());
let mut idat = Vec::new();
let mut legacy_png = bytes[..8].to_vec();
let mut idat_offset = None;
let mut offset = 8;
while offset < bytes.len() {
let len = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize;
let end = offset + 12 + len;
if &bytes[offset + 4..offset + 8] == b"IDAT" {
idat_offset.get_or_insert(legacy_png.len());
idat.extend_from_slice(&bytes[offset + 8..offset + 8 + len]);
} else {
legacy_png.extend_from_slice(&bytes[offset..end]);
}
offset = end;
}
let (_, legacy) = old_and_new_inflate(&idat);
let mut chunk = (legacy.len() as u32).to_be_bytes().to_vec();
chunk.extend_from_slice(b"IDAT");
chunk.extend_from_slice(&legacy);
chunk.extend_from_slice(&crc32fast::hash(&chunk[4..]).to_be_bytes());
let at = idat_offset.unwrap();
legacy_png.splice(at..at, chunk);
assert_eq!(photocraft_codecs::decode(&legacy_png).unwrap().data(), image.data());
}
/// New zlib-rs streams and legacy-miniz streams preserve the same document samples.
#[test]
fn png_psd_and_pcraft_decode_identically() {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let doc = document(depth, Size::new(257, 131));
let pixels = doc.layers[0].surface().unwrap().read_region(doc.bounds());
if depth != SampleType::F32 {
let sample = if depth == SampleType::U8 { CodecSample::U8 } else { CodecSample::U16 };
let image = Image::from_normalized(257, 131, ChannelLayout::Rgba, sample, &pixels).unwrap();
check_png(&photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(), &image);
}
let raw_opts = PsdExportOptions { merged_compression: Compression::Raw, merged_matte: false, ..Default::default() };
let merged = document_to_psd_with(&doc, &raw_opts).0.image_data.data;
for compression in [Compression::Zip, Compression::ZipPrediction] {
let opts = PsdExportOptions { merged_compression: compression, merged_matte: false, ..Default::default() };
let mut file = document_to_psd_with(&doc, &opts).0;
// The IO exporter normally chooses Raw for float composites; also cover ZIP here.
if depth == SampleType::F32 {
file.image_data = photocraft_psd::ImageData::encode(compression, &merged, &file.header).unwrap();
}
let bytes = file.to_bytes().unwrap();
let parsed = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap();
assert_eq!(parsed.image_data.compression, compression);
let (inflated, legacy) = old_and_new_inflate(&parsed.image_data.data);
// The PSD streaming helper uses a different flate2 reader from plane decoding.
assert_eq!(photocraft_psd::compression::zip_decompress(&legacy, inflated.len()).unwrap(), inflated);
file.image_data.data = legacy;
for fixture in [bytes, file.to_bytes().unwrap()] {
let parsed = photocraft_psd::PsdFile::from_bytes(&fixture).unwrap();
assert_eq!(parsed.image_data.decode(&parsed.header).unwrap(), merged);
let back = import("compatibility.psd", &fixture).unwrap().document;
assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels);
}
}
let mut thumbnail = Rgba8Image::new(7, 3);
thumbnail.pixels = (0..84).map(|i| (i * 37) as u8).collect();
let opts = SaveOptions { thumbnail: Some(thumbnail.clone()), ..Default::default() };
let bytes = save_to_bytes(&doc, &opts).unwrap();
assert!(load_from_bytes(&bytes).unwrap() == doc, "all tile bytes, {depth:?}");
let image = Image::from_u8(7, 3, ChannelLayout::Rgba, thumbnail.pixels).unwrap();
check_png(&read_thumbnail(&bytes).unwrap().unwrap(), &image);
}
}
/// PDF export writes its image at the old backend's size or smaller: zlib-rs level 1
/// (`Compression::fast()`) writes static Huffman blocks only, which made PDFs of photos
/// 5-30% bigger than miniz's level 1 did.
#[test]
fn pdf_image_stream_is_no_bigger_than_miniz_fast() {
let (w, h) = (512u32, 384u32);
let mut doc = Document::new("photo", Size::new(w, h), ColorMode::Rgb, SampleType::U8);
// A noisy gradient: smooth like a photo, with sensor-like grain.
let mut x32 = 0x9E37_79B9u32;
let mut samples = Vec::with_capacity((w * h * 3) as usize);
let mut vals = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
for c in 0..3 {
x32 ^= x32 << 13;
x32 ^= x32 >> 17;
x32 ^= x32 << 5;
let base = (x * 160 / w + y * 80 / h + c * 20) as i32;
let v = (base + (x32 % 9) as i32 - 4).clamp(0, 255) as u8;
samples.push(v);
vals.push(common::g(v));
}
vals.push(1.0);
}
}
let mut surface = photocraft_raster::Surface::new(doc.pixel_format());
surface.write_region(doc.bounds(), &vals);
doc.layers.push(Layer::new("photo", LayerContent::Raster(surface)));
let pdf = photocraft_io::export(&doc, "photo.pdf", &Default::default()).unwrap().bytes;
let at = pdf.windows(15).position(|s| s == b"/Subtype /Image").unwrap();
let dict = &pdf[at..];
let len_at = dict.windows(8).position(|s| s == b"/Length ").unwrap() + 8;
let digits = dict[len_at..].iter().take_while(|b| b.is_ascii_digit()).count();
let len: usize = std::str::from_utf8(&dict[len_at..len_at + digits]).unwrap().parse().unwrap();
let start = dict.windows(7).position(|s| s == b"stream\n").unwrap() + 7;
let stream = &dict[start..start + len];
assert_eq!(miniz_oxide::inflate::decompress_to_vec_zlib(stream).unwrap(), samples);
let old = miniz_oxide::deflate::compress_to_vec_zlib(&samples, 1).len();
assert!(len <= old, "PDF image stream {len} bytes, miniz level 1 wrote {old}");
}
+2
View File
@@ -20,6 +20,7 @@ mod comps_artboards;
mod corpus;
mod corpus_regressions;
mod cylinder_warp;
mod deflate_compatibility;
mod effects_multi;
mod exif_resolution;
mod export_progress;
@@ -51,6 +52,7 @@ mod psd_damaged_merged;
mod psd_empty_channels;
mod psd_font_identity;
mod psd_frame_stroke;
mod psd_import_file;
mod psd_kerning;
mod psd_layer_block_length;
mod psd_maximize_compatibility;
+2 -2
View File
@@ -89,7 +89,7 @@ fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() {
for mode in [photocraft_psd::ColorMode::Indexed, photocraft_psd::ColorMode::Multichannel, photocraft_psd::ColorMode::Duotone] {
let mut file = layered(SampleType::U8, "x.psd");
file.header.color_mode = mode;
file.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: Vec::new() };
file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new());
assert!(import("flat-mode.psd", &file.to_bytes().unwrap()).is_err(), "{mode:?}");
}
}
@@ -98,7 +98,7 @@ fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() {
fn lost_extra_channels_are_reported_while_layers_remain_usable() {
let mut file = layered(SampleType::U8, "x.psd");
file.header.channels = 5;
file.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: Vec::new() };
file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new());
let result = import("extra-channel.psd", &file.to_bytes().unwrap()).unwrap();
assert_eq!(result.document.layer_count(), 1);
assert!(result.document.channels.is_empty());
+155
View File
@@ -0,0 +1,155 @@
//! `import_file` parses a PSD/PSB from the open file (channel data read as it is decoded) and must
//! open the same document, with the same warnings, as importing the file's bytes.
use photocraft_io::{ImportResult, import, import_file};
use photocraft_psd::testgen;
use photocraft_raster::Interrupt;
struct TempDir(std::path::PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("photocraft-import-file-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
fn write(&self, name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = self.0.join(name);
std::fs::write(&path, bytes).unwrap();
path
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// The document's debug form with every `…Id(n)` number blanked.
fn without_ids(doc: &photocraft_doc::Document) -> String {
let s = format!("{doc:?}");
let mut out = String::with_capacity(s.len());
let mut rest = s.as_str();
while let Some(at) = rest.find("Id(") {
out.push_str(&rest[..at + 3]);
rest = rest[at + 3..].trim_start_matches(|c: char| c.is_ascii_digit());
}
out.push_str(rest);
out
}
fn open(name: &str, path: &std::path::Path) -> Result<ImportResult, photocraft_io::IoError> {
import_file(name, path, &photocraft_io::ImportOptions::default(), &Interrupt::NONE)
}
#[test]
fn import_file_opens_what_importing_the_bytes_opens() {
let dir = TempDir::new("same");
let mut checked = 0;
for case in testgen::all_cases() {
let ext = if case.file.header.version.is_psb() { "psb" } else { "psd" };
let name = format!("case.{ext}");
let bytes = case.file.to_bytes().unwrap();
let path = dir.write(&name, &bytes);
let from_bytes = import(&name, &bytes);
let from_file = open(&name, &path);
match (from_bytes, from_file) {
(Ok(a), Ok(b)) => {
// Ids come from a process-wide counter, so the two opens differ only there.
assert!(without_ids(&b.document) == without_ids(&a.document), "{}", case.name);
assert_eq!(b.warnings, a.warnings, "{}", case.name);
checked += 1;
}
(Err(_), Err(_)) => {}
(a, b) => panic!("{}: bytes {:?}, file {:?}", case.name, a.map(|r| r.warnings), b.map(|r| r.warnings)),
}
}
assert!(checked > 50, "only {checked} cases opened");
}
#[test]
fn import_file_reads_other_formats_whole() {
let dir = TempDir::new("other");
let doc = photocraft_doc::Document::new("x", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8);
let png = photocraft_io::export(&doc, "x.png", &Default::default()).unwrap().bytes;
let path = dir.write("x.png", &png);
let r = open("x.png", &path).unwrap();
assert_eq!(r.document.size, doc.size);
}
#[test]
fn import_file_fails_cleanly() {
let dir = TempDir::new("fail");
assert!(open("missing.psd", &dir.0.join("missing.psd")).is_err());
let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Rle).to_bytes().unwrap();
// Cut inside the layer records, inside the channel data, and inside the merged image.
for cut in [10, 60, bytes.len() / 2, bytes.len() - 5] {
let name = format!("cut{cut}.psd");
let path = dir.write(&name, &bytes[..cut]);
let from_bytes = import(&name, &bytes[..cut]);
let from_file = open(&name, &path);
// The merged image is not read when the layers are what opens, so a file cut inside it
// can open from the file where the strict parse of its bytes refused it.
if from_bytes.is_ok() {
assert!(from_file.is_ok(), "cut at {cut}");
}
}
}
#[test]
fn a_cancelled_import_file_reports_cancelled() {
let dir = TempDir::new("cancel");
let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap();
let path = dir.write("c.psd", &bytes);
let cancel = || true;
let ctl = Interrupt::cancel_only(&cancel);
assert!(matches!(import_file("c.psd", &path, &photocraft_io::ImportOptions::default(), &ctl), Err(photocraft_io::IoError::Cancelled)));
}
/// A read that fails while the layers are decoded from the file (it is truncated or rewritten,
/// its drive goes away) fails the open: no layer is left empty for a save to lose.
#[test]
fn a_read_failing_while_layers_decode_fails_the_open() {
use photocraft_psd::ReadAt;
/// The file's bytes, failing every read of channel data (as a dropped network share or a
/// truncated file would) except the 2-byte compression fields the parse reads.
struct Failing {
bytes: Vec<u8>,
data: Vec<(u64, u64)>,
}
impl ReadAt for Failing {
fn len(&self) -> u64 {
self.bytes.len() as u64
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> {
let end = offset + buf.len() as u64;
if self.data.iter().any(|&(a, b)| offset < b && end > a) {
return Err(photocraft_psd::PsdError::Read("the drive went away".into()));
}
self.bytes.as_slice().read_at(offset, buf)
}
}
for c in [photocraft_psd::Compression::Rle, photocraft_psd::Compression::Raw, photocraft_psd::Compression::Zip] {
let file = testgen::layered(photocraft_psd::Version::Psd, photocraft_psd::ColorMode::Rgb, 8, c);
let bytes = file.to_bytes().unwrap();
let lazy = photocraft_psd::PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap();
let data: Vec<(u64, u64)> = lazy
.layers()
.iter()
.flat_map(|l| &l.channels)
.filter_map(|ch| ch.stored.as_ref())
.filter(|s| s.len > 0)
.map(|s| (s.offset, s.offset + s.len))
.collect();
assert!(!data.is_empty());
// Opening the same file whole succeeds: only the failed reads fail the open.
assert!(import("x.psd", &bytes).is_ok());
let r = photocraft_io::import_source_for_open_with("x.psd", photocraft_psd::Source::new(Failing { bytes, data }), &Interrupt::NONE);
match r {
Err(photocraft_io::IoError::Read(msg)) => assert!(msg.contains("the drive went away"), "{c:?}: {msg}"),
r => panic!("{c:?}: the open didn't fail: {:?}", r.map(|(r, damaged)| (r.warnings, damaged))),
}
}
}
+5 -6
View File
@@ -658,7 +658,7 @@ fn fill_layer_keeps_photoshop_pixels() {
VersionedDescriptor::new(Descriptor::new("null").with("Clr ", Value::Descriptor(c))).to_bytes()
};
// Photoshop-rendered pixels deliberately differ from the parametric fill.
let plane = |v: u8| ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![v; 4] };
let plane = |v: u8| ChannelData::new(0, Some(Compression::Raw), vec![v; 4]);
let mut chans = vec![plane(255), plane(10), plane(20), plane(30)];
for (i, c) in chans.iter_mut().enumerate() {
c.id = i as i16 - 1;
@@ -762,7 +762,7 @@ fn merged_composite_unmattes_photoshop_white() {
let mut f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1);
f.header.channels = 4;
// straight red at alpha 0.5, matted: r = 1, g = b = 0.5
f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data: vec![255, 128, 128, 128] };
f.image_data = photocraft_psd::ImageData::new(Compression::Raw, vec![255, 128, 128, 128]);
let m = merged_composite(&f).unwrap();
assert!((m[0][0] - 1.0).abs() < 0.01 && m[0][1] < 0.01 && m[0][2] < 0.01, "{:?}", m[0]);
let (d, _) = psd_to_document(&f);
@@ -772,8 +772,7 @@ fn merged_composite_unmattes_photoshop_white() {
// HDR and negative straight samples must survive the actual F32 PSD import boundary.
let mut hdr = testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, Compression::Raw, 1, 1);
hdr.header.channels = 4;
hdr.image_data =
photocraft_psd::ImageData { compression: Compression::Raw, data: [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect() };
hdr.image_data = photocraft_psd::ImageData::new(Compression::Raw, [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect());
assert_eq!(merged_composite(&hdr).unwrap(), vec![[2.0, -0.5, 0.0, 0.5]]);
let mut deep = testgen::merged_only(Version::Psd, ColorMode::Rgb, 16, Compression::Raw, 1, 1);
deep.header.channels = 4;
@@ -793,7 +792,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() {
f.layers_mut().push(LayerRecord {
name: b"shape".to_vec(),
mask: photocraft_psd::MaskData::Mask(mask),
channels: vec![photocraft_psd::ChannelData { id: -2, compression: Some(Compression::Raw), data: vec![] }],
channels: vec![photocraft_psd::ChannelData::new(-2, Some(Compression::Raw), vec![])],
blocks: vec![TaggedBlock::unicode_name("shape"), TaggedBlock::new(*b"SoCo", vec![]), TaggedBlock::new(*b"vmsk", vec![0; 8])],
..Default::default()
});
@@ -805,7 +804,7 @@ fn vector_rendered_mask_not_doubled_on_shapes() {
let record = f.layers_mut().last_mut().unwrap();
let photocraft_psd::MaskData::Mask(mask) = &mut record.mask else { panic!("fixture has a mask") };
mask.real = Some(photocraft_psd::RealMask { flags: 0, background: 255, rect: photocraft_psd::Rect { top: 0, left: 0, bottom: 1, right: 1 } });
record.channels.push(photocraft_psd::ChannelData { id: -3, compression: Some(Compression::Raw), data: vec![64] });
record.channels.push(photocraft_psd::ChannelData::new(-3, Some(Compression::Raw), vec![64]));
let (imported, _) = psd_to_document(&f);
assert_eq!(imported.layers.last().unwrap().content.kind_name(), "Shape");
let mask = imported.layers.last().unwrap().mask.as_ref().expect("selected real mask must survive synthetic cleanup");
+1 -1
View File
@@ -77,7 +77,7 @@ fn pixel_layers_with_unknown_blocks_stay_pixel_layers() {
// A normal pixel layer (pixels, flag clear) carrying an unknown block.
f.layers_mut()[0].blocks.push(extra());
// Flagged but with pixels: never dropped for an adjustment.
let plane = |id: i16| ChannelData { id, compression: Some(Compression::Raw), data: vec![200; 4] };
let plane = |id: i16| ChannelData::new(id, Some(Compression::Raw), vec![200; 4]);
let mut painted = adjustment_record("painted", vec![extra()]);
painted.rect = Rect::from_xywh(0, 0, 2, 2);
painted.channels = (-1..3).map(plane).collect();
+3
View File
@@ -432,6 +432,9 @@ fn svgz_is_inflated_with_a_size_cap() {
let r = import("drawing.svgz", &gzip(plain.as_bytes())).unwrap();
assert_eq!(r.document.layers.len(), 1);
assert!(close(px(&r.document, 4, 4), [0.0, 0.0, 1.0, 1.0]));
let split = plain.len() / 2;
let members = [gzip(&plain.as_bytes()[..split]), gzip(&plain.as_bytes()[split..])].concat();
assert!(close(px(&import("members.svgz", &members).unwrap().document, 4, 4), [0.0, 0.0, 1.0, 1.0]));
// A bomb: a few hundred KB of gzip holding more than the cap of whitespace.
let mut bomb = format!("<svg {NS} width=\"8\" height=\"8\">").into_bytes();
bomb.resize(usize::try_from(svg::MAX_INFLATED_BYTES).unwrap() + 1024, b' ');
+35
View File
@@ -1887,3 +1887,38 @@ fn resizing_with_bad_sizes_leaves_the_dual_tip_alone() {
b.resize_with_dual_brush(50.0);
assert_eq!(b.dual_brush.size, 20.0);
}
/// `touches` is true wherever `coverage_at` can be above 0, false only where it is 0 for sure.
#[test]
fn touches_covers_every_pixel_with_coverage() {
let b = BrushSettings { size: 6.0, ..brush() };
let mut r = StrokeRenderer::new(&b, None, 1.0);
r.push(&line(100.0, 300.0, 200.0));
r.finish();
for y in (0..400).step_by(3) {
for x in (0..500).step_by(3) {
if r.coverage_at(x, y) > 0.0 {
assert!(r.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})");
}
}
}
// Across the origin and tile edges (64 px): every pixel, both sides of each edge.
let mut o = StrokeRenderer::new(&b, None, 1.0);
o.push(&[StrokePoint::new(-70.0, -70.0, 1.0), StrokePoint::new(70.0, 70.0, 1.0)]);
o.finish();
for y in -140..140 {
for x in -140..140 {
if o.coverage_at(x, y) > 0.0 {
assert!(o.touches(Rect::new(x, y, x + 1, y + 1)), "({x}, {y})");
}
}
}
assert!(!o.touches(Rect::new(-128, 64, -64, 128)), "a tile the diagonal misses");
assert!(!o.touches(Rect::new(-200, -200, -128, -128)), "ends exactly at a tile edge");
assert!(o.touches(Rect::new(-200, -200, -127, -127)), "one pixel into the next tile");
assert!(r.touches(Rect::new(150, 199, 151, 201)));
assert!(!r.touches(Rect::new(0, 0, 50, 50)), "far from the stroke");
assert!(!r.touches(Rect::new(400, 400, 400, 400)), "empty");
assert!(r.touches(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX)), "huge, without a huge scan");
assert!(!r.touches(Rect::new(1_000_000, 1_000_000, i32::MAX, i32::MAX)));
}
+15
View File
@@ -1044,6 +1044,21 @@ impl StrokeRenderer {
self.ctx.stroke_mask_wet(c, self.cov.depth(x, y), self.dual.as_ref().map(|d| d.get(x, y)), x, y)
}
/// Whether any coverage tile overlaps `r`: outside them [`coverage_at`](Self::coverage_at) is
/// 0, so a caller scanning a big area can skip it.
pub fn touches(&self, r: Rect) -> bool {
if r.is_empty() {
return false;
}
let (t0x, t0y) = (r.x0.div_euclid(COV_TILE), r.y0.div_euclid(COV_TILE));
let (t1x, t1y) = ((r.x1 - 1).div_euclid(COV_TILE), (r.y1 - 1).div_euclid(COV_TILE));
let span = (i64::from(t1x) - i64::from(t0x) + 1).saturating_mul(i64::from(t1y) - i64::from(t0y) + 1);
if span > self.cov.tiles.len() as i64 {
return self.cov.tiles.keys().any(|&(tx, ty)| (t0x..=t1x).contains(&tx) && (t0y..=t1y).contains(&ty));
}
(t0y..=t1y).any(|ty| (t0x..=t1x).any(|tx| self.cov.tiles.contains_key(&(tx, ty))))
}
/// Dense final coverage over the stroke bounds.
pub fn dense_coverage(&self) -> (Rect, Vec<f32>) {
let b = self.bounds();
+10 -1
View File
@@ -13,6 +13,7 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB
| `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified files | Channel data keeps its original encoding. Unknown blocks and resources are stored raw. Exact padding is recorded wherever it can vary: tagged blocks, layer info, section trailers. |
| `from_bytes(to_bytes(f)) == f` for any model `f` | Canonical defaults: `padding: None` means "zero-pad to even", and the parser yields `None` whenever the file used that default. |
| Lazy decoding | The parser only copies encoded bytes. Channels are decoded when asked (`ChannelData::decode`, `ImageData::decode`). |
| Lazy reading | `PsdFile::from_source` reads only the structure. Channel data and the merged image stay in the source as `Stored` ranges and are read when decoded, so opening a 2 GB file doesn't need 2 GB for the file itself. The model equals what `from_bytes` builds, and it writes back the same bytes. |
| No compositing | `PsdBuilder` takes the merged image from the caller. Without one, it writes a white placeholder and sets `has_real_merged_data = false` in resource 1057. |
## Public API (overview)
@@ -22,6 +23,8 @@ A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB
PsdFile::from_bytes(&[u8]) -> Result<PsdFile>
PsdFile::from_bytes_and_merged(&[u8], want) -> Result<(PsdFile, Option<Result<Vec<u8>>>)>
// + decode_merged() when want(&file): ZIP inflated once
PsdFile::from_source(Source) -> Result<PsdFile> // channel data and merged image left in the source
PsdFile::from_source_and_merged_recovering(Source, want, recover)
PsdFile::to_bytes(&self) -> Result<Vec<u8>>
PsdFile::open(path) / save(path) // native only
PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement,
@@ -36,6 +39,11 @@ PsdFile::composite_rgba8() -> Result<RgbaImage>
PsdFile::resource(id), global_block(key), icc_profile(), resolution(),
has_real_merged_data(), merged_has_alpha(), validate()
// Sources (lazy reading)
trait ReadAt { len(), read_at(offset, buf) } // [u8], Vec<u8>, Arc<T>, FileSource (pread / seek_read)
Source::new(impl ReadAt) / read_vec(offset, len) // shared handle; equal when the same source
Stored { source, offset, len }::read() / read_part(at, len)
// Header
Header { version: Version::{Psd,Psb}, channels, width, height, depth, color_mode, reserved }
ColorMode::{Bitmap, Grayscale, Indexed, Rgb, Cmyk, Multichannel, Duotone, Lab, Unknown(u16)}
@@ -47,7 +55,8 @@ LayerRecord { rect, channels: Vec<ChannelData>, blend_mode, opacity, clipping, f
LayerRecord::name() // prefers `luni`
LayerRecord::section_divider(), section_type(), layer_id(), fill_opacity(), is_visible(),
block(key), block_mut(key), channel(id), channel_rect(id), decode_channel(id, depth, version)
ChannelData { id, compression: Option<Compression>, data } // encoded bytes kept verbatim
ChannelData { id, compression: Option<Compression>, data, stored: Option<Stored> } // encoded bytes kept verbatim
ChannelData::new(id, compression, data); encoded() -> Cow<[u8]>; encoded_len(); load()
ChannelData::encode(id, compression, decoded, w, h, depth, version)
ChannelData::decode(w, h, depth, version); set_decoded(...)
MaskData::{None, Mask(LayerMask), Raw(Vec<u8>)}
+2 -2
View File
@@ -11,12 +11,12 @@ fn main() -> Result<()> {
let plane_bytes = 6000 * 4000 * usize::from(depth / 8);
let mut layer = LayerRecord { rect: Rect::from_xywh(0, 0, 6000, 4000), name: b"RGB".to_vec(), ..Default::default() };
for id in 0..3 {
layer.channels.push(ChannelData { id, compression: Some(Compression::Raw), data: vec![0; plane_bytes] });
layer.channels.push(ChannelData::new(id, Some(Compression::Raw), vec![0; plane_bytes]));
}
file.layer_info = Some(LayerInfo { merged_alpha: false, layers: vec![layer], padding: None });
file.layer_info_placement =
LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, padding: None };
file.image_data = ImageData { compression: Compression::Raw, data: vec![0; plane_bytes * 3] };
file.image_data = ImageData::new(Compression::Raw, vec![0; plane_bytes * 3]);
black_box(file.to_bytes()?);
let mut samples = Vec::new();
let mut size = 0;
+3
View File
@@ -37,6 +37,9 @@ pub enum PsdError {
/// A compressed stream could not be decoded.
#[error("decompression failed: {0}")]
Decompress(String),
/// Reading from a [`crate::source::ReadAt`] source failed.
#[error("read failed: {0}")]
Read(String),
/// An operation is not supported for this data (e.g. unknown compression).
#[error("unsupported: {0}")]
Unsupported(String),
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more