Merge pull request #7817 from dotCooCoo/feat/psd-import-options-import-slices-after-7649

PSD: Import Slices brings a file's slices in as user slices on Open and Place
This commit is contained in:
BFlat
2026-11-15 20:45:50 +07:00
committed by GitHub
19 changed files with 2006 additions and 47 deletions
+6
View File
@@ -54,6 +54,7 @@ pub mod ppi;
pub mod progress;
mod psdlayers;
pub mod psdread;
mod psdslices;
mod pxrread;
mod save;
mod screens;
@@ -93,6 +94,9 @@ pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
@@ -240,6 +244,8 @@ mod tests_psd;
mod tests_psdlayers;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_psdslices;
#[cfg(test)]
mod tests_heifread;
File diff suppressed because one or more lines are too long
+17 -8
View File
@@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
"psd" | "psb" if opts.layers => {
let cms = vectorcraft_color::cms::active();
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
}
}
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
},
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
};
// A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on),
// whether its layers or its merged image came in.
if matches!(format.id, "psd" | "psb")
&& opts.import_slices
&& let Some(canvas) = doc.artboards.first().map(|a| a.rect)
{
let (slices, notes) = super::psd_slices(bytes, canvas);
for (rect, options) in slices {
crate::cmd::slices::add_slice(&mut doc, rect, options);
}
warnings.extend(notes);
}
// A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
if matches!(format.id, "pdf" | "ai" | "ait")
+9 -1
View File
@@ -36,6 +36,8 @@ pub struct LoadOptions {
pub layers: bool,
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
pub hidden_layers: bool,
/// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out).
pub import_slices: bool,
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
pub dxf: vectorcraft_cad::ImportOptions,
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
text_as: TextAs::default(),
layers: true,
hidden_layers: false,
import_slices: true,
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
@@ -81,7 +84,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -111,6 +114,10 @@ impl LoadOptions {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
};
let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?,
};
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
None => (true, false),
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
@@ -137,6 +144,7 @@ impl LoadOptions {
text_as,
layers,
hidden_layers,
import_slices,
dxf,
editing_data,
trust_editing_data,
+64
View File
@@ -43,6 +43,7 @@ use std::cell::Cell;
use std::sync::Arc;
use image::RgbaImage;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_color::blend::{blend_rgb, composite};
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
@@ -51,6 +52,7 @@ use vectorcraft_geom::Affine;
use super::load::{RasterImage, as_png};
use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb};
use crate::cmd::Session;
use crate::cmd::place::text::mac_roman;
/// Most layer groups inside one another.
@@ -1527,3 +1529,65 @@ pub(super) fn import(
doc.limit_depth_noting(&mut warnings);
Ok(Some((doc, warnings)))
}
/// [`import`] within the memory allowed for one image, CMYK converted with the active color
/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with.
pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result<Option<(Document, Vec<String>)>, String> {
let cms = vectorcraft_color::cms::active();
import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false))
}
/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PsdInfo {
/// The large document format.
pub psb: bool,
/// The canvas, in pixels.
pub width: u32,
pub height: u32,
/// The layers, group markers left out.
pub layers: usize,
/// The layers among them that are hidden.
pub hidden: usize,
/// The layer groups.
pub groups: usize,
/// The slices that come in with `importSlices` (those generated automatically, and those
/// outside the canvas, left out).
pub slices: usize,
}
/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records
/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it
/// opens and places as its merged image.
pub fn info(bytes: &[u8]) -> Result<PsdInfo, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default();
let layers = records.iter().filter(|r| r.divider == 0);
Ok(PsdInfo {
psb: h.psb,
width: h.width,
height: h.height,
layers: layers.clone().count(),
hidden: layers.filter(|r| r.hidden).count(),
groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(),
slices: super::psdslices::count(bytes),
})
}
const INFO: &str = "document.psdInfo";
/// `document.psdInfo`.
pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result<Value> {
let bytes = super::source(p, INFO)?.bytes;
let i = info(&bytes).map_err(super::load::err)?;
Ok(json!({
"format": if i.psb { "psb" } else { "psd" },
"width": i.width,
"height": i.height,
"layers": i.layers,
"hiddenLayers": i.hidden,
"groups": i.groups,
"slices": i.slices,
}))
}
+2 -2
View File
@@ -105,7 +105,7 @@ pub(super) struct Header<'a> {
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
palette: &'a [u8],
/// The image resources.
resources: &'a [u8],
pub(super) resources: &'a [u8],
/// The layer and mask information.
pub(super) layers: &'a [u8],
}
@@ -172,7 +172,7 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
/// blocks whose signature is `8BIM` are given.
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
let mut r = Reader::new(resources);
std::iter::from_fn(move || {
if r.rest().is_empty() {
+408
View File
@@ -0,0 +1,408 @@
//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place`
//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's
//! public Photoshop File Formats Specification
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Version 6 stores the slices
//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning
//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them
//! (<https://github.com/Agamnentzar/ag-psd>, `src/imageResources.ts` and `src/descriptor.ts`),
//! which agrees with psd.rb (<https://github.com/layervault/psd.rb>,
//! `lib/psd/resources/slices.rb`) on the keys both read.
//!
//! A slice the file marks as generated automatically is left out: the document lays out its own
//! auto slices around the others. A slice that follows a layer comes in as a user slice over the
//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its
//! link, target, message, alternative text, cell text and background color; text alignment isn't
//! read. The file is untrusted: every read is checked, and the slice count, the strings and the
//! descriptor's nesting and item count are capped.
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use super::psdread::{Reader, TRUNCATED, header, resources};
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
/// The most slices one file brings in.
const MAX_SLICES: usize = 10_000;
/// The deepest descriptor objects and lists nest.
const MAX_DEPTH: usize = 16;
/// The most values the descriptors of one slices resource hold together, nested ones included.
const MAX_VALUES: usize = 200_000;
/// The error of descriptors that hold more than [`MAX_VALUES`].
const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values";
/// One slice as the file stores it.
#[derive(Clone, Debug, PartialEq)]
struct PsdSlice {
/// Left, top, right and bottom, in the canvas's pixels.
rect: [i64; 4],
options: SliceOptions,
}
/// The slices a file stores, those generated automatically left out, and its canvas.
struct Stored {
slices: Vec<PsdSlice>,
/// The canvas's width and height, in pixels.
size: (u32, u32),
}
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB
/// file, or its slices can't be read.
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) };
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
}
/// The slices of resource 1050's `data`.
fn decode(data: &[u8]) -> Result<Vec<PsdSlice>, String> {
let mut r = Reader::new(data);
// The values every descriptor of the resource may hold together.
let mut budget = MAX_VALUES;
match r.u32()? {
6 => version_6(&mut r, &mut budget),
7 | 8 => {
if r.u32()? != 16 {
return Err("the slices' descriptor has a version other than 16".into());
}
let d = descriptor(&mut r, 0, &mut budget)?;
from_descriptor(&d)
}
v => Err(format!("the slices are stored in version {v}, which isn't read")),
}
}
/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record.
/// The descriptors that follow the records spend one `budget` of values between them.
fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, String> {
r.take(16)?;
unicode(r)?;
let count = r.u32()? as usize;
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let mut out = vec![];
for _ in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
// A slice that follows a layer gives the layer's ID.
if origin == 1 {
r.take(4)?;
}
let name = unicode(r)?;
let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image };
let mut rect = [0i64; 4];
for v in &mut rect {
*v = i64::from(r.u32()? as i32);
}
let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?);
let html = r.u8()? != 0;
let cell = unicode(r)?;
// The horizontal and vertical alignment.
r.take(8)?;
let [a, red, green, blue] = r.array::<4>()?;
let background = if a == 0 && red == 0 && green == 0 && blue == 0 {
String::new()
} else if a == 0 {
"matte".into()
} else {
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
Ok(_) => {
let used = r.rest().len() - ahead.rest().len();
r.take(used)?;
}
Err(e) if e == TOO_MANY_VALUES => return Err(e),
Err(_) => {}
}
}
// Origin 0 is a slice generated automatically.
if origin != 0 {
let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() };
out.push(PsdSlice { rect, options: for_kind(options) });
}
}
Ok(out)
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
if list.len() > MAX_SLICES {
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
}
let mut out = vec![];
for s in list {
let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) };
if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") {
continue;
}
let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) };
let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string());
let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?];
let text = |k: &str| match field(s, k) {
Some(Value::Text(t)) => t.clone(),
_ => String::new(),
};
let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image };
let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true)));
let background = match field(s, "bgColorType") {
Some(Value::Enum(_, v)) if v == "matte" => "matte".into(),
Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") {
Some(Value::Object(c)) => {
let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255));
match (channel("Rd "), channel("Grn "), channel("Bl ")) {
(Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"),
_ => String::new(),
}
}
_ => String::new(),
},
_ => String::new(),
};
let options = SliceOptions {
kind,
name: text("Nm "),
url: text("url"),
target: text("null"),
message: text("Msge"),
alt: text("altTag"),
text: cell_text(text("cellText"), html),
background,
..Default::default()
};
out.push(PsdSlice { rect, options: for_kind(options) });
}
Ok(out)
}
/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No
/// Image slice has no link, target, message or alternative text.
fn for_kind(mut o: SliceOptions) -> SliceOptions {
if o.kind == SliceKind::Image {
o.text.clear();
} else {
for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] {
s.clear();
}
}
o
}
/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped.
fn cell_text(text: String, html: bool) -> String {
if html { text } else { text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") }
}
/// The longest text one string, key or class ID holds (UTF-16 units or bytes).
const MAX_TEXT: usize = 65_536;
/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`].
fn text_len(n: usize) -> Result<usize, String> {
if n > MAX_TEXT {
return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read"));
}
Ok(n)
}
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
Long(i32),
Double(f64),
Bool(bool),
Text(String),
/// An enumeration's type and value.
Enum(String, String),
Object(Vec<(String, Value)>),
List(Vec<Value>),
/// A value of another type, read past.
Other,
}
/// The value with key `key`.
fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
d.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// A whole number: a long, or a finite double rounded.
fn number(v: Option<&Value>) -> Option<i64> {
match v? {
Value::Long(n) => Some(i64::from(*n)),
Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64),
_ => None,
}
}
/// A key or class ID: a length, then that many characters, or four when the length is 0.
fn id(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let b = r.take(if n == 0 { 4 } else { n })?;
Ok(String::from_utf8_lossy(b).into_owned())
}
/// A class: its Unicode name, then its ID.
fn class(r: &mut Reader<'_>) -> Result<(), String> {
unicode(r)?;
id(r)?;
Ok(())
}
/// A descriptor: its class, the count of its items, then each item's key, type and value.
fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result<Vec<(String, Value)>, String> {
if depth > MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
class(r)?;
let count = r.u32()? as usize;
let mut out = vec![];
for _ in 0..count {
let key = id(r)?;
let kind = r.array::<4>()?;
out.push((key, value(r, &kind, depth, budget)?));
}
Ok(out)
}
/// A value of type `kind`.
fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result<Value, String> {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
Ok(match kind {
b"long" => Value::Long(r.u32()? as i32),
b"doub" => Value::Double(f64::from_be_bytes(r.array()?)),
b"UntF" => {
r.take(4)?;
Value::Double(f64::from_be_bytes(r.array()?))
}
b"UnFl" => {
r.take(4)?;
Value::Double(f64::from(f32::from_be_bytes(r.array()?)))
}
b"bool" => Value::Bool(r.u8()? != 0),
b"TEXT" => Value::Text(unicode(r)?),
b"enum" => Value::Enum(id(r)?, id(r)?),
b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?),
b"VlLs" => {
if depth >= MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
let count = r.u32()? as usize;
let mut items = vec![];
for _ in 0..count {
let kind = r.array::<4>()?;
items.push(value(r, &kind, depth + 1, budget)?);
}
Value::List(items)
}
b"comp" => {
r.take(8)?;
Value::Other
}
b"type" | b"GlbC" => {
class(r)?;
Value::Other
}
b"tdta" | b"alis" => {
let n = r.u32()? as usize;
r.take(n)?;
Value::Other
}
b"obj " => {
let count = r.u32()? as usize;
for _ in 0..count {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
match &r.array::<4>()? {
b"prop" => {
class(r)?;
id(r)?;
}
b"Clss" => class(r)?,
b"Enmr" => {
class(r)?;
id(r)?;
id(r)?;
}
b"rele" => {
class(r)?;
r.take(4)?;
}
b"Idnt" | b"indx" => {
r.take(4)?;
}
b"name" => {
class(r)?;
unicode(r)?;
}
k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))),
}
}
Value::Other
}
k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))),
})
}
/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points),
/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no
/// size, and for slices that can't be read (the file comes in without them). Empty, without a
/// warning, when the file stores no slices.
pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
match read(bytes) {
Ok(None) => (vec![], vec![]),
Ok(Some(s)) => laid_over(&s.slices, s.size, canvas),
Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]),
}
}
/// `slices` of a canvas of `size` pixels laid over `canvas` (points).
fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1)));
let mut out = vec![];
for s in slices {
let [l, t, r, b] = s.rect;
let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w)));
let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h)));
if l < r && t < b {
let x = |v: i64| canvas.x0 + v as f64 * sx;
let y = |v: i64| canvas.y0 + v as f64 * sy;
out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone()));
}
}
let warnings = match slices.len() - out.len() {
0 => vec![],
1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()],
n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")],
};
(out, warnings)
}
/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none
/// or they can't be read.
pub(crate) fn count(bytes: &[u8]) -> usize {
match read(bytes) {
Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(),
_ => 0,
}
}
+187 -1
View File
@@ -1,7 +1,8 @@
//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and
//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers
//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export
//! read back, and damaged files read without a panic.
//! read back, and damaged files read without a panic. Placing them with their layers as objects
//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`.
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
@@ -967,10 +968,12 @@ fn damaged_layers_never_panic() {
let mut f = good.clone();
f[i] = v;
let _ = psdlayers::import(&f, true, 1 << 30, cms);
let _ = psdlayers::info(&f);
}
}
for n in 0..good.len() {
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
let _ = psdlayers::info(&good[..n]);
}
// A layer past the memory allowed is refused, not read.
assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large"));
@@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() {
assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}");
}
}
/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50).
fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result<Value>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p));
(s, r)
}
/// The one object `file.place` placed.
fn placed(s: &Session, r: &Value) -> Node {
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn placing_with_layers_embeds_the_layers_as_one_group() {
let f = file(8, 8, &stack(), 8, false, false);
let (mut s, r) = place(&f, json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}");
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas");
assert_eq!(name(&g), "layers.psd");
let kids = g.children().unwrap();
assert_eq!(kids.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first");
// A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50).
let ((x, y), px) = pixels_of(&s, &kids[0]);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255]));
// A group is a group of its layers; a pass-through group isn't isolated, another mode's is.
let folder = &kids[1];
assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal);
let inner = folder.children().unwrap();
assert_eq!(inner.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner A"], "the hidden layer is left out");
assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6);
let screens = &kids[2];
assert!(screens.isolate && screens.blend == BlendMode::Screen);
let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]);
assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128]));
assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity);
// One undo step.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)));
// Hidden layers come in hidden when asked for.
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
assert_eq!(r["warnings"], json!([]), "{r}");
let g = placed(&s, &r);
let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect();
assert_eq!(inner, [("Inner A", true), ("Inner B", false)]);
// Without `layers`, the merged image, in the same box.
let (s, r) = place(&f, json!({}));
let r = r.unwrap();
let flat = placed(&s, &r);
let ((x, y), px) = pixels_of(&s, &flat);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}");
}
#[test]
fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() {
let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]);
masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255]));
let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true}));
let g = placed(&s, &r.unwrap());
let kids = g.children().unwrap();
assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image");
let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask");
let ((x, y), px) = pixels_of(&s, &m.art);
assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer");
// A layer that reaches past the canvas: the group is clipped to the canvas, as the merged
// image shows only the canvas.
let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]);
let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
let kids = g.children().unwrap();
let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap();
assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. }));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas");
assert_eq!(kids[1..].iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Over"]);
assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0));
// A hidden layer that reaches past the canvas clips the group too, so showing it later draws
// only the canvas. Left out, it doesn't.
let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]);
hidden.hidden = true;
let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false);
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::<Vec<_>>(), [("Bottom", true), ("Hidden", false)]);
let (s, r) = place(&f, json!({"layers": true}));
assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. }));
}
#[test]
fn placing_with_layers_never_links_and_refuses_values_it_cant_use() {
let f = file(8, 8, &stack(), 8, false, false);
let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("layers.psd");
std::fs::write(&path, &f).unwrap();
let from_path = |p: Value| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p));
(s, r)
};
// From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused.
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(false), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. }));
let (s, r) = from_path(json!({"layers": true, "link": true}));
assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image"));
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed");
// Without `layers` the file is linked as before.
let (s, r) = from_path(json!({}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(true), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// A file without layers is embedded as its merged image, without a warning.
let flat = {
let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false);
let at = 26 + 8;
let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize;
f.splice(at..at + 4 + len, 0u32.to_be_bytes());
f
};
std::fs::write(&path, &flat).unwrap();
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that are all left out: the merged image, with the importer's warnings.
let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]);
gone.hidden = true;
let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that can't be read: the merged image, with a warning.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
let (s, r) = place(&cut, json!({"layers": true}));
let r = r.unwrap();
assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Values the command can't use are errors, and nothing is placed.
for (p, why) in [
(json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"),
(json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"),
(json!({"layers": "yes"}), "layers must be true or false"),
(json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"),
] {
let (s, r) = place(&f, p.clone());
assert!(r.unwrap_err().to_string().contains(why), "{p}");
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}");
}
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"}));
assert!(q.unwrap_err().to_string().contains("`layers` must be true or false"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_layers_without_opening_the_file() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)}));
let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap();
assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0}));
let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap();
assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}");
// Layer records that can't be read count as no layers: the file opens as its merged image.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0));
assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file"));
}
@@ -0,0 +1,459 @@
//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices
//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8
//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format";
//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and
//! moved in one undo step, linked files, and `document.psdInfo`'s count.
use serde_json::{Value, json};
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use crate::Session;
/// A Unicode string: a count of UTF-16 units, then the units.
fn ustr(s: &str) -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
}
/// One version 6 slice record.
#[derive(Clone)]
struct S {
/// 0: generated automatically, 1: follows a layer, 2: made by the user.
origin: u32,
name: &'static str,
/// 0: No Image, 1: Image.
kind: u32,
/// Left, top, right, bottom (px).
rect: [i32; 4],
url: &'static str,
target: &'static str,
message: &'static str,
alt: &'static str,
html: bool,
cell: &'static str,
/// Alpha, red, green, blue.
argb: [u8; 4],
}
fn user(name: &'static str, rect: [i32; 4]) -> S {
S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] }
}
/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or
/// nothing).
fn v6(slices: &[S], trailing: &[u8]) -> Vec<u8> {
let mut b = 6u32.to_be_bytes().to_vec();
b.extend([0u8; 16]);
b.extend(ustr("group"));
b.extend((slices.len() as u32).to_be_bytes());
for (i, s) in slices.iter().enumerate() {
b.extend((i as u32 + 1).to_be_bytes());
b.extend(0u32.to_be_bytes());
b.extend(s.origin.to_be_bytes());
if s.origin == 1 {
b.extend(7u32.to_be_bytes());
}
b.extend(ustr(s.name));
b.extend(s.kind.to_be_bytes());
for v in s.rect {
b.extend(v.to_be_bytes());
}
for t in [s.url, s.target, s.message, s.alt] {
b.extend(ustr(t));
}
b.push(u8::from(s.html));
b.extend(ustr(s.cell));
b.extend([0u8; 8]);
b.extend(s.argb);
b.extend(trailing);
}
b
}
/// A descriptor value.
enum D {
Long(i32),
Doub(f64),
Bool(bool),
Text(&'static str),
Enum(&'static str, &'static str),
Obj(Vec<(&'static str, D)>),
List(Vec<D>),
}
/// A key or class ID: a four-character one with length 0, else its length and characters.
fn key(k: &str) -> Vec<u8> {
let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec();
b.extend(k.as_bytes());
b
}
/// A descriptor: an empty class name, the class ID, the count, then each item.
fn descriptor(items: &[(&str, D)]) -> Vec<u8> {
let mut b = ustr("");
b.extend(key("null"));
b.extend((items.len() as u32).to_be_bytes());
for (k, v) in items {
b.extend(key(k));
b.extend(value(v));
}
b
}
/// A value's type, then the value.
fn value(v: &D) -> Vec<u8> {
let mut b = vec![];
match v {
D::Long(n) => {
b.extend(b"long");
b.extend(n.to_be_bytes());
}
D::Doub(d) => {
b.extend(b"doub");
b.extend(d.to_be_bytes());
}
D::Bool(on) => {
b.extend(b"bool");
b.push(u8::from(*on));
}
D::Text(t) => {
b.extend(b"TEXT");
b.extend(ustr(t));
}
D::Enum(t, e) => {
b.extend(b"enum");
b.extend(key(t));
b.extend(key(e));
}
D::Obj(items) => {
b.extend(b"Objc");
b.extend(descriptor(items));
}
D::List(items) => {
b.extend(b"VlLs");
b.extend((items.len() as u32).to_be_bytes());
for i in items {
b.extend(value(i));
}
}
}
b
}
/// A bounds object: top, left, bottom and right.
fn bounds(l: i32, t: i32, r: i32, b: i32) -> D {
D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))])
}
/// Resource 1050 in `version` 7 or 8 holding `slices`.
fn v7(version: u32, slices: Vec<D>) -> Vec<u8> {
let mut b = version.to_be_bytes().to_vec();
b.extend(16u32.to_be_bytes());
b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))]));
b
}
/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat.
fn psd(layers: bool) -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("layer.new", &json!({ "name": "Top" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
/// `psd` with image resource `id` holding `data` added to its image resources.
fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec<u8> {
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(id.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn b64(f: &[u8]) -> String {
vectorcraft_format::base64_encode(f)
}
fn open(f: &[u8], extra: Value) -> (Session, Value) {
let mut s = Session::new();
let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("document.open", &p).unwrap();
(s, r)
}
/// The document's user slices: rectangle and options.
fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> {
s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect()
}
fn warnings(r: &Value) -> Vec<String> {
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
#[test]
fn version_6_slices_open_as_user_slices_with_their_options() {
let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) };
let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let data = v6(&[linked, plain, html, matte, auto], &[]);
for layers in [true, false] {
let f = with_resource(&psd(layers), 1050, &data);
// Either conversion brings the slices in; the automatic one stays out.
for p in [json!({}), json!({"layers": false})] {
let (s, r) = open(&f, p);
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 4, "{got:?}");
assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0));
assert_eq!(
got[0].1,
SliceOptions {
kind: SliceKind::Image,
name: "logo".into(),
url: "https://example.com/".into(),
target: "_blank".into(),
message: "Go".into(),
alt: "Logo".into(),
..Default::default()
}
);
// Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is.
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a &lt; b &amp; c", ""));
assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("<b>Hi</b>", "#123456", ""));
// An Image slice's cell text isn't kept; a background with no alpha is the matte.
assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte"));
// Web output lays them out with auto slices around them.
let layout = s.doc().unwrap().doc.slice_layout();
assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4);
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
}
}
}
#[test]
fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing));
let (s, r) = open(&f, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let names: Vec<String> = slices(&s).into_iter().map(|(_, o)| o.name).collect();
assert_eq!(names, ["a", "b"]);
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
// 100 of them hold 250,100 together.
let list = D::List((0..2_500).map(D::Long).collect());
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat();
let records: Vec<S> = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect();
// Alone, one such descriptor is read past.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).len(), 1);
// Together they are refused, and the file opens without slices.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}");
assert!(slices(&s).is_empty());
}
#[test]
fn version_7_and_8_descriptors_open_as_user_slices() {
let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| {
D::Obj(vec![
("sliceID", D::Long(1)),
("groupID", D::Long(0)),
("origin", D::Enum("ESliceOrigin", origin)),
("Type", D::Enum("ESliceType", kind)),
("bounds", bounds(l, t, r, b)),
("Nm ", D::Text("cell")),
("url", D::Text("https://example.com/")),
("null", D::Text("_top")),
("Msge", D::Text("msg")),
("altTag", D::Text("alt")),
("cellTextIsHTML", D::Bool(false)),
("cellText", D::Text("x>y")),
("bgColorType", D::Enum("ESliceBGColorType", "Clr ")),
("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])),
])
};
for version in [7, 8] {
let data = v7(
version,
vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)],
);
let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0));
assert_eq!(
got[0].1,
SliceOptions {
name: "cell".into(),
url: "https://example.com/".into(),
target: "_top".into(),
message: "msg".into(),
alt: "alt".into(),
background: "#ff8000".into(),
..Default::default()
}
);
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x&gt;y", ""));
}
}
#[test]
fn import_slices_false_leaves_them_out_and_must_be_a_switch() {
let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]));
let (s, _) = open(&f, json!({"importSlices": false}));
assert!(slices(&s).is_empty());
let mut s = Session::new();
let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err();
assert!(e.to_string().contains("importSlices must be true or false"), "{e}");
}
#[test]
fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
let mut bad_descriptor = v7(7, vec![]);
bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes());
let cases: Vec<(Vec<u8>, &str)> = vec![
(good[..good.len() - 3].to_vec(), "cut short"),
([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"),
(bad_descriptor, "version other than 16"),
// The count follows the version, the bounds and the group's name.
([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"),
(v7(8, vec![D::Long(3)]), "other than a slice"),
// A whole record whose name is longer than a slice's text may be.
(v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"),
];
for (data, why) in cases {
for layers in [true, false] {
let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}");
assert!(slices(&s).is_empty());
// The art still came in.
assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}");
}
}
// A name of the longest length read comes in.
let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536));
// A file without slices opens without a word about them.
let (s, r) = open(&psd(true), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
#[test]
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({}));
assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]);
let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect();
assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]);
}
#[test]
fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]);
for layers in [false, true] {
let f = with_resource(&psd(layers), 1050, &data);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
// Fitted into a 40 pt square at (100, 60): twice the size.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}");
let got: Vec<Rect> = slices(&s).into_iter().map(|(r, _)| r).collect();
assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]);
// The placed art stays selected, and one undo takes the art and the slices away.
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_none());
// Centered on `at` at 100%.
s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap();
assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0));
// `importSlices: false` places the art alone.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap();
assert!(r.get("slices").is_none());
assert_eq!(slices(&s).len(), 2);
}
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("poster.psd");
std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap();
let path = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &json!({ "path": path })).unwrap();
assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None));
assert!(slices(&s).is_empty());
let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err();
assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}");
// Embedded from its path, they come in.
let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap();
assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1)));
// file.place.info counts what a place would bring in.
let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap();
assert_eq!(info["slices"], json!(1));
let info = s.execute("file.place.info", &json!({ "path": path })).unwrap();
assert_eq!(info["slices"], json!(0));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_slices_that_come_in() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap();
let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]);
assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1));
assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0));
assert_eq!(info(&mut s, &psd(true))["slices"], json!(0));
}
#[test]
fn damaged_slices_never_panic() {
let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]);
let base = with_resource(&psd(false), 1050, &data);
let start = base.windows(data.len()).position(|w| w == data).unwrap();
for at in (start - 12..start + data.len()).step_by(3) {
for v in [0u8, 0x7f, 0xff] {
let mut f = base.clone();
f[at] = v;
let mut s = Session::new();
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
}
}
}
File diff suppressed because one or more lines are too long
+5
View File
@@ -1841,6 +1841,7 @@ proptest! {
/// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden
/// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count.
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.)
/// Neither does `document.psdInfo`, nor placing them with their layers as objects.
#[test]
fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) {
let (name, mut bytes) = raster_samples().swap_remove(which);
@@ -1855,6 +1856,10 @@ proptest! {
let mut s = vectorcraft_engine::Session::new();
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true});
let _ = no_panic(s.execute("document.open", &p));
let _ = no_panic(s.execute("document.psdInfo", &p));
let _ = no_panic(s.execute("file.new", &json!({})));
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true});
let _ = no_panic(s.execute("file.place", &p));
});
prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err());
}
+2
View File
@@ -97,6 +97,7 @@ pub mod plugin;
mod png_options;
pub mod print;
pub mod print_presets;
pub mod psd_import;
mod psd_options;
pub mod raster_effects;
pub mod rearrange_artboards;
@@ -417,6 +418,7 @@ registry! {
PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC,
SafeMode: [safe_mode::KIND] => safe_mode::SPEC,
DxfImport: [dxf_import::KIND] => dxf_import::SPEC,
PsdImport: [psd_import::KIND] => psd_import::SPEC,
RasterFormatOptions: ["tiffOptions", "bmpOptions", "tgaOptions"] => png_options::SPEC,
SaveForWeb: [save_for_web::KIND] => save_for_web::SPEC,
PsdOptions: ["psdOptions"] => png_options::SPEC,
+585
View File
@@ -0,0 +1,585 @@
//! PSD Import Options: opening a PSD or PSB file with two or more layers or with slices, or
//! placing one without Link, asks whether its layers become objects or one flat image, whether
//! hidden layers come in, and whether its slices come in (Import Slices, offered only for a file
//! with slices)
//! (<https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html>).
//! A linked file shows its flat image, so placing with Link doesn't ask. The two-layer threshold,
//! the starting choices, Import Slices applying to both conversions and remembering the choices
//! are VectorCraft's own.
//!
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px),
//! `layers`, `hidden` and `slices` (counts, from `document.psdInfo`), `convert` (`objects` |
//! `flatten`), `hiddenLayers` and `importSlices`. `__place` keeps the other `file.place` params.
//! The file's bytes stay in [`crate::state::UiState::dialog_file`]. OK opens or places the file
//! with `layers`, `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the
//! choices for the next file; errors keep the dialog open.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use super::DialogSpec;
use super::import_pdf::{DialogFile, other_place_params, place_source, with_file};
use crate::state::Dialog;
use crate::{VectorcraftApp, io, widgets};
pub const KIND: &str = "psdImport";
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |d| if d.str("mode") == "place" { tl!("Place PSD") } else { tl!("PSD Import Options") }.into(),
body,
confirm,
min_width: 380.0,
..DialogSpec::FORM
};
/// The fewest layers a file has for the dialog to ask.
const MIN_LAYERS: usize = 2;
/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they
/// are a PSD or PSB file with [`MIN_LAYERS`] layers or more, or with slices; false when they aren't
/// (the loader then opens or places the file, or says why it can't).
pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool {
let Ok(info) = fileio::psd_info(bytes) else { return false };
if info.layers < MIN_LAYERS && info.slices == 0 {
return false;
}
app.ui.dialog_file = Some(DialogFile::new(bytes.to_vec()));
let (layers, hidden, slices) = last_choices(app);
let mut fields = json!({
"mode": if place.is_some() { "place" } else { "open" },
"name": name,
"width": info.width,
"height": info.height,
"layers": info.layers,
"hidden": info.hidden,
"slices": info.slices,
"convert": if layers { "objects" } else { "flatten" },
"hiddenLayers": hidden,
"importSlices": slices,
});
if let Some(p) = path {
fields["path"] = json!(p);
}
if let Some(p) = place {
fields["__place"] = other_place_params(p, &["layers", "hiddenLayers", "importSlices"]);
}
app.ui.dialog = Some(Dialog::new(KIND, fields));
true
}
/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`,
/// or the file's bytes) and give no `layers`.
pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false);
if !embedded || p.get("layers").is_some() {
return false;
}
let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "psd" | "pdd" | "psb")) else { return false };
offer(app, &name, &bytes, path, Some(p))
}
/// The PSD Import Options chosen last (layers, hidden layers, slices), at first Convert Layers to
/// Objects without hidden layers, with Import Slices.
fn last_choices(app: &VectorcraftApp) -> (bool, bool, bool) {
let last = |k: &str, default: bool| app.ui.psd_import.get(k).and_then(Value::as_bool).unwrap_or(default);
(last("layers", true), last("hiddenLayers", false), last("importSlices", true))
}
/// Several files placed without Link load the place cursor without asking: the `file.place.queue`
/// params `q` take the PSD Import Options chosen last, which apply to each PSD or PSB file among them.
pub fn queue_options(app: &VectorcraftApp, q: &mut Value) {
let (layers, hidden, slices) = last_choices(app);
q["layers"] = json!(layers);
if layers && hidden {
q["hiddenLayers"] = json!(true);
}
q["importSlices"] = json!(slices);
}
/// `file.place` params `p` placed without asking (Show Import Options off) that embed a PSD or PSB
/// file and give no `layers` take the PSD Import Options chosen last; `hiddenLayers` and
/// `importSlices` that the params give are kept.
pub fn last_options(app: &VectorcraftApp, p: &mut Value) {
let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false);
let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default();
if embedded && p.get("layers").is_none() && matches!(fileio::extension(name).as_str(), "psd" | "pdd" | "psb") {
let (layers, hidden, slices) = last_choices(app);
p["layers"] = json!(layers);
if layers && hidden && p.get("hiddenLayers").is_none() {
p["hiddenLayers"] = json!(true);
}
if p.get("importSlices").is_none() {
p["importSlices"] = json!(slices);
}
if p.get("path").is_none() {
// A file from bytes has no file to link to; it may carry the Place dialog's Link.
p["link"] = json!(false);
}
}
}
/// OK: open or place the file with the choices.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let file = app.ui.dialog_file.clone().ok_or("the file is no longer loaded")?;
let layers = d.str("convert") != "flatten";
let hidden = layers && d.bool("hiddenLayers");
// Import Slices is a choice only for a file with slices; otherwise the one made last stays.
let has_slices = d.fields.get("slices").and_then(Value::as_u64).unwrap_or(0) > 0;
let slices = if has_slices { d.bool("importSlices") } else { last_choices(app).2 };
app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers"), "importSlices": slices });
let r = if d.str("mode") == "place" {
let mut p = with_file(d.fields.get("__place"), d, &file);
p["layers"] = json!(layers);
if layers || has_slices {
// Layers and slices are always embedded; a file from bytes may carry the Place dialog's
// Link.
p["link"] = json!(false);
}
if hidden {
p["hiddenLayers"] = json!(true);
}
if has_slices {
p["importSlices"] = json!(slices);
}
crate::place::run_for_user(app, &p).map(|_| ())
} else {
let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string);
let mut p = json!({ "layers": layers, "hiddenLayers": hidden });
if has_slices {
p["importSlices"] = json!(slices);
}
io::open_document(app, &d.str("name"), &file.bytes, path, &p).map(|_| ())
};
match r {
Ok(()) => {
// Placing may have opened another dialog; only this one closes.
if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) {
app.ui.dialog = None;
}
Ok(Value::Null)
}
Err(e) => {
app.ui.dialog = Some(d.clone());
Err(e)
}
}
}
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0);
widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers")));
// Offered only for a file with slices, with either conversion.
let sliced = count("slices") > 0;
ui.add_space(8.0);
let convert = d.str("convert") != "flatten";
if widgets::radio(ui, tl!("Convert Layers to Objects"), convert, true) {
d.fields.insert("convert".into(), json!("objects"));
}
ui.horizontal(|ui| {
ui.add_space(22.0);
let on = d.bool("hiddenLayers");
if widgets::check(ui, tl!("Import Hidden Layers"), on && convert, convert) {
d.fields.insert("hiddenLayers".into(), json!(!on));
}
});
if widgets::radio(ui, tl!("Flatten Layers to a Single Image"), !convert, true) {
d.fields.insert("convert".into(), json!("flatten"));
}
ui.add_space(8.0);
let on = d.bool("importSlices");
if widgets::check(ui, tl!("Import Slices"), on && sliced, sliced) {
d.fields.insert("importSlices".into(), json!(!on));
}
false
}
#[cfg(test)]
mod tests {
use vectorcraft_engine::Session;
use vectorcraft_engine::doc::NodeKind;
use super::*;
/// A PSD file of three layers, the middle one hidden, written by `document.export`.
fn layered() -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
let back = s.doc().unwrap().doc.layers[0].id.0;
s.execute("layer.setProps", &json!({"id": back, "name": "Back"})).unwrap();
for (name, color) in [("Back", "#ff0000"), ("Middle", "#00ff00"), ("Front", "#0000ff")] {
if name != "Back" {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
s.execute("paint.setFill", &json!({ "color": color })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
}
let middle = s.doc().unwrap().doc.layers[1].id.0;
s.execute("layer.setProps", &json!({"id": middle, "visible": false})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "hiddenLayers": true})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
fn app() -> VectorcraftApp {
VectorcraftApp::new(Session::new(), Default::default())
}
fn frame(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
fn set(app: &mut VectorcraftApp, k: &str, v: Value) {
app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
}
fn layer_names(app: &VectorcraftApp) -> Vec<(String, bool)> {
app.session.doc().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect()
}
#[test]
fn opening_a_layered_file_asks_for_the_import_options() {
let psd = layered();
let mut app = app();
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), d.str("mode"), d.str("convert"), d.bool("hiddenLayers")), (KIND, "open".into(), "objects".into(), false));
assert_eq!((&d.fields["layers"], &d.fields["hidden"], &d.fields["width"]), (&json!(3), &json!(1), &json!(20)));
assert!(app.session.active().is_none(), "nothing opens before OK");
let text = frame(&mut app);
for label in [
"PSD Import Options",
"20 × 20 px",
"Layers: 3",
"Convert Layers to Objects",
"Import Hidden Layers",
"Flatten Layers to a Single Image",
"OK",
] {
assert!(text.contains(label), "{label} in {text}");
}
// Layers as objects, hidden ones left out.
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Front".to_string(), true)]);
// With Import Hidden Layers the hidden layer comes in hidden.
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
set(&mut app, "hiddenLayers", json!(true));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Middle".to_string(), false), ("Front".to_string(), true)]);
// Flatten opens one image, and the next file starts from the choices made last.
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool("hiddenLayers"), "remembered");
set(&mut app, "convert", json!("flatten"));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
assert_eq!(st.doc.layers.len(), 1);
assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([one]) if matches!(one.kind, NodeKind::Image(_))));
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().str("convert"), "flatten");
}
#[test]
fn files_with_fewer_than_two_layers_open_without_asking() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let one = s.execute("document.export", &json!({"format": "psd"})).unwrap();
let flat = s.execute("document.export", &json!({"format": "psd", "layers": false})).unwrap();
for r in [one, flat] {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let mut app = app();
io::open_bytes(&mut app, "one.psd", &bytes, None).unwrap();
assert!(app.ui.dialog.is_none());
assert!(app.session.active().is_some());
}
}
#[test]
fn placing_without_link_asks_and_places_the_layers_as_a_group() {
let b64 = vectorcraft_format::base64_encode(&layered());
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap();
assert_eq!(r["dialog"], KIND);
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.str("mode"), &d.fields["__place"]), ("place".into(), &json!({"at": [50, 50]})));
assert!(frame(&mut app).contains("Place PSD"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
let g = st.doc.node(id).unwrap();
assert!(matches!(g.kind, NodeKind::Group { .. }));
let names: Vec<&str> = g.children().unwrap().iter().filter_map(|c| c.name.as_deref()).collect();
assert_eq!(names, ["Back", "Front"]);
// Flatten places the merged image.
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap();
set(&mut app, "convert", json!("flatten"));
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_)));
}
#[test]
fn several_files_placed_without_link_take_the_last_choices() {
let dir = std::env::temp_dir().join(format!("vc-psd-import-queue-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["a.psd", "b.psd"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, layered()).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
// Place both through the Place dialog, then click the cursor once for each: what was placed.
let place_two = |app: &mut VectorcraftApp, link: bool| -> Vec<vectorcraft_engine::doc::Node> {
let files: Vec<Value> = paths.iter().map(|p| json!({ "path": p })).collect();
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": link, "template": false}));
crate::place::confirm(app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
let view = vectorcraft_engine::ViewInfo::default();
(0..2)
.map(|_| {
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(app, &p);
}
}
}
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is placed") };
st.doc.node(id).unwrap().clone()
})
.collect()
};
let visible = |n: &vectorcraft_engine::doc::Node| -> Vec<bool> { n.children().unwrap().iter().map(|c| c.visible).collect() };
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// At first, Convert Layers to Objects without hidden layers.
for n in place_two(&mut app, false) {
assert!(matches!(n.kind, NodeKind::Group { .. }));
assert_eq!(visible(&n), [true, true]);
}
// Then the choices made last.
app.ui.psd_import = json!({"layers": true, "hiddenLayers": true});
for n in place_two(&mut app, false) {
assert_eq!(visible(&n), [true, false, true]);
}
app.ui.psd_import = json!({"layers": false, "hiddenLayers": true});
assert!(place_two(&mut app, false).iter().all(|n| matches!(n.kind, NodeKind::Image(_))));
// Placed with Link, the files keep their flat images.
app.ui.psd_import = json!({"layers": true, "hiddenLayers": false});
assert!(place_two(&mut app, true).iter().all(|n| matches!(n.kind, NodeKind::Image(_))));
std::fs::remove_dir_all(&dir).ok();
}
/// `psd` with a slices resource (1050, version 6) holding one user slice over its top-left
/// 10 × 10 px, named "cell".
fn sliced(psd: &[u8]) -> Vec<u8> {
let ustr = |s: &str| -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
};
let mut data = 6u32.to_be_bytes().to_vec();
data.extend([0u8; 16]);
data.extend(ustr(""));
data.extend(1u32.to_be_bytes());
// ID, group ID, origin (made by the user), name, type (Image), left, top, right, bottom.
data.extend([1u32, 0, 2].iter().flat_map(|v| v.to_be_bytes()));
data.extend(ustr("cell"));
data.extend([1u32, 0, 0, 10, 10].iter().flat_map(|v| v.to_be_bytes()));
// URL, target, message, alt text, cell text is HTML, cell text, alignments, color.
for _ in 0..4 {
data.extend(ustr(""));
}
data.push(0);
data.extend(ustr(""));
data.extend([0u8; 12]);
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(1050u16.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(&data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn slice_names(app: &VectorcraftApp) -> Vec<String> {
app.session.doc().unwrap().doc.slices.iter().map(|s| s.options.name.clone()).collect()
}
#[test]
fn a_file_with_slices_asks_with_import_slices_on_either_conversion() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd"})).unwrap();
// One layer: without slices it opens at once, with them it asks.
let psd = sliced(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let mut app = app();
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), &d.fields["slices"], d.bool("importSlices")), (KIND, &json!(1), true));
assert!(frame(&mut app).contains("Import Slices"));
// Flatten keeps Import Slices: the merged image opens with the slice.
set(&mut app, "convert", json!("flatten"));
super::super::confirm(&mut app).unwrap();
assert_eq!(slice_names(&app), ["cell"]);
// Left off, the slice stays out, and the next file starts from that choice.
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
set(&mut app, "importSlices", json!(false));
super::super::confirm(&mut app).unwrap();
assert!(slice_names(&app).is_empty());
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
assert!(!app.ui.dialog.as_ref().unwrap().bool("importSlices"), "remembered");
// A layered file without slices keeps the choice made last for the next sliced one.
app.ui.dialog = None;
io::open_bytes(&mut app, "poster.psd", &layered(), None).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["slices"], json!(0));
set(&mut app, "importSlices", json!(true));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.ui.psd_import["importSlices"], json!(false));
}
#[test]
fn placing_a_sliced_file_without_link_brings_its_slices_with_the_art() {
let b64 = vectorcraft_format::base64_encode(&sliced(&layered()));
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool("importSlices"));
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
assert_eq!(st.doc.slices.len(), 1);
assert_eq!(st.doc.slices[0].rect, vectorcraft_geom::Rect::new(40.0, 40.0, 50.0, 50.0));
// Several files placed together take the choice made last.
let mut q = json!({});
app.ui.psd_import = json!({"layers": true, "importSlices": false});
queue_options(&app, &mut q);
assert_eq!(q["importSlices"], json!(false));
}
#[test]
fn placing_with_show_import_options_off_takes_the_last_choices() {
let b64 = vectorcraft_format::base64_encode(&sliced(&layered()));
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The file's bytes carry the Place dialog's Link, which they have no file for.
let place = |app: &mut VectorcraftApp, slices: Option<bool>| {
let mut p = json!({"name": "poster.psd", "dataBase64": b64, "link": true, "showImportOptions": false});
if let Some(s) = slices {
p["importSlices"] = json!(s);
}
crate::place::run_for_user(app, &p).unwrap();
assert!(app.ui.dialog.is_none(), "placed without asking");
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
(st.doc.node(id).unwrap().kind.clone(), st.doc.slices.len())
};
// At first, Convert Layers to Objects with Import Slices.
let (kind, slices) = place(&mut app, None);
assert!(matches!(kind, NodeKind::Group { .. }));
assert_eq!(slices, 1);
// An `importSlices` the params give is kept.
let (kind, slices) = place(&mut app, Some(false));
assert!(matches!(kind, NodeKind::Group { .. }));
assert_eq!(slices, 1, "no new slice");
// Then the choices made last.
app.ui.psd_import = json!({"layers": false, "importSlices": false});
let (kind, slices) = place(&mut app, None);
assert!(matches!(kind, NodeKind::Image(_)));
assert_eq!(slices, 1, "no new slice");
let (_, slices) = place(&mut app, Some(true));
assert_eq!(slices, 2, "the given importSlices brings the slice in");
}
#[test]
fn files_from_bytes_placed_with_link_take_the_last_choices() {
let files: Vec<Value> = ["a.psd", "b.psd"].iter().map(|n| json!({ "name": n })).collect();
let mut app = app();
for n in ["a.psd", "b.psd"] {
app.place.picked.push((n.to_string(), sliced(&layered())));
}
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The dialog's Link is on, but files from bytes have no file to link to.
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": true, "template": false, "showImportOptions": false}));
crate::place::confirm(&mut app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
let view = vectorcraft_engine::ViewInfo::default();
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(&mut app, &p);
}
}
}
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is placed") };
// At first, Convert Layers to Objects with Import Slices.
assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. }));
assert_eq!(st.doc.slices.len(), 1);
}
#[test]
fn a_cursor_loaded_with_show_import_options_on_asks_for_each_psd_file() {
let dir = std::env::temp_dir().join(format!("vc-psd-import-asks-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["a.psd", "b.psd"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, layered()).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
let files: Vec<Value> = paths.iter().map(|p| json!({ "path": p })).collect();
let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() };
let mut app = VectorcraftApp::new(Session::new(), services);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The choices made last would place the layers without asking with Show Import Options off.
app.ui.psd_import = json!({"layers": true, "importSlices": true});
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": false, "template": false, "showImportOptions": true}));
crate::place::confirm(&mut app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
assert_eq!(app.session.tool_options()["count"], 2);
// A click on the canvas: the file the cursor's request names asks.
let view = vectorcraft_engine::ViewInfo::default();
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(&mut app, &p);
}
}
}
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the clicked file asks");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn scripted_places_and_places_that_give_layers_dont_ask() {
let b64 = vectorcraft_format::base64_encode(&layered());
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// `file.place` run as a command places at once, as before.
let r = crate::place::run(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(r["format"], "psd");
// The user's place with `layers` given doesn't ask either.
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "layers": false})).unwrap();
assert!(app.ui.dialog.is_none());
}
}
+7 -3
View File
@@ -52,10 +52,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt
let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library };
return load(app, p).map(|_| Value::Null);
}
// A PDF with several pages or a password asks first (the Import PDF dialog), and so does a
// DXF drawing (DXF Import Options).
// A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF
// drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import
// Options), unless `p` says how its layers come in.
if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None)
|| crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None))
{
return Ok(Value::Null);
}
@@ -552,9 +554,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
check_import_size(path, false)?;
let mut bytes = read(app, path)?;
if background && opens_as(path).is_none() {
// A PDF with several pages or a password, or a DXF drawing, asks first, as at once.
// A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers
// or with slices asks first, as at once.
if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None)
|| crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None))
{
note_recent(app, path);
return Ok(Value::Null);
+20 -6
View File
@@ -61,7 +61,7 @@ pub fn is_document(name: &str) -> bool {
#[derive(Default)]
pub struct PlaceState {
/// Web: the bytes of the files picked for the Place dialog, by name.
picked: Vec<(String, Vec<u8>)>,
pub(crate) picked: Vec<(String, Vec<u8>)>,
/// The loaded cursor's thumbnails by file name.
thumbs: Vec<(String, Thumb)>,
/// The Control bar's `image.info`, for (document uid, revision, image id).
@@ -125,10 +125,11 @@ fn engine(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result<Value, String
/// File → Place… (`file.place`): with a file (`path` or `name` + `dataBase64`), place it, centred
/// in the view unless `at`, `rect` or `replace` say otherwise (a text file without `text` options,
/// a DXF drawing without `dxf` options and a PDF with several pages or a password and no `page`
/// ask for them first, unless `showImportOptions: false` places them with the options confirmed
/// last); with `paths`, the Place dialog for them; with neither, pick the files first. The file is
/// read and placed at once (MCP, scripts).
/// a DXF drawing without `dxf` options, a PSD file embedded without `layers` (when the user places
/// it) and a PDF with several pages or a password and no `page` ask for them first, unless
/// `showImportOptions: false` places them with the options confirmed last); with `paths`, the
/// Place dialog for them; with neither, pick the files first. The file is read and placed at once
/// (MCP, scripts).
pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
place_file(app, p, Read::AtOnce)
}
@@ -181,6 +182,7 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
if let Some(dxf) = crate::dialogs::dxf_import::last_options(app, &p) {
p["dxf"] = dxf;
}
crate::dialogs::psd_import::last_options(app, &mut p);
}
if p.get("text").is_none() && crate::dialogs::text_import::is_text(&p) {
return Ok(crate::dialogs::text_import::open(app, &p));
@@ -209,6 +211,12 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
if ask && crate::dialogs::dxf_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND }));
}
// A PSD file with several layers or with slices that the user embeds asks for its import
// options. A place run as a command (MCP, scripts) places at once and takes `layers` and
// `importSlices` itself.
if ask && matches!(read, Read::ForUser { .. }) && crate::dialogs::psd_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::psd_import::KIND }));
}
if ["at", "rect", "replace"].iter().all(|k| p.get(k).is_none())
&& let Some(v) = app.view()
{
@@ -409,9 +417,15 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
let files: Vec<&Value> = many.iter().filter(|s| s.get("path").is_none()).collect();
let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template });
if !ask {
// Each text file and DXF drawing in the cursor takes the options confirmed last.
// Each text file, DXF drawing and embedded PSD file in the cursor takes the options
// confirmed last.
q["text"] = crate::dialogs::text_import::last_options(app);
q["dxf"] = crate::dialogs::dxf_import::remembered(app);
if !link || paths.is_empty() {
// Files from bytes have no file to link to; they may carry the dialog's Link.
q["link"] = json!(false);
crate::dialogs::psd_import::queue_options(app, &mut q);
}
}
queue_files(app, &q, Read::ForUser { dropped: false }, ask)
}
+4
View File
@@ -831,6 +831,9 @@ pub struct UiState {
/// never used).
#[serde(default)]
pub dxf_import: Value,
/// The PSD Import Options chosen last (layers, hiddenLayers, importSlices; null: never used).
#[serde(default)]
pub psd_import: Value,
/// The Home screen is shown over the open documents (`app.home`): the active document's uid
/// and the document count when it opened. Choosing a tab, or a document opening, closing or
/// becoming active, leaves it.
@@ -1260,6 +1263,7 @@ impl Default for UiState {
transform_each: Value::Null,
rearrange_artboards_spacing: Value::Null,
dxf_import: Value::Null,
psd_import: Value::Null,
home: None,
trace_hold_source: None,
layers_panel: Default::default(),
+1 -1
View File
@@ -294,7 +294,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors,
| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` |
| DWG | open, export | no | no | no open spec; DXF instead |
| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) |
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | placing as layers and a PSD import options dialog missing; the embedded ICC profile's tags are 4-byte aligned (#1584) |
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | |
| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) |
| WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | |
+66 -6
View File
@@ -7188,10 +7188,12 @@ with `pointer_gesture` (a click places at 100% with the top-left corner there, a
number, naming the key, and place nothing; null is the same as leaving the key out.
In the app, `file.place` asks for a file's import options before placing it: a text file without `text` (Text Import
Options), a DXF drawing without `dxf` (DXF Import Options), and a PDF, `.ai` or `.ait` file with several pages or a
password and no `page` (Place PDF). `showImportOptions: false` places such a file without asking, with the options
last confirmed in its dialog: the text options, and the DXF fit, lineweight, centering and layer choices with the
drawing at 1:1 in its own unit. A PDF is placed on page 1 (or `page`) and its crop box, and an encrypted PDF given no
Options), a DXF drawing without `dxf` (DXF Import Options), a PDF, `.ai` or `.ait` file with several pages or a
password and no `page` (Place PDF), and a PSD or PSB file embedded without `layers` that has two layers or more or
slices (Place PSD). `showImportOptions: false` places such a file without asking, with the options last confirmed in
its dialog: the text options, the DXF fit, lineweight, centering and layer choices with the drawing at 1:1 in its own
unit, and the PSD conversion, hidden-layer and Import Slices choices. A PDF is placed on page 1 (or `page`) and its
crop box, and an encrypted PDF given no
`password` still asks for the password. A `showImportOptions` that is not true or false is refused, and nothing is placed. The
Place dialog (File › Place, or `file.place {paths}`) has a Show Import Options checkbox after Link, Template and
Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)).
@@ -8620,6 +8622,65 @@ flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, R
A document with transparency keeps it. `file.place {path}` links the file like any image (`links.update` reads it
again when it changes); Multichannel files are refused.
`file.place` with `layers: true` embeds a PSD or PSB file's layers as objects instead, and `hiddenLayers: true`
brings the hidden layers in, hidden. The
[PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html)
offer the conversion and the hidden layers only for a file that is opened or embedded, and a linked file shows its
flat image. The rest are VectorCraft's own rules:
- The layers are read as `document.open` reads them (below) and placed as one group named after the file. A layer
becomes an image and a layer group becomes a group, each with the layer's name, visibility, opacity, blend mode
and opacity mask. A Pass Through group is not isolated; a group in any other mode is.
- The group takes the place the merged image would take: `at` centers the file's canvas and `rect` fits it. When
layers reach past the canvas, hidden layers included, the group is a clip group whose clipping path is the canvas.
- The layers are never linked. With `layers: true`, `link` is false unless it is given, and `link: true` is an
error.
- `hiddenLayers: true` without `layers: true` is an error.
- A file without layers is embedded as its merged image, and so is a file whose layers are all left out, with the
import's warnings. A file whose layers can't be read is embedded as its merged image with a warning.
- `file.place.queue` and `file.place.info` take `layers` and `hiddenLayers` too.
`document.psdInfo` reads a PSD or PSB file without opening it: its `format` (`psd` or `psb`), the canvas `width`
and `height` in pixels, and the counts `layers` (group markers left out), `hiddenLayers`, `groups` and `slices`
(the slices `importSlices` brings in). A file without layer records, or whose layer records can't be read, has
`layers: 0`; a file without slices, or whose slices can't be read, has `slices: 0`. A file that is not a PSD or PSB
file is an error.
`importSlices` brings a PSD or PSB file's slices in as user slices (Object › Slice), which Save for Web exports.
The [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html)
keep the slices a file holds, and offer it only for a file that is opened or embedded. The slices are read from
image resource 1050 as the
[Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it,
in version 6 and in the descriptor of versions 7 and 8. The rest are VectorCraft's own rules:
- `document.open` takes `importSlices`, default true, with the layers as objects and with `layers: false` alike.
The slices lie over the canvas, each clipped to it.
- `file.place` takes `importSlices`, default true when the file is embedded and false when it is linked;
`importSlices: true` with a linked file is an error. The slices move and scale with the placed art, in the same
undo step, and the reply lists their ids in `slices`. `file.place.info` counts them in `slices`, and
`file.place.queue` takes `importSlices` too.
- Each slice keeps its name, its type (Image or No Image), its link, target, message, alternative text and
background color, and a No Image slice keeps its cell text (plain text escaped as HTML). Text alignment isn't
read. A slice that follows a layer comes in as a user slice over the rectangle the file stores for it.
- Slices the file generated automatically are left out: the document lays out its own auto slices around the
others. A slice wholly outside the canvas, or without a size, is left out with a warning, and so are slices that
can't be read; the file's art comes in either way. A file without slices brings no warning.
In the app, File › Open of a PSD or PSB file with two or more layers, or with slices, shows PSD Import Options:
Convert Layers to Objects (with Import Hidden Layers) or Flatten Layers to a Single Image, and Import Slices, which
is offered only for a file with slices and applies to either choice. File › Place shows the same dialog for such a
file placed without Link, and so does a file dropped on the canvas with Shift held. The dialog starts from the
choices made last, at first Convert Layers to Objects without hidden layers, with Import Slices. A file with fewer
than two layers and no slices, a file placed with Link, and `document.open` and `file.place` run as commands don't
show it. Several files placed together without Link load the place cursor without asking, and each PSD or PSB file
among them comes in with the choices made last.
```json
{"name":"run_command","arguments":{"command":"file.place","params":{"path":"/tmp/poster.psd","layers":true,"hiddenLayers":true}}}
{"name":"run_command","arguments":{"command":"document.psdInfo","params":{"path":"/tmp/poster.psd"}}}
{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","importSlices":false}}}
```
A PSD or PSB file that names a clipping path (the saved path its clipping path resource names, in the
[published PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)) places, and
opens as its merged image (`layers: false`, a file with no layers, or a file whose layers can't be read), inside a clip group whose clipping
@@ -8679,8 +8740,7 @@ Each layer's pixels must fit the memory allowed for one image, and the pixels of
canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image,
with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when
they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its
own instead of clipped. File › Open in the app has no PSD import options dialog: it converts the layers and leaves
hidden layers out.
own instead of clipped.
```json
{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}}
+3 -1
View File
@@ -1874,8 +1874,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`).
- Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`).
- BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`).
- File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels. There is no PSD import options dialog yet (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`).
- File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`).
- File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [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. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`).
- 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` keep the clip group, 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`).
- 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`).