Merge pull request #7995 from dotCooCoo/feat/psd-export-writes-slices

PSD export: slices are written, so an opened PSD's slices survive an export
This commit is contained in:
BFlat
2026-11-16 11:37:59 +07:00
committed by GitHub
6 changed files with 398 additions and 11 deletions
+1 -1
View File
@@ -308,7 +308,7 @@ const PSD_LAYERS: FormatOption = FormatOption {
name: "layers",
ty: "boolean",
default: "true",
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent",
description: "write layers: each top-level layer a pixel layer with its opacity and blend mode (a background colour is a Background layer); false: one flat image, on white where transparent. The user and object slices are written either way",
};
const MAX_EDITABILITY: FormatOption = FormatOption {
@@ -511,3 +511,75 @@ fn damaged_slices_never_panic() {
}
}
}
/// The PSD file `document.export` writes from `s`, with its layers or flat.
fn export(s: &mut Session, layers: bool) -> Vec<u8> {
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
#[test]
fn an_opened_files_slices_survive_a_psd_export() {
let link =
S { url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", argb: [255, 0x12, 0x34, 0x56], ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [0, 1, 2, 3], ..user("", [0, 12, 6, 18]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let f = with_resource(&psd(true), 1050, &v6(&[link, plain, html, auto], &[]));
let (mut s, _) = open(&f, json!({}));
let opened = slices(&s);
assert_eq!(opened.len(), 3);
for layers in [true, false] {
let out = export(&mut s, layers);
let (again, r) = open(&out, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
// The same rectangles and options; the auto slices are laid out again around them.
let mut got = slices(&again);
let mut want = opened.clone();
let order = |v: &mut Vec<(Rect, SliceOptions)>| v.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0).then(a.0.x0.total_cmp(&b.0.x0)));
order(&mut got);
order(&mut want);
assert_eq!(got, want);
let layout = again.doc().unwrap().doc.slice_layout();
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
assert_eq!(s.execute("document.psdInfo", &json!({"dataBase64": b64(&out)})).unwrap()["slices"], json!(3));
}
}
#[test]
fn object_slices_are_written_as_user_slices_and_html_text_as_its_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
let rect = r["id"].as_u64().unwrap();
s.execute("object.slice.make", &json!({"ids": [rect]})).unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
s.execute("object.slice.options", &json!({"kind": "noImage", "name": "box", "text": "<i>x</i>", "background": "#00ff00"})).unwrap();
let t = s.execute("text.create", &json!({"x": 100, "y": 50, "text": "A & B"})).unwrap()["id"].as_u64().unwrap();
s.execute("object.slice.make", &json!({"ids": [t]})).unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
s.execute("object.slice.options", &json!({"kind": "htmlText"})).unwrap();
let (again, _) = open(&export(&mut s, false), json!({}));
let got = slices(&again);
assert_eq!(got.len(), 2, "{got:?}");
let doc = &s.doc().unwrap().doc;
let rb = doc.slice_bounds(vectorcraft_doc::NodeId(rect)).unwrap();
let boxed = got.iter().find(|g| g.1.name == "box").unwrap();
// Within a pixel of the object's bounds.
for (a, b) in [(boxed.0.x0, rb.x0), (boxed.0.y0, rb.y0), (boxed.0.x1, rb.x1), (boxed.0.y1, rb.y1)] {
assert!((a - b).abs() <= 1.0, "{:?} against {rb:?}", boxed.0);
}
assert_eq!((boxed.1.kind, boxed.1.text.as_str(), boxed.1.background.as_str()), (SliceKind::NoImage, "<i>x</i>", "#00ff00"));
let text = got.iter().find(|g| g.1.name.is_empty()).unwrap();
assert_eq!((text.1.kind, text.1.text.as_str()), (SliceKind::NoImage, "A &amp; B"));
}
#[test]
fn twenty_exported_slices_open_again_with_the_one_whose_id_is_16() {
let columns: Vec<S> = (0..20).map(|x| user("", [x, 0, x + 1, 20])).collect();
let (mut s, _) = open(&with_resource(&psd(false), 1050, &v6(&columns, &[])), json!({}));
assert_eq!(slices(&s).len(), 20);
let (again, r) = open(&export(&mut s, true), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&again), slices(&s));
}
+166 -7
View File
@@ -1,14 +1,15 @@
//! PSD export: a layered bitmap at 8 bits per channel, written from the format's public
//! specification. The file holds the header, the resolution and colour profile resources, the
//! layer records and their channels (PackBits row by row; groups as section dividers), then the
//! specification. The file holds the header, the resolution, colour profile and slices resources,
//! the layer records and their channels (PackBits row by row; groups as section dividers), then the
//! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the
//! format keeps inks) or grayscale.
use std::collections::HashMap;
use std::sync::Arc;
use vectorcraft_color::{BlendMode, cms};
use vectorcraft_doc::text::TypeAntiAlias;
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind};
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource};
use vectorcraft_geom::{Point, Rect};
use super::jpeg::{self, ColorModel};
@@ -302,6 +303,8 @@ struct File {
records: Vec<Record>,
ppi: f64,
icc: Option<Arc<[u8]>>,
/// Image resource 1050's data, when the file has slices.
slices: Option<Vec<u8>>,
}
/// Refuse a size the format can't store.
@@ -332,7 +335,8 @@ impl File {
out.extend(mode(self.model).to_be_bytes());
// No colour mode data.
out.extend(0u32.to_be_bytes());
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile.
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the
// profile, the slices.
let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 };
let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32;
let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat();
@@ -341,6 +345,9 @@ impl File {
if let Some(icc) = &self.icc {
resource(&mut resources, 1039, icc)?;
}
if let Some(slices) = &self.slices {
resource(&mut resources, SLICES, slices)?;
}
out.extend(len32(resources.len())?.to_be_bytes());
out.extend(resources);
self.write_layers(&mut out)?;
@@ -390,17 +397,20 @@ fn icc(o: &PsdOptions) -> Result<Option<Arc<[u8]>>, String> {
pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result<Vec<u8>, String> {
let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img));
let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false);
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write()
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None }
.write()
}
/// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's
/// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it
/// paints, its opacity and blend mode in the layer's record.
/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach
/// into `region` are written with or without layers ([`slices`]).
pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result<Vec<u8>, String> {
let o = &opts.psd;
let scale = opts.scale();
let (width, height) = crate::region_pixels(region, scale);
check_size(width, height)?;
let slices = slices(doc, region, scale, (width, height))?;
let ro = opts.render_options(RasterFormat::Psd);
let (mut merged, mut alpha) = {
let px = r.render_region_with(doc, region, scale, &ro).to_straight();
@@ -426,7 +436,156 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast
merged.pop();
alpha = false;
}
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write()
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write()
}
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
/// The most slices one file holds (as many as `document.open` reads).
pub(crate) const MAX_SLICES: usize = 10_000;
/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads).
pub(crate) const MAX_SLICE_TEXT: usize = 65_536;
/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the
/// "Slices resource format" of the Photoshop File Formats Specification
/// (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>), version 6: the bounds of all
/// the slices, the group's name, the count, then one record per slice. `None` when no slice
/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]),
/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel
/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its
/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text
/// slice is written as No Image with its type's text as HTML. Text alignment is written as the
/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`]
/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]).
fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result<Option<Vec<u8>>, String> {
let users: HashMap<NodeId, &SliceOptions> = doc.slices.iter().map(|s| (s.id, &s.options)).collect();
let mut found = vec![];
for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) {
let Some(id) = area.id else { continue };
let r = area.rect;
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
let number = area.number;
return Err(format!("slice {number} has no finite bounds and can't be written to PSD"));
}
let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue };
// The part inside `region`, found before the region is rounded to whole pixels.
let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1));
if !(x0 < x1 && y0 < y1) {
continue;
}
let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max));
let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h));
// Whole pixels, at least one each way.
let span = |a: f64, b: f64, max: u32| {
let max = i64::from(max);
let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max));
if b <= a {
a = a.min(max - 1);
b = a + 1;
}
(a as i32, b as i32)
};
let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h));
let text = match options.kind {
SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(),
_ => options.text.clone(),
};
found.push(([l, t, r, b], options, text));
}
if found.is_empty() {
return Ok(None);
}
if found.len() > MAX_SLICES {
let count = found.len();
return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds"));
}
let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0);
for ([l, t, r, b], _, _) in &found {
(left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b));
}
let mut out = 6u32.to_be_bytes().to_vec();
for v in [top, left, bottom, right] {
out.extend(v.to_be_bytes());
}
let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s);
unicode(&mut out, stem)?;
out.extend((found.len() as u32).to_be_bytes());
// IDs from 1.
for ((rect, o, text), id) in found.into_iter().zip(1u32..) {
out.extend(id.to_be_bytes());
// Group 0; made by the user.
out.extend(0u32.to_be_bytes());
out.extend(2u32.to_be_bytes());
unicode(&mut out, &o.name)?;
out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes());
for v in rect {
out.extend(v.to_be_bytes());
}
for s in [&o.url, &o.target, &o.message, &o.alt] {
unicode(&mut out, s)?;
}
// The cell text is HTML, as a No Image slice shows it.
out.push(1);
unicode(&mut out, &text)?;
// The default horizontal and vertical alignment.
out.extend([0; 8]);
out.extend(background(o));
}
Ok(Some(out))
}
/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a
/// colour) or an opaque `#rrggbb`.
fn background(o: &SliceOptions) -> [u8; 4] {
let bg = o.background.trim();
if bg.eq_ignore_ascii_case("matte") {
return [0, 255, 255, 255];
}
let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()));
match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) {
Some(c) => {
let [_, r, g, b] = c.to_be_bytes();
[255, r, g, b]
}
None => [0; 4],
}
}
/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a
/// line break as `<br>` (CR LF is one break). Empty for anything but type.
fn html_text(n: &Node) -> String {
let NodeKind::Text(t) = &n.kind else { return String::new() };
t.plain_text()
.replace("\r\n", "\n")
.split(['\n', '\r', '\u{2029}'])
.map(|l| l.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;"))
.collect::<Vec<_>>()
.join("<br>")
}
/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past
/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`].
fn unicode(out: &mut Vec<u8>, s: &str) -> Result<(), String> {
let units = s.encode_utf16().count();
if units > MAX_SLICE_TEXT {
return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds"));
}
room(out.len(), units)?;
out.extend((units as u32).to_be_bytes());
out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes()));
Ok(())
}
/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes,
/// make it longer than the 4 GB a PSD resource holds.
pub(crate) fn room(len: usize, units: usize) -> Result<(), String> {
let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len));
match end.map(u32::try_from) {
Some(Ok(_)) => Ok(()),
_ => Err("the slices are too large for PSD (at most 4 GB)".into()),
}
}
/// Draws the parts of a document as layer records, bottom first.
+146 -3
View File
@@ -1,15 +1,16 @@
//! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups,
//! hidden layers), the merged image, the colour models, and a reader's view of the file.
//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the
//! file.
use std::sync::Arc;
use vectorcraft_color::{BlendMode, Color};
use vectorcraft_doc::{Document, LayerColor, Node};
use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use vectorcraft_testkit::fixtures::DocBuilder;
use super::jpeg::ColorModel;
use super::psd::{MAX_SIDE, PsdOptions};
use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room};
use super::*;
/// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply
@@ -735,3 +736,145 @@ fn long_unicode_name_is_cut_on_a_character_boundary() {
let file = export(&b.build(), &opts(PsdOptions::default()));
assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254));
}
/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice.
fn sliced() -> Document {
let mut d = doc();
let red = d.layers[0].children().unwrap()[0].id;
let user = SliceOptions {
name: "banner".into(),
url: "https://example.com/".into(),
target: "_blank".into(),
message: "Go".into(),
alt: "Banner".into(),
background: "#123456".into(),
..SliceOptions::default()
};
let id = d.alloc_id();
d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user });
let cell = SliceOptions { kind: SliceKind::NoImage, text: "<b>Hi</b>".into(), background: "matte".into(), ..SliceOptions::default() };
d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell));
d
}
/// The slices resource of `file` as an independent reader reads it.
fn slices_of(file: &[u8]) -> Option<craft_psd::slices::SlicesResource> {
let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes");
psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes"))
}
#[test]
fn slices_are_written_with_or_without_layers() {
let d = sliced();
for layers in [true, false] {
let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() }));
let res = slices_of(&file).expect("the slices resource");
assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1"));
let s = &res.slices;
assert_eq!(s.len(), 2, "{s:?}");
// Laid out top to bottom: the user slice, then the object slice, both written as made by
// the user.
let user = &s[0];
assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15]));
assert_eq!(
(user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()),
("banner", "https://example.com/", "_blank", "Go", "Banner")
);
assert_eq!(user.color, [255, 0x12, 0x34, 0x56]);
let cell = &s[1];
assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40]));
assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "<b>Hi</b>", true));
assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte");
assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0));
}
// A document without slices has no slices resource.
assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none());
}
#[test]
fn slices_are_cut_to_the_exported_region_in_its_pixels() {
let doc = sliced();
// The right part at 2 px a point: the user slice is cut at the region's left edge, and the red
// square's slice ends at that edge.
let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) };
let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
let res = slices_of(&file).unwrap();
assert_eq!(res.slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[0, 10, 20, 30]]);
assert_eq!(res.bounds, [10, 0, 30, 20]);
// A region no slice reaches has none.
let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
assert!(slices_of(&file).is_none());
// A slice thinner than a pixel keeps one pixel.
let mut thin = doc.clone();
thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0);
let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap();
assert_eq!(res.slices[0].rect, [20, 5, 21, 15]);
// The overlap is found before the region is rounded to whole pixels: a slice inside a region
// that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written.
let o = opts(PsdOptions::default());
let mut edge = doc.clone();
edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0);
edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None;
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap();
assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[9, 5, 10, 15]]);
edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0);
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap();
assert!(slices_of(&file).is_none());
}
#[test]
fn an_html_text_slice_writes_one_break_for_each_line_ending() {
use vectorcraft_doc::{CharStyle, NodeKind, TextObject};
use vectorcraft_geom::Point;
let mut d = DocBuilder::new(100.0, 60.0).build();
let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() });
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() }));
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap();
assert_eq!(res.slices[0].cell_text, "A<br>B<br>C<br>D<br>E");
}
#[test]
fn slice_ids_count_from_1_and_the_limits_are_errors() {
let mut doc = doc();
for i in 0..20 {
let id = doc.alloc_id();
let x = f64::from(i) * 5.0;
doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() });
}
let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap();
let ids: Vec<u32> = res.slices.iter().map(|s| s.id).collect();
assert_eq!(ids, (1..=20).collect::<Vec<_>>());
let export_err = |d: &Document| {
Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default()
};
let mut long = doc.clone();
long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1);
let e = export_err(&long);
assert!(e.contains("characters"), "{e}");
let mut many = doc.clone();
many.slices = (0..=MAX_SLICES as u64)
.map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() })
.collect();
let e = export_err(&many);
assert!(e.contains("slices"), "{e}");
// Not clipped to the artboard, a slice keeps bounds that aren't finite.
let mut bad = doc;
bad.slices_clip_to_artboard = false;
bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0);
let e = export_err(&bad);
assert!(e.contains("finite"), "{e}");
}
#[test]
fn slices_past_4_gb_are_an_error_before_they_are_written() {
let max = u32::MAX as usize;
assert_eq!(room(0, MAX_SLICE_TEXT), Ok(()));
assert_eq!(room(max - 4 - 2 * 10, 10), Ok(()));
let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default();
assert!(e.contains("4 GB"), "{e}");
assert!(room(max, 0).is_err());
assert!(room(0, usize::MAX).is_err());
}
+12
View File
@@ -8929,6 +8929,18 @@ has the option as Preserve Text Editability
{"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"preserveText":true}}}
```
With or without layers, the file keeps the document's slices in image resource 1050, in version 6 of the slices
resource format of the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/).
`importSlices` reads that form, so the slices of an opened PSD file come back when the export is opened. The rest are
VectorCraft's own rules:
- The user and object slices that reach into the exported artboard are written, each clipped to it, in its pixels,
at least one pixel each way. Auto slices aren't written; the document that opens the file lays them out again.
- An object slice is written as a user slice over its object's bounds. Each slice keeps its name, its type (Image
or No Image), its link, target, message, alternative text, cell text and background color. An HTML Text slice is
written as No Image with its type's text as HTML. Text alignment is written as the default.
- More than 10000 slices, a slice text longer than 65536 characters, or a slice without finite bounds is an error.
PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the
flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK
(converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution.
+1
View File
@@ -1929,6 +1929,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before (`crates/engine/src/cmd/fileio/tests_psdread.rs`).
- Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`).
The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged.
- PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`).
- PCX files (`.pcx`) open and place, from the ZSoft PCX Technical Reference Manual: 1 bit in the header palette's first two colors (black and white when the version has no palette or both colors are the same), 1 bit in two to four planes and 4 bits with up to 16 colors from the header's palette (the EGA colors for versions 0 and 3), 2 bits in the CGA colors that the header's CGA palette settings pick (background, color burst, palette and intensity), 8 bits with the 256-color palette after the image data (gray levels without one) and 24-bit color in three planes, run-length encoded. The header's HDpi and VDpi size the image. A file of another depth or plane count, one cut short, and one whose pixels as RGBA pass the pixel allowance are refused with a message before its pixels are decoded. Open and Place recognize a PCX file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a PCX file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_pcxread.rs`).
- Pixar picture files (`.pxr`) open, place and paste, from "The Format of Stored Pictures" in the Pixar Image Computer manuals: any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded with all four packet kinds and block ends, in tiles of any size (pixels of border tiles past the picture are dropped). R alone is gray, a missing color channel is 0 and a missing A opaque; 12-bit samples are clamped to 0.0 to 1.0; color matted to black becomes straight color; a null tile is transparent when the picture has A and black otherwise. The offsets aren't read, and the image takes the default resolution. Version 2 headers read like version 0. A file cut short, one with a tile whose writing wasn't finished, one with header values or packets the format doesn't define, and one whose pixels as RGBA pass the pixel allowance are refused with a message. Every reader recognizes a Pixar file by its magic number. Tested on synthetic files only (`crates/engine/src/cmd/fileio/tests_pxrread.rs`).
- JPEG 2000 JP2 and raw codestream images open and place from `.jpf`, `.jpx`, `.jp2`, `.j2k`, `.j2c` and `.jpc`. Each axis uses the valid display resolution (`resd`), else the valid capture resolution (`resc`), whichever box comes first ([ITU-T T.800](https://www.itu.int/rec/T-REC-T.800/en), I.5.3.7.2); an axis with none uses 72 ppi. Multiple codestreams, JPX composition or layers, and unsupported color spaces are refused with a message. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_jp2read.rs`).