mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 02:05:42 +00:00
Merge feat/psd-import-options into feat/psd-import-options-import-slices-after-7649
This commit is contained in:
@@ -92,6 +92,8 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
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 save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::access::file_list;
|
||||
use super::formats::formats;
|
||||
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, save, screens};
|
||||
use super::{CommandSpec, action_batch, always, batch, cmd, export, has_doc, has_selection, load, pdfimport, psdlayers, save, screens};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -139,6 +139,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
pdfimport::pdf_info
|
||||
),
|
||||
cmd!(
|
||||
query "document.psdInfo",
|
||||
"PSD Info",
|
||||
[],
|
||||
None,
|
||||
"{path} or {name?, dataBase64} what a PSD or PSB file holds, read from its header and layer records without decoding pixels → {format: psd|psb, width, height (the canvas, px), layers (group markers not counted), hiddenLayers (the hidden ones among them), groups}; a file without layer records, or whose layer records can't be read, has layers: 0 and opens and places as its merged image; a file that is not a PSD or PSB file is an error",
|
||||
always,
|
||||
psdlayers::psd_info
|
||||
),
|
||||
cmd!(
|
||||
"document.exportForOffice",
|
||||
"Save for Office Documents…",
|
||||
|
||||
@@ -526,14 +526,11 @@ 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))),
|
||||
};
|
||||
|
||||
@@ -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,60 @@ 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,
|
||||
}
|
||||
|
||||
/// What PSD or PSB file `bytes` holds, read from its header and 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(),
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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}));
|
||||
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"));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! - A raster image becomes one image at 100% of its physical size: its pixels at the resolution
|
||||
//! the file declares ([`fileio::ppi`]; 72 ppi when it declares none), linked to its file with
|
||||
//! `link` ([`super::links`]).
|
||||
//! - A PSD or PSB file placed with `layers` becomes one group of its layers as objects, embedded
|
||||
//! ([`fileio::psd_layers`]); otherwise it is an image like any other, its merged image.
|
||||
//! - An SVG becomes one group of its art; so does a DXF drawing, read with the DXF options
|
||||
//! (`dxf`, [`fileio::dxfimport`]), and an HP-GL plot file (`vectorcraft_cad::hpgl`).
|
||||
//! - An EMF, WMF or PICT picture becomes one group, clipped to its frame (`crop: "crop"`) or
|
||||
@@ -75,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file placed in a clip group, which the Links commands take}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -84,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Placed File Info",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…} (both as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
|
||||
always,
|
||||
info
|
||||
),
|
||||
@@ -102,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Load Place Cursor",
|
||||
[],
|
||||
None,
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
|
||||
"{paths?: [path…], files?: [{name, dataBase64}…], link?, template?, page?, crop?, text?, dxf?, layers?, hiddenLayers?, thumbnail?: px} load the place cursor (the `place` tool) with up to 100 files (as file.place reads them): a click places the current file at 100% with its top-left corner there, a drag places it at the dragged size (aspect kept), ←/→ and ↑/↓ cycle the files, Esc discards the current one; each placement is a file.place, and the previous tool returns after the last → {count, files: [{name, format, width, height, thumbnailBase64?}], skipped: [{name, error}]}",
|
||||
has_doc,
|
||||
queue
|
||||
),
|
||||
@@ -235,12 +237,38 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
let art = Art::Vector { src: Box::new(a.doc), nodes: a.nodes, clip: a.clip };
|
||||
return Ok(Loaded { name, format, art, natural: a.frame, warnings: a.warnings, link: None, board: None });
|
||||
}
|
||||
// A PSD or PSB file placed with `layers`: its layers as objects, never linked. One without
|
||||
// layers, or whose layers can't be read, is embedded as its merged image.
|
||||
let (mut embed, mut unread) = (false, vec![]);
|
||||
if matches!(format.id, "psd" | "psb") {
|
||||
let layers = switch_or(p, "layers", false, cmd)?;
|
||||
if switch_or(p, "hiddenLayers", false, cmd)? && !layers {
|
||||
return Err(bad(cmd, "hiddenLayers applies to a PSD file placed with layers: true"));
|
||||
}
|
||||
if layers {
|
||||
// Layers are embedded: a link shows the file's flat image.
|
||||
if switch_or(p, "link", false, cmd)? {
|
||||
return Err(bad(cmd, "layers: a linked PSD file is placed as its flat image; leave link out or give link: false"));
|
||||
}
|
||||
embed = true;
|
||||
match fileio::psd_layers(&src.bytes, opts.hidden_layers) {
|
||||
Ok(Some((doc, warnings))) => match psd_groups(doc) {
|
||||
Some((art, natural)) => return Ok(Loaded { name, format, art, natural, warnings, link: None, board: None }),
|
||||
// No layer has art: the merged image, embedded.
|
||||
None => unread = warnings,
|
||||
},
|
||||
// No layers: the merged image, embedded.
|
||||
Ok(None) => {}
|
||||
Err(e) => unread.push(format!("the layers can't be read ({e}): the file was placed as its merged image")),
|
||||
}
|
||||
}
|
||||
}
|
||||
if format.raster {
|
||||
let img = fileio::raster_image(&src.bytes)?;
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
|
||||
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
|
||||
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
|
||||
let link = src.path.filter(|_| !embed).map(|path| super::links::link_info(path, &src.bytes));
|
||||
let warnings = unread.into_iter().chain(fileio::size_note(&img.blob.bytes)).collect();
|
||||
return Ok(Loaded { name, format, art: Art::Image(img), natural, warnings, link, board: None });
|
||||
}
|
||||
if pdf {
|
||||
@@ -300,6 +328,47 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board })
|
||||
}
|
||||
|
||||
/// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an
|
||||
/// image for each layer and a group for each layer group, bottom first, with the layer's name,
|
||||
/// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas,
|
||||
/// where the merged image would lie, and the art is clipped to the canvas when layers reach past it.
|
||||
/// None when no layer brought any art in.
|
||||
fn psd_groups(mut doc: Document) -> Option<(Art, Rect)> {
|
||||
let canvas = doc.artboards.first()?.rect;
|
||||
let nodes = psd_objects(&std::mem::take(&mut doc.layers));
|
||||
// Hidden layers count too: showing one later must not draw past the canvas.
|
||||
let symbols = doc.symbol_boxes();
|
||||
let reached = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, reach(&symbols, n)))?;
|
||||
let past = reached.union(canvas) != canvas;
|
||||
Some((Art::Vector { src: Box::new(doc), nodes, clip: past.then_some(canvas) }, canvas))
|
||||
}
|
||||
|
||||
/// The bounds of `n` and every object inside it, hidden ones included.
|
||||
fn reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
match n.children() {
|
||||
Some(kids) => kids.iter().fold(None, |acc, k| vectorcraft_geom::union_opt(acc, reach(symbols, k))),
|
||||
None => n.geometric_bounds_with(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers a PSD import made as objects: a layer of sublayers as a group of them, and a layer
|
||||
/// holding one image as that image, each with the layer's name, visibility, opacity, blend mode,
|
||||
/// isolation and opacity mask.
|
||||
fn psd_objects(layers: &[Arc<Node>]) -> Vec<Node> {
|
||||
layers
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let mut n = (**l).clone();
|
||||
let NodeKind::Layer { children, .. } = &l.kind else { return n };
|
||||
n.kind = match &children[..] {
|
||||
[c] if matches!(c.kind, NodeKind::Image(_)) => c.kind.clone(),
|
||||
_ => NodeKind::Group { children: psd_objects(children).into_iter().map(Arc::new).collect(), clip: false },
|
||||
};
|
||||
n
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Page `page` (1-based) of the PDF/.ai/.ait file `src` (`bytes`, read from `path` when there is
|
||||
/// one) as art to place: clipped to the box `opts.crop` names, or (`bounding`) the bounds of its
|
||||
/// art; read with `opts.password`. Only the page placed is read. A .ai saved without PDF
|
||||
@@ -799,7 +868,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
|
||||
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
|
||||
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
|
||||
for mut q in queued {
|
||||
for k in ["link", "template", "page", "crop", "text", "dxf"] {
|
||||
for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers"] {
|
||||
if let Some(v) = p.get(k) {
|
||||
q[k] = v.clone();
|
||||
}
|
||||
@@ -845,7 +914,7 @@ impl Session {
|
||||
/// desktop the Place dialog's OK with several files does this off the UI thread).
|
||||
pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_switches(params, &["link", "template", "layers", "hiddenLayers"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
let files = queued_files(params)?;
|
||||
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
|
||||
|
||||
@@ -1812,6 +1812,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);
|
||||
@@ -1826,6 +1827,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());
|
||||
}
|
||||
|
||||
@@ -96,6 +96,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;
|
||||
@@ -413,6 +414,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,
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
//! PSD Import Options: opening a PSD or PSB file with two or more layers, or placing one
|
||||
//! without Link, asks whether its layers become objects or one flat image, and whether hidden
|
||||
//! layers come in
|
||||
//! (<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 and remembering them are VectorCraft's own.
|
||||
//!
|
||||
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px),
|
||||
//! `layers` and `hidden` (counts, from `document.psdInfo`), `convert` (`objects` | `flatten`) and
|
||||
//! `hiddenLayers`. `__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` and
|
||||
//! `hiddenLayers` and remembers both 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; 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 {
|
||||
return false;
|
||||
}
|
||||
app.ui.dialog_file = Some(DialogFile::new(bytes.to_vec()));
|
||||
let (layers, hidden) = 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,
|
||||
"convert": if layers { "objects" } else { "flatten" },
|
||||
"hiddenLayers": hidden,
|
||||
});
|
||||
if let Some(p) = path {
|
||||
fields["path"] = json!(p);
|
||||
}
|
||||
if let Some(p) = place {
|
||||
fields["__place"] = other_place_params(p, &["layers", "hiddenLayers"]);
|
||||
}
|
||||
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, at first Convert Layers to Objects without hidden layers.
|
||||
fn last_choices(app: &VectorcraftApp) -> (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))
|
||||
}
|
||||
|
||||
/// 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) = last_choices(app);
|
||||
q["layers"] = json!(layers);
|
||||
if layers && hidden {
|
||||
q["hiddenLayers"] = json!(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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");
|
||||
app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers") });
|
||||
let r = if d.str("mode") == "place" {
|
||||
let mut p = with_file(d.fields.get("__place"), d, &file);
|
||||
p["layers"] = json!(layers);
|
||||
if layers {
|
||||
// Layers are always embedded; a file from bytes may carry the Place dialog's Link.
|
||||
p["link"] = json!(false);
|
||||
}
|
||||
if hidden {
|
||||
p["hiddenLayers"] = json!(true);
|
||||
}
|
||||
crate::place::run_for_user(app, &p).map(|_| ())
|
||||
} else {
|
||||
let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string);
|
||||
io::open_document(app, &d.str("name"), &file.bytes, path, &json!({ "layers": layers, "hiddenLayers": hidden })).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")));
|
||||
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"));
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
@@ -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 (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
|
||||
// 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);
|
||||
|
||||
@@ -152,6 +152,11 @@ fn place_file(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Value,
|
||||
if crate::dialogs::dxf_import::offer_place(app, p) {
|
||||
return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND }));
|
||||
}
|
||||
// A PSD file with several layers that the user embeds asks for its import options. A place
|
||||
// run as a command (MCP, scripts) places at once and takes `layers` itself.
|
||||
if matches!(read, Read::ForUser { .. }) && crate::dialogs::psd_import::offer_place(app, p) {
|
||||
return Ok(json!({ "dialog": crate::dialogs::psd_import::KIND }));
|
||||
}
|
||||
let mut p = p.clone();
|
||||
if ["at", "rect", "replace"].iter().all(|k| p.get(k).is_none())
|
||||
&& let Some(v) = app.view()
|
||||
@@ -343,7 +348,11 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
|
||||
many => {
|
||||
let paths: Vec<&Value> = many.iter().filter_map(|s| s.get("path")).collect();
|
||||
let files: Vec<&Value> = many.iter().filter(|s| s.get("path").is_none()).collect();
|
||||
queue_files(app, &json!({ "paths": paths, "files": files, "link": link, "template": template }), Read::ForUser { dropped: false })
|
||||
let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template });
|
||||
if !link {
|
||||
crate::dialogs::psd_import::queue_options(app, &mut q);
|
||||
}
|
||||
queue_files(app, &q, Read::ForUser { dropped: false })
|
||||
}
|
||||
};
|
||||
app.place.picked.clear();
|
||||
|
||||
@@ -819,6 +819,9 @@ pub struct UiState {
|
||||
/// never used).
|
||||
#[serde(default)]
|
||||
pub dxf_import: Value,
|
||||
/// The PSD Import Options chosen last (layers, hiddenLayers; 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.
|
||||
@@ -1237,6 +1240,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(),
|
||||
|
||||
@@ -290,7 +290,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; 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`; 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; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); layer comps and slices aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
|
||||
| PSB | open | yes (layers as layers, or the merged image) | 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) | |
|
||||
|
||||
+37
-2
@@ -8220,6 +8220,42 @@ 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` and `groups`. A file
|
||||
without layer records, or whose layer records can't be read, has `layers: 0`. A file that is not a PSD or PSB file
|
||||
is an error.
|
||||
|
||||
In the app, File › Open of a PSD or PSB file with two or more layers shows PSD Import Options: Convert Layers to
|
||||
Objects (with Import Hidden Layers) or Flatten Layers to a Single Image. 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. A file with fewer than two
|
||||
layers, 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"}}}
|
||||
```
|
||||
|
||||
`document.open` converts a PSD or PSB file's layers to objects. In
|
||||
[PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html),
|
||||
the option that converts layers to objects keeps as much of the layer structure as it can, merges the layers of a
|
||||
@@ -8268,8 +8304,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}}}
|
||||
|
||||
@@ -1810,7 +1810,8 @@ 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 and slices aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.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`).
|
||||
|
||||
Reference in New Issue
Block a user