Merge main into feat/psd-export-writes-slices

This commit is contained in:
dotCooCoo
2026-11-15 18:39:24 -08:00
138 changed files with 11077 additions and 792 deletions
+86 -6
View File
@@ -8,13 +8,15 @@ use std::collections::HashMap;
use std::sync::Arc;
use vectorcraft_color::{BlendMode, cms};
use vectorcraft_doc::text::TypeAntiAlias;
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource};
use vectorcraft_geom::Rect;
use vectorcraft_geom::{Point, Rect};
use super::jpeg::{self, ColorModel};
use super::psd_type;
use super::tiff::packbits;
use super::{RasterExportOptions, RasterFormat, on_white};
use crate::{RenderOptions, Rendered, Renderer, fx};
use crate::{AntiAlias, RenderOptions, Rendered, Renderer, fx};
/// Most pixels a side of a PSD can have (larger images need the format's large-document variant).
pub const MAX_SIDE: u32 = 30_000;
@@ -34,6 +36,11 @@ pub struct PsdOptions {
/// its objects together (a clipping mask, an opacity mask, its own appearance, knockout) stays
/// one pixel layer.
pub max_editability: bool,
/// With `layers`: horizontal and vertical point type in layers and sublayers is written as type
/// layers that a reader can edit, each with its pixels: type in solid colours without strokes,
/// effects or an appearance of its own. A layer that holds such type becomes a group of its type
/// layers and pixel layers of the art between them.
pub preserve_text: bool,
/// With `layers`: hidden layers (and hidden objects) are written as hidden layers instead of
/// being left out.
pub hidden_layers: bool,
@@ -43,7 +50,7 @@ pub struct PsdOptions {
impl Default for PsdOptions {
fn default() -> Self {
Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, hidden_layers: false, embed_icc: true }
Self { color_model: ColorModel::Rgb, layers: true, max_editability: false, preserve_text: false, hidden_layers: false, embed_icc: true }
}
}
@@ -142,6 +149,8 @@ struct Record {
hidden: bool,
/// Section divider: [`OPEN_GROUP`] or [`END_GROUP`].
divider: Option<u32>,
/// A type layer's type tool object (`TySh`).
type_tool: Option<Vec<u8>>,
}
/// Section divider kinds.
@@ -160,6 +169,7 @@ impl Record {
opacity: 255,
hidden: false,
divider: None,
type_tool: None,
}
}
@@ -239,6 +249,9 @@ impl Record {
if let Some(kind) = self.divider {
block(&mut extra, b"lsct", &[&kind.to_be_bytes()[..], b"8BIM", &self.blend].concat())?;
}
if let Some(data) = &self.type_tool {
block(&mut extra, b"TySh", data)?;
}
out.extend(len32(extra.len())?.to_be_bytes());
out.extend(extra);
Ok(())
@@ -610,13 +623,40 @@ impl Parts<'_> {
return;
}
let (hidden, opacity) = (!n.visible, opacity_byte(n.opacity));
if self.o.max_editability
if self.o.preserve_text
&& let Some(t) = psd_type::editable(n)
{
let record = self.draw(n);
let [top, left, bottom, right] = record.rect.map(f64::from);
let origin = Point::new(self.region.x0, self.region.y0);
let aa = if self.ro.anti_alias == AntiAlias::None { TypeAntiAlias::None } else { t.anti_alias };
let type_tool = Some(psd_type::type_block(t, origin, self.scale, Rect::new(left, top, right, bottom), aa));
self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, type_tool, ..record });
return;
}
let per_object = self.o.max_editability;
let hidden_layers = self.o.hidden_layers;
if (per_object || self.o.preserve_text && holds_type(n, hidden_layers))
&& splits(n)
&& let Some(children) = n.children()
{
self.records.push(Record { divider: Some(END_GROUP), ..Record::empty(GROUP_END.into(), self.colors()) });
for c in children {
self.add(c);
if per_object {
for c in children {
self.add(c);
}
} else {
// The art between type layers stays together, one pixel layer per stretch.
let mut stretch: Vec<Arc<Node>> = vec![];
for c in children {
if type_layer(c, hidden_layers) {
self.add_stretch(n, std::mem::take(&mut stretch));
self.add(c);
} else {
stretch.push(c.clone());
}
}
self.add_stretch(n, stretch);
}
// A group in normal blending lets its layers blend with what is below it.
let blend = if n.blend == BlendMode::Normal && !n.isolate { *b"pass" } else { blend_key(n.blend) };
@@ -627,6 +667,22 @@ impl Parts<'_> {
self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, ..record });
}
/// `nodes`, children of layer `layer` next to each other, drawn together as one pixel layer
/// named after the layer (nothing when they paint nothing).
fn add_stretch(&mut self, layer: &Node, nodes: Vec<Arc<Node>>) {
if nodes.is_empty() {
return;
}
let mut part = layer.clone();
if let Some(children) = part.children_mut() {
*children = nodes;
}
let record = self.draw(&part);
if record.rect != [0; 4] {
self.records.push(record);
}
}
/// `n` drawn alone, visible, at full opacity in normal blending (its record carries those).
fn draw(&mut self, n: &Node) -> Record {
let name = n.display_name();
@@ -691,6 +747,30 @@ fn splits(n: &Node) -> bool {
matches!(n.kind, NodeKind::Layer { clip: false, .. }) && n.extras().mask.is_none() && n.knockout != Knockout::On && !fx::has_object_fx(n)
}
/// Does layer `n`, or a sublayer that can be written as a group, hold point type that can be a type
/// layer? Not when other art in it blends in a mode other than normal (the object, or a fill or
/// stroke of it, as [`Node::blends_through`] sees it): drawn as a pixel layer of its own, it would no
/// longer blend with the type or the art below. Hidden type counts only when `hidden` (Include
/// Hidden Layers) writes it.
fn holds_type(n: &Node, hidden: bool) -> bool {
let Some(children) = n.children().filter(|_| splits(n)) else { return false };
let mut held = false;
for c in children {
if type_layer(c, hidden) {
held = true;
} else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) {
return false;
}
}
held
}
/// Is child `c` written as a type layer, or as a group holding one ([`holds_type`])? A hidden child
/// is written only when `hidden`.
fn type_layer(c: &Node, hidden: bool) -> bool {
(c.visible || hidden) && (psd_type::editable(c).is_some() || holds_type(c, hidden))
}
/// Does anything in `n` carry effects of its own that may paint outside the art's bounds?
fn reaches_beyond(n: &Node) -> bool {
fx::has_object_fx(n) || n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c)))
+547
View File
@@ -0,0 +1,547 @@
//! Type layers of PSD export: point type as a type tool object (the `TySh` block of the format's
//! public specification), so a reader can edit the text. The block holds the text's transform, the
//! text descriptor (the text, its orientation and bounds, and its `EngineData`: the runs of
//! character and paragraph attributes with the fonts they use) and an unwarped warp descriptor.
//! The layer keeps its pixels for readers that show them.
use vectorcraft_color::Paint;
use vectorcraft_doc::text::TypeAntiAlias;
use vectorcraft_doc::{CharStyle, Composer, Justify, Node, NodeKind, ParaStyle, TextKind, TextObject};
use vectorcraft_geom::{Affine, Point, Rect};
/// Point type that a type layer draws as `n` draws: horizontal or vertical point type with text,
/// whose characters use only the attributes a type layer carries ([`carried`]) in solid colours
/// with whole-number tracking, each drawn with its own font (no fallback font), without strokes or
/// inline graphics, whose paragraphs set only an alignment ([`flat`]) and run left to right, and
/// without System Layout, Optical Margin Alignment, ruby, an appearance of its own, effects or an
/// opacity mask. Other type stays pixels.
pub(super) fn editable(n: &Node) -> Option<&TextObject> {
let NodeKind::Text(t) = &n.kind else { return None };
let text = t.plain_text();
let has_cjk = text.chars().any(cjk);
let flat = |p: &ParaStyle| flat(p, has_cjk);
let plain = matches!(t.kind, TextKind::Point)
&& !text.is_empty()
&& !t.system_layout
&& !t.optical_margin
&& t.ruby.is_empty()
&& !t.stacks_warichu()
&& flat(&t.para)
&& t.paras.iter().all(flat)
&& text.split('\n').enumerate().all(|(i, p)| !vectorcraft_text::paragraph_is_rtl(p, t.para_at(i).direction))
&& n.appearance.items.is_empty()
&& n.appearance.effects.is_empty()
&& n.extras().mask.is_none()
&& !crate::fx::has_object_fx(n)
&& t.runs
.iter()
.all(|r| r.inline.is_none() && matches!(r.style.fill, Paint::Solid { .. }) && matches!(r.style.stroke, Paint::None) && carried(&r.style))
// A type layer's tracking is a whole number of thousandths of an em.
&& t.runs.iter().all(|r| r.style.tracking.fract() == 0.0)
// The type layer names one font per run: a character its font lacks would be drawn with
// another. Breaks, joiners and variation selectors draw no glyph of their own (as the
// shaper's `drawn_chars` counts them).
&& t.runs.iter().all(|r| face(&r.style).is_some_and(|f| r.text.chars().all(|c| !drawn(c) || f.covers(c))));
plain.then_some(&**t)
}
/// Does `c` need a glyph of its own: not a control character (tab, line or paragraph break), a
/// line separator, a joiner or a variation selector?
fn drawn(c: char) -> bool {
!(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'))
}
/// The face the text of style `s` is drawn with: its font version when that is installed.
fn face(s: &CharStyle) -> Option<std::sync::Arc<vectorcraft_text::FontFace>> {
vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref())
}
/// Does paragraph `p` set only its alignment, the others being at their defaults (no indents,
/// spacing, tabs, bullets or numbers, direction, Auto Leading, word or letter spacing, glyph scaling
/// or hanging punctuation)? Settings that only choose where area type breaks its lines or what
/// hangs where it breaks them (hyphenation, the single-line or every-line composer, kinsoku,
/// Burasagari, Bunri-Kinshi, breaking Korean anywhere) and the paragraph style's name may be set,
/// and so may Mojikumi when `cjk` is false (it spaces only Chinese, Japanese and Korean characters).
/// A paragraph set to a Standard composer is not flat.
fn flat(p: &ParaStyle, cjk: bool) -> bool {
let only = ParaStyle {
justify: p.justify,
style_name: p.style_name.clone(),
hyphenate: p.hyphenate,
hyphenation: p.hyphenation.clone(),
composer: if matches!(p.composer, Composer::SingleLine | Composer::EveryLine) { p.composer } else { ParaStyle::default().composer },
kinsoku: p.kinsoku,
kinsoku_type: p.kinsoku_type,
burasagari: p.burasagari,
bunri_kinshi: p.bunri_kinshi,
korean_line_break_anywhere: p.korean_line_break_anywhere,
mojikumi: if cjk { ParaStyle::default().mojikumi } else { p.mojikumi },
..ParaStyle::default()
};
only == *p
}
/// Is `c` in a block of Chinese, Japanese or Korean characters or their punctuation?
fn cjk(c: char) -> bool {
matches!(c, '\u{1100}'..='\u{11FF}' | '\u{2E80}'..='\u{9FFF}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{F900}'..='\u{FAFF}' | '\u{FE30}'..='\u{FE4F}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{3FFFF}')
}
/// Does `s` set only attributes a type layer carries (font and its version, size, leading,
/// tracking, scaling, baseline shift, all caps, underline, strikethrough, fill), the others being
/// at their defaults? Attributes that change nothing drawn without a stroke (the stroke's own
/// settings, overprint, the character style's name) may be set, and so may the language when it
/// is the default, English: USA. The type layer does not record the language, so type in another
/// language stays pixels.
fn carried(s: &CharStyle) -> bool {
if !s.language.as_deref().is_none_or(|l| l.eq_ignore_ascii_case("en-US")) {
return false;
}
let only = CharStyle {
language: s.language.clone(),
font_family: s.font_family.clone(),
font_style: s.font_style.clone(),
font_version: s.font_version.clone(),
size: s.size,
leading: s.leading,
tracking: s.tracking,
baseline_shift: s.baseline_shift,
h_scale: s.h_scale,
v_scale: s.v_scale,
fill: s.fill.clone(),
stroke: s.stroke.clone(),
stroke_width: s.stroke_width,
stroke_cap: s.stroke_cap,
stroke_join: s.stroke_join,
stroke_miter_limit: s.stroke_miter_limit,
stroke_dash: s.stroke_dash.clone(),
stroke_align: s.stroke_align,
overprint_fill: s.overprint_fill,
overprint_stroke: s.overprint_stroke,
style_name: s.style_name.clone(),
underline: s.underline,
strikethrough: s.strikethrough,
all_caps: s.all_caps,
..CharStyle::default()
};
only == *s
}
/// A value of the `EngineData` text engine document.
enum E {
Dict(Vec<(&'static str, E)>),
Array(Vec<E>),
Str(String),
Int(i64),
Real(f64),
Bool(bool),
}
impl E {
fn is_container(&self) -> bool {
match self {
E::Dict(_) => true,
E::Array(a) => a.iter().any(|v| matches!(v, E::Dict(_) | E::Array(_))),
_ => false,
}
}
/// Writes the value with tab indents and a key per line.
fn write(&self, depth: usize, out: &mut Vec<u8>) {
let tabs = |out: &mut Vec<u8>, n: usize| out.extend(std::iter::repeat_n(b'\t', n));
match self {
E::Dict(items) => {
out.extend(b"<<\n");
for (k, v) in items {
tabs(out, depth + 1);
out.push(b'/');
out.extend(k.as_bytes());
if v.is_container() {
out.push(b'\n');
tabs(out, depth + 1);
} else {
out.push(b' ');
}
v.write(depth + 1, out);
out.push(b'\n');
}
tabs(out, depth);
out.extend(b">>");
}
E::Array(items) if self.is_container() => {
out.extend(b"[\n");
for v in items {
tabs(out, depth);
v.write(depth, out);
out.push(b'\n');
}
tabs(out, depth);
out.push(b']');
}
E::Array(items) => {
out.push(b'[');
for v in items {
out.push(b' ');
v.write(depth, out);
}
out.extend(b" ]");
}
// UTF-16BE after a byte order mark, with `(`, `)` and `\` escaped.
E::Str(s) => {
out.push(b'(');
for b in [0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)) {
if matches!(b, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(b);
}
out.push(b')');
}
E::Int(i) => out.extend(i.to_string().as_bytes()),
E::Real(r) => out.extend(real(*r).as_bytes()),
E::Bool(b) => out.extend(if *b { &b"true"[..] } else { b"false" }),
}
}
}
/// A number as the text engine writes it: `12.0`, `.5`, `-.25`; at most five decimals.
fn real(r: f64) -> String {
if !r.is_finite() {
return "0.0".into();
}
let mut s = format!("{r:.5}");
while s.ends_with('0') {
s.pop();
}
if s.ends_with('.') {
s.push('0');
}
if s == "-0.0" {
s = "0.0".into();
}
match (s.strip_prefix("0."), s.strip_prefix("-0.")) {
(Some(rest), _) if rest != "0" => format!(".{rest}"),
(_, Some(rest)) => format!("-.{rest}"),
_ => s,
}
}
/// A descriptor value (the format's ActionDescriptor items).
enum V {
Text(String),
Enum(&'static str, &'static str),
Long(i32),
Doub(f64),
/// A unit (`#Pnt`: points) and its value.
UntF(&'static [u8; 4], f64),
Objc(&'static str, Vec<(&'static str, V)>),
Raw(Vec<u8>),
}
/// A class, key or enumeration id: a four-character code after a zero length, else its length and
/// bytes. `warp` is written as a string, as readers look it up.
fn id(out: &mut Vec<u8>, s: &str) {
if s.len() == 4 && s != "warp" {
out.extend(0u32.to_be_bytes());
} else {
out.extend((s.len() as u32).to_be_bytes());
}
out.extend(s.as_bytes());
}
/// A Unicode string: its UTF-16 unit count, then the units (`nul`: a terminating zero counted).
fn unicode(out: &mut Vec<u8>, s: &str, nul: bool) {
let units: Vec<u16> = s.encode_utf16().chain(nul.then_some(0)).collect();
out.extend((units.len() as u32).to_be_bytes());
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
}
/// A descriptor: an empty class name, the class id, then its items.
fn descriptor(out: &mut Vec<u8>, class: &str, items: &[(&str, V)]) {
unicode(out, "", false);
id(out, class);
out.extend((items.len() as u32).to_be_bytes());
for (key, v) in items {
id(out, key);
match v {
V::Text(s) => {
out.extend(b"TEXT");
unicode(out, s, true);
}
V::Enum(ty, value) => {
out.extend(b"enum");
id(out, ty);
id(out, value);
}
V::Long(i) => {
out.extend(b"long");
out.extend(i.to_be_bytes());
}
V::Doub(d) => {
out.extend(b"doub");
out.extend(d.to_be_bytes());
}
V::UntF(unit, d) => {
out.extend(b"UntF");
out.extend(*unit);
out.extend(d.to_be_bytes());
}
V::Objc(class, items) => {
out.extend(b"Objc");
descriptor(out, class, items);
}
V::Raw(data) => {
out.extend(b"tdta");
out.extend((data.len() as u32).to_be_bytes());
out.extend(data);
}
}
}
}
/// The PostScript name of the face the text is drawn with (the style's font version when that is
/// installed), as type layers name fonts; without the face installed, its family and style without
/// spaces.
fn postscript(s: &CharStyle) -> String {
if let Some(face) = face(s) {
return face.postscript_name();
}
let squeeze = |s: &str| -> String { s.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).collect() };
match s.font_style.as_str() {
"" | "Regular" => squeeze(&s.font_family),
style => format!("{}-{}", squeeze(&s.font_family), squeeze(style)),
}
}
/// The character attributes of `s` at `px` pixels per point, its font being `font` in the font set.
fn style_data(s: &CharStyle, font: usize, px: f64) -> E {
let rgb = match &s.fill {
Paint::Solid { color, .. } => color.to_rgb(),
_ => [0.0; 3],
};
E::Dict(vec![
("Font", E::Int(font as i64)),
("FontSize", E::Real(s.size * px)),
("FauxBold", E::Bool(false)),
("FauxItalic", E::Bool(false)),
("AutoLeading", E::Bool(s.leading.is_none())),
("Leading", E::Real(s.leading.unwrap_or(0.0) * px)),
("HorizontalScale", E::Real(s.h_scale / 100.0)),
("VerticalScale", E::Real(s.v_scale / 100.0)),
("Tracking", E::Int(s.tracking.round() as i64)),
("AutoKerning", E::Bool(true)),
("Kerning", E::Int(0)),
("BaselineShift", E::Real(s.baseline_shift * px)),
("FontCaps", E::Int(if s.all_caps { 2 } else { 0 })),
("Underline", E::Bool(s.underline)),
("Strikethrough", E::Bool(s.strikethrough)),
("FillFlag", E::Bool(true)),
("FillColor", E::Dict(vec![("Type", E::Int(1)), ("Values", E::Array([1.0, rgb[0], rgb[1], rgb[2]].map(|v| E::Real(f64::from(v))).into()))])),
])
}
/// The paragraph attributes of alignment `j`.
fn paragraph_data(j: Justify) -> E {
let n = match j {
Justify::Auto | Justify::Left => 0,
Justify::Right => 1,
Justify::Center => 2,
Justify::JustifyLeft => 3,
Justify::JustifyRight => 4,
Justify::JustifyCenter => 5,
Justify::JustifyAll => 6,
};
E::Dict(vec![("Justification", E::Int(n)), ("AutoLeading", E::Real(1.2)), ("LeadingType", E::Int(0))])
}
/// The anti-aliasing method `aa` as the text descriptor's `AntA` value and the `EngineData`
/// `AntiAlias` number.
fn anti_alias(aa: TypeAntiAlias) -> (&'static str, i64) {
match aa {
TypeAntiAlias::None => ("Anno", 0),
TypeAntiAlias::Crisp => ("AnCr", 1),
TypeAntiAlias::Strong => ("AnSt", 2),
TypeAntiAlias::Sharp => ("AnSh", 4),
}
}
/// The `EngineData` of `t` at `px` pixels per point, drawn with anti-aliasing `aa`: the text with a
/// `\r` after each paragraph, a style run per text run and a paragraph run per paragraph (lengths in
/// UTF-16 units), point type's shape, and the fonts.
fn engine_data(t: &TextObject, px: f64, aa: TypeAntiAlias) -> Vec<u8> {
let text = t.plain_text().replace('\n', "\r");
let mut fonts: Vec<String> = vec![];
let (mut styles, mut lengths) = (vec![], vec![]);
let runs: Vec<_> = t.runs.iter().filter(|r| !r.text.is_empty()).collect();
for (i, r) in runs.iter().enumerate() {
let name = postscript(&r.style);
let font = fonts.iter().position(|f| *f == name).unwrap_or_else(|| {
fonts.push(name);
fonts.len() - 1
});
styles.push(E::Dict(vec![("StyleSheet", E::Dict(vec![("StyleSheetData", style_data(&r.style, font, px))]))]));
// The closing `\r` belongs to the last run.
lengths.push(E::Int(r.text.encode_utf16().count() as i64 + i64::from(i + 1 == runs.len())));
}
let (mut paras, mut para_lengths) = (vec![], vec![]);
for (i, p) in text.split('\r').enumerate() {
paras.push(E::Dict(vec![(
"ParagraphSheet",
E::Dict(vec![("DefaultStyleSheet", E::Int(0)), ("Properties", paragraph_data(t.para_at(i).justify))]),
)]));
para_lengths.push(E::Int(p.encode_utf16().count() as i64 + 1));
}
let (writing, procession) = if t.vertical { (2, 1) } else { (0, 0) };
let point = |x: f64, y: f64| E::Array(vec![E::Real(x), E::Real(y)]);
let shape = E::Dict(vec![
("ShapeType", E::Int(0)),
("Procession", E::Int(procession)),
("Lines", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![]))])),
(
"Cookie",
E::Dict(vec![(
"Photoshop", // brand-ok: the key's name in the files
E::Dict(vec![
("ShapeType", E::Int(0)),
("PointBase", point(0.0, 0.0)),
(
"Base",
E::Dict(vec![
("ShapeType", E::Int(0)),
("TransformPoint0", point(1.0, 0.0)),
("TransformPoint1", point(0.0, 1.0)),
("TransformPoint2", point(0.0, 0.0)),
]),
),
]),
)]),
),
]);
let first = runs.first().map_or_else(|| style_data(&CharStyle::default(), 0, px), |r| style_data(&r.style, 0, px));
let resources = || {
E::Dict(vec![
(
"FontSet",
E::Array(
fonts
.iter()
.map(|f| E::Dict(vec![("Name", E::Str(f.clone())), ("Script", E::Int(0)), ("FontType", E::Int(1)), ("Synthetic", E::Int(0))]))
.collect(),
),
),
("StyleSheetSet", E::Array(vec![E::Dict(vec![("Name", E::Str("Normal RGB".into())), ("StyleSheetData", E::Dict(vec![]))])])),
(
"ParagraphSheetSet",
E::Array(vec![E::Dict(vec![
("Name", E::Str("Normal RGB".into())),
("DefaultStyleSheet", E::Int(0)),
("Properties", paragraph_data(Justify::Left)),
])]),
),
("TheNormalStyleSheet", E::Int(0)),
("TheNormalParagraphSheet", E::Int(0)),
])
};
let mut normal = resources();
// The normal style sheet holds the first run's attributes.
if let E::Dict(items) = &mut normal
&& let Some((_, E::Array(sheets))) = items.iter_mut().find(|(k, _)| *k == "StyleSheetSet")
&& let Some(E::Dict(sheet)) = sheets.first_mut()
&& let Some((_, data)) = sheet.iter_mut().find(|(k, _)| *k == "StyleSheetData")
{
*data = first;
}
let doc = E::Dict(vec![
(
"EngineDict",
E::Dict(vec![
("Editor", E::Dict(vec![("Text", E::Str(format!("{text}\r")))])),
("ParagraphRun", E::Dict(vec![("RunArray", E::Array(paras)), ("RunLengthArray", E::Array(para_lengths)), ("IsJoinable", E::Int(1))])),
("StyleRun", E::Dict(vec![("RunArray", E::Array(styles)), ("RunLengthArray", E::Array(lengths)), ("IsJoinable", E::Int(2))])),
("AntiAlias", E::Int(anti_alias(aa).1)),
("UseFractionalGlyphWidths", E::Bool(t.fractional_widths)),
(
"Rendered",
E::Dict(vec![
("Version", E::Int(1)),
("Shapes", E::Dict(vec![("WritingDirection", E::Int(writing)), ("Children", E::Array(vec![shape]))])),
]),
),
]),
),
("ResourceDict", resources()),
("DocumentResources", normal),
]);
let mut out = b"\n\n".to_vec();
doc.write(0, &mut out);
out.push(b'\n');
out
}
/// The `TySh` block of point type `t`, drawn into a canvas whose top left is `origin` (document
/// points) at `px` pixels per point with anti-aliasing `aa`; `ink` is what the layer paints, in
/// canvas pixels. The transform maps the text's own space, in pixels with its origin at the first
/// baseline's start, to the canvas.
pub(super) fn type_block(t: &TextObject, origin: Point, px: f64, ink: Rect, aa: TypeAntiAlias) -> Vec<u8> {
let [a, b, c, d, e, f] = t.xf.as_coeffs();
let xf = Affine::new([a, b, c, d, (e - origin.x) * px, (f - origin.y) * px]);
// The ink in text space: the canvas rectangle taken back through the transform.
let bounds = if xf.determinant().abs() > 1e-12 && [ink.x0, ink.y0, ink.x1, ink.y1].iter().all(|v| v.is_finite()) {
let inv = xf.inverse();
let pts = [(ink.x0, ink.y0), (ink.x1, ink.y0), (ink.x0, ink.y1), (ink.x1, ink.y1)].map(|(x, y)| inv * Point::new(x, y));
let (xs, ys) = (pts.map(|p| p.x), pts.map(|p| p.y));
let (min, max) = (|v: [f64; 4]| v.into_iter().fold(f64::INFINITY, f64::min), |v: [f64; 4]| v.into_iter().fold(f64::NEG_INFINITY, f64::max));
[min(xs), min(ys), max(xs), max(ys)]
} else {
[0.0; 4]
};
let rect = |class: &'static str| {
V::Objc(
class,
vec![
("Left", V::UntF(b"#Pnt", bounds[0])),
("Top ", V::UntF(b"#Pnt", bounds[1])),
("Rght", V::UntF(b"#Pnt", bounds[2])),
("Btom", V::UntF(b"#Pnt", bounds[3])),
],
)
};
let orientation = if t.vertical { "Vrtc" } else { "Hrzn" };
let mut out = 1u16.to_be_bytes().to_vec();
for v in xf.as_coeffs() {
out.extend(v.to_be_bytes());
}
// Text version 50, descriptor version 16.
out.extend(50u16.to_be_bytes());
out.extend(16u32.to_be_bytes());
descriptor(
&mut out,
"TxLr",
&[
("Txt ", V::Text(t.plain_text().replace('\n', "\r"))),
("textGridding", V::Enum("textGridding", "None")),
("Ornt", V::Enum("Ornt", orientation)),
("AntA", V::Enum("Annt", anti_alias(aa).0)),
("bounds", rect("bounds")),
("boundingBox", rect("boundingBox")),
("TextIndex", V::Long(0)),
("EngineData", V::Raw(engine_data(t, px, aa))),
],
);
// Warp version 1, descriptor version 16: no warp.
out.extend(1u16.to_be_bytes());
out.extend(16u32.to_be_bytes());
descriptor(
&mut out,
"warp",
&[
("warpStyle", V::Enum("warpStyle", "warpNone")),
("warpValue", V::Doub(0.0)),
("warpPerspective", V::Doub(0.0)),
("warpPerspectiveOther", V::Doub(0.0)),
("warpRotate", V::Enum("Ornt", "Hrzn")),
],
);
// The warped bounds: zeros without a warp.
out.extend([0u8; 16]);
out
}
+372 -2
View File
@@ -59,6 +59,8 @@ struct Rec {
opacity: u8,
hidden: bool,
divider: Option<usize>,
/// The type tool object of a type layer.
type_tool: Option<Vec<u8>>,
}
/// The file: header channels, colour mode, image resources, layer count and records.
@@ -96,7 +98,7 @@ fn parse(f: &[u8]) -> Parsed<'_> {
let end = p + 16 + u32_at(f, p + 12);
let mut q = p + 16 + 8;
q += (1 + f[q] as usize).next_multiple_of(4);
let (mut name, mut divider) = (String::new(), None);
let (mut name, mut divider, mut type_tool) = (String::new(), None, None);
while q < end {
assert_eq!(&f[q..q + 4], b"8BIM");
let len = u32_at(f, q + 8);
@@ -104,11 +106,12 @@ fn parse(f: &[u8]) -> Parsed<'_> {
match &f[q + 4..q + 8] {
b"luni" => name = String::from_utf16(&(0..u32_at(data, 0)).map(|i| u16_at(data, 4 + i * 2)).collect::<Vec<_>>()).unwrap(),
b"lsct" => divider = Some(u32_at(data, 0)),
b"TySh" => type_tool = Some(data.to_vec()),
_ => {}
}
q += 12 + len;
}
out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider });
out.records.push(Rec { name, rect, channels, blend, opacity, hidden: flags & 2 != 0, divider, type_tool });
p = end;
}
out
@@ -358,6 +361,373 @@ fn the_profile_and_the_size_limit() {
assert!(err.contains(&MAX_SIDE.to_string()), "{err}");
}
/// A descriptor value as the format's specification lays it out.
#[derive(Debug, PartialEq)]
enum Item {
Text(String),
Enum(String, String),
Long(i32),
Doub(f64),
Unit(String, f64),
Object(String, Vec<(String, Item)>),
Raw(Vec<u8>),
}
/// Reads an id (a four-character code after a zero length, else a length and its bytes) at `at`.
fn read_id(d: &[u8], at: &mut usize) -> String {
let n = u32_at(d, *at);
let len = if n == 0 { 4 } else { n };
let s = String::from_utf8(d[*at + 4..*at + 4 + len].to_vec()).unwrap();
*at += 4 + len;
s
}
fn read_unicode(d: &[u8], at: &mut usize) -> String {
let n = u32_at(d, *at);
let units: Vec<u16> = (0..n).map(|i| u16_at(d, *at + 4 + i * 2)).collect();
*at += 4 + n * 2;
String::from_utf16(&units).unwrap().trim_end_matches('\0').to_string()
}
/// Reads a descriptor at `at`: its class and items.
fn read_descriptor(d: &[u8], at: &mut usize) -> (String, Vec<(String, Item)>) {
read_unicode(d, at);
let class = read_id(d, at);
let count = u32_at(d, *at);
*at += 4;
let mut items = vec![];
for _ in 0..count {
let key = read_id(d, at);
let ty = d[*at..*at + 4].to_vec();
*at += 4;
let f64_at = |at: usize| f64::from_be_bytes(d[at..at + 8].try_into().unwrap());
let v = match &ty[..] {
b"TEXT" => Item::Text(read_unicode(d, at)),
b"enum" => Item::Enum(read_id(d, at), read_id(d, at)),
b"long" => {
*at += 4;
Item::Long(u32_at(d, *at - 4) as i32)
}
b"doub" => {
*at += 8;
Item::Doub(f64_at(*at - 8))
}
b"UntF" => {
let unit = String::from_utf8(d[*at..*at + 4].to_vec()).unwrap();
*at += 12;
Item::Unit(unit, f64_at(*at - 8))
}
b"Objc" => {
let (class, items) = read_descriptor(d, at);
Item::Object(class, items)
}
b"tdta" => {
let n = u32_at(d, *at);
*at += 4 + n;
Item::Raw(d[*at - n..*at].to_vec())
}
other => panic!("unexpected item type {other:?}"),
};
items.push((key, v));
}
(class, items)
}
/// A type tool object: its transform, its text descriptor and its warp descriptor.
struct TypeTool {
transform: [f64; 6],
text: Vec<(String, Item)>,
warp: (String, Vec<(String, Item)>),
}
fn type_tool(d: &[u8]) -> TypeTool {
assert_eq!(u16_at(d, 0), 1, "version");
let transform = std::array::from_fn(|i| f64::from_be_bytes(d[2 + i * 8..10 + i * 8].try_into().unwrap()));
assert_eq!((u16_at(d, 50), u32_at(d, 52)), (50, 16), "text and descriptor versions");
let mut at = 56;
let (class, text) = read_descriptor(d, &mut at);
assert_eq!(class, "TxLr");
assert_eq!((u16_at(d, at), u32_at(d, at + 2)), (1, 16), "warp and descriptor versions");
at += 6;
let warp = read_descriptor(d, &mut at);
assert_eq!(d.len(), (at + 16).next_multiple_of(2), "the four warped bounds end the block (padded to an even length)");
TypeTool { transform, text, warp }
}
fn item<'a>(items: &'a [(String, Item)], key: &str) -> &'a Item {
&items.iter().find(|(k, _)| k == key).unwrap_or_else(|| panic!("no {key}")).1
}
/// `s` as the text engine stores a string: UTF-16BE after a byte order mark.
fn engine_string(s: &str) -> Vec<u8> {
[0xFE, 0xFF].into_iter().chain(s.encode_utf16().flat_map(u16::to_be_bytes)).collect()
}
fn type_node(b: &mut DocBuilder, origin: (f64, f64), text: &str, f: impl FnOnce(&mut vectorcraft_doc::TextObject)) -> Node {
use vectorcraft_doc::{CharStyle, NodeKind, TextObject};
let style = CharStyle { size: 12.0, fill: vectorcraft_color::Paint::solid(Color::rgb8(0, 0, 0)), ..CharStyle::default() };
let mut t = TextObject::point(vectorcraft_geom::Point::new(origin.0, origin.1), text, style);
f(&mut t);
Node::new(b.alloc(), NodeKind::Text(Box::new(t)))
}
/// Layer 1: a red square, point type, a blue square.
fn type_doc() -> Document {
let mut b = DocBuilder::new(100.0, 60.0);
b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {});
let t = type_node(&mut b, (20.0, 40.0), "Hi\nyou", |_| {});
b.add(t);
b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {});
b.build()
}
#[test]
fn preserve_text_writes_point_type_as_a_type_layer_between_pixel_layers() {
let doc = type_doc();
let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }) };
let file = export(&doc, &o);
let p = parse(&file);
let rows: Vec<(&str, Option<usize>, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.divider, r.type_tool.is_some())).collect();
assert_eq!(
rows,
[
("</Layer group>", Some(3), false),
("Layer 1", None, false),
("Hi\nyou", None, true),
("Layer 1", None, false),
("Layer 1", Some(1), false),
],
"the layer becomes a group: the art below the type, the type layer, the art above it"
);
assert_eq!(p.records[1].rect, [0, 0, 60, 60], "the red square alone, at 2 pixels a point");
assert_eq!(p.records[3].rect, [20, 120, 80, 180], "the blue square alone");
assert_ne!(p.records[2].rect, [0; 4], "the type layer keeps its pixels");
let t = type_tool(p.records[2].type_tool.as_deref().unwrap());
assert_eq!(t.transform, [1.0, 0.0, 0.0, 1.0, 40.0, 80.0], "the first baseline's start, in pixels");
assert_eq!(item(&t.text, "Txt "), &Item::Text("Hi\ryou".into()));
assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Hrzn".into()));
let Item::Object(_, bounds) = item(&t.text, "bounds") else { panic!("bounds") };
let [l, top, r, bottom] = ["Left", "Top ", "Rght", "Btom"].map(|k| match item(bounds, k) {
Item::Unit(_, v) => *v,
other => panic!("{other:?}"),
});
assert!(l < 4.0 && top < 0.0 && r > l && bottom > 24.0, "the ink around the baselines: {l} {top} {r} {bottom}");
assert_eq!(t.warp.0, "warp");
assert_eq!(item(&t.warp.1, "warpStyle"), &Item::Enum("warpStyle".into(), "warpNone".into()));
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
let has = |needle: &[u8]| engine.windows(needle.len()).any(|w| w == needle);
assert!(has(&engine_string("Hi\ryou\r")), "the text ends with a paragraph break");
assert!(has(b"/FontSize 24.0"), "the size in pixels at 144 ppi");
assert!(has(b"/RunLengthArray [ 3 4 ]"), "a paragraph run per paragraph, breaks counted");
assert!(has(b"/RunLengthArray [ 7 ]"), "one style run over the text and the closing break");
assert!(has(b"/Values [ 1.0 0.0 0.0 0.0 ]"), "black");
assert!(has(b"/ShapeType 0"), "point type");
assert!(has(b"/UseFractionalGlyphWidths true"), "Fractional Widths on");
// A reader takes the file, and the merged image is the same render.
assert_eq!(craft_psd::PsdFile::from_bytes(&file).unwrap().layers().len(), p.records.len());
let plain = export(&doc, &RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) });
assert_eq!(merged(&file), merged(&plain));
assert_eq!(parse(&plain).records.iter().filter(|r| r.type_tool.is_some()).count(), 0, "off: no type layers");
}
#[test]
fn type_a_type_layer_cant_draw_stays_pixels() {
use vectorcraft_doc::{NodeKind, TextKind};
use vectorcraft_geom::PathData;
let mut b = DocBuilder::new(100.0, 60.0);
let area = type_node(&mut b, (10.0, 20.0), "Area", |t| {
t.kind = TextKind::Area { frame: PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(5.0, 5.0, 60.0, 50.0), 0.1)) };
});
b.add(area);
let stroked = type_node(&mut b, (10.0, 50.0), "Stroked", |t| {
t.runs[0].style.stroke = vectorcraft_color::Paint::solid(Color::rgb8(255, 0, 0));
t.runs[0].style.stroke_width = 1.0;
});
b.add(stroked);
let kerned = type_node(&mut b, (40.0, 50.0), "Kerned", |t| t.runs[0].style.kerning = Some(50.0));
b.add(kerned);
let indented = type_node(&mut b, (70.0, 50.0), "Indented", |t| t.para.first_line_indent = 4.0);
b.add(indented);
let listed = type_node(&mut b, (10.0, 35.0), "Listed", |t| t.para.list = Some(vectorcraft_doc::text::ParaList::default()));
b.add(listed);
let system = type_node(&mut b, (40.0, 35.0), "System", |t| t.system_layout = true);
b.add(system);
let hanging = type_node(&mut b, (70.0, 35.0), "\"Hung\"", |t| t.optical_margin = true);
b.add(hanging);
let tabbed = type_node(&mut b, (10.0, 10.0), "a\tb", |t| {
t.para.tabs = vec![vectorcraft_doc::TabStop { position: 30.0, align: Default::default(), leader: String::new(), align_on: '.' }];
});
b.add(tabbed);
let leading = type_node(&mut b, (40.0, 10.0), "Auto", |t| t.para.justification.auto_leading = 150.0);
b.add(leading);
let standard = type_node(&mut b, (40.0, 20.0), "Std", |t| t.para.composer = vectorcraft_doc::Composer::StandardEveryLine);
b.add(standard);
// Hebrew: right to left from its first strong character, so Auto alignment is right. In an
// installed font that covers it when there is one; otherwise its font lacks it.
let hebrew_face = vectorcraft_text::FontDb::global().face_covering('ש');
let hebrew = type_node(&mut b, (70.0, 10.0), "שלום", |t| {
if let Some(f) = &hebrew_face {
(t.runs[0].style.font_family, t.runs[0].style.font_style) = (f.family.clone(), f.style.clone());
}
});
b.add(hebrew);
let tracked = type_node(&mut b, (10.0, 58.0), "Tracked", |t| t.runs[0].style.tracking = 0.5);
b.add(tracked);
let british = type_node(&mut b, (70.0, 58.0), "Colour", |t| t.runs[0].style.language = Some("en-GB".into()));
b.add(british);
// Drawn partly with a fallback font: the bundled fonts have no 縦.
let fallback = type_node(&mut b, (40.0, 58.0), "A縦", |_| {});
b.add(fallback);
let mut doc = b.build();
let with = |o: PsdOptions| export(&doc, &opts(o));
assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way");
// An empty point type object has no text to edit.
let empty = Node::new(
doc.alloc_id(),
NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "", Default::default()))),
);
doc.insert(Some(doc.layers[0].id), usize::MAX, empty).unwrap();
let file = export(&doc, &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()));
}
#[test]
fn vertical_type_and_maximum_editability() {
let mut b = DocBuilder::new(100.0, 60.0);
b.rect(Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb8(255, 0, 0), |_| {});
let t = type_node(&mut b, (50.0, 10.0), "Up", |t| t.vertical = true);
b.add(t);
let hidden = type_node(&mut b, (10.0, 50.0), "Hidden", |_| {});
b.add(Node { visible: false, ..hidden });
let doc = b.build();
let o = opts(PsdOptions { preserve_text: true, max_editability: true, hidden_layers: true, ..PsdOptions::default() });
let file = export(&doc, &o);
let p = parse(&file);
let rows: Vec<(&str, bool, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.type_tool.is_some(), r.hidden)).collect();
let square = doc.layers[0].children().unwrap()[0].display_name();
assert_eq!(
rows,
[("</Layer group>", false, false), (square.as_str(), false, false), ("Up", true, false), ("Hidden", true, true), ("Layer 1", false, false)],
"each object a layer of its own; hidden type is a hidden type layer"
);
let t = type_tool(p.records[2].type_tool.as_deref().unwrap());
assert_eq!(item(&t.text, "Ornt"), &Item::Enum("Ornt".into(), "Vrtc".into()));
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
assert!(engine.windows(19).any(|w| w == b"/WritingDirection 2"), "vertical writing");
}
#[test]
fn type_layer_keeps_fractional_widths_off() {
let mut b = DocBuilder::new(100.0, 60.0);
let t = type_node(&mut b, (10.0, 30.0), "Whole", |t| t.fractional_widths = false);
b.add(t);
let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
let p = parse(&file);
let record = p.records.iter().find(|r| r.type_tool.is_some()).expect("a type layer");
let t = type_tool(record.type_tool.as_deref().unwrap());
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
let needle = b"/UseFractionalGlyphWidths false";
assert!(engine.windows(needle.len()).any(|w| w == needle), "whole-point advances, as the pixels are drawn");
}
#[test]
fn type_layer_keeps_the_anti_aliasing_method() {
use vectorcraft_doc::text::TypeAntiAlias;
let engine_anti_alias = |doc: &Document, o: &RasterExportOptions| {
let file = export(doc, o);
let p = parse(&file);
let t = type_tool(p.records.iter().find_map(|r| r.type_tool.as_deref()).expect("a type layer"));
let Item::Raw(engine) = item(&t.text, "EngineData") else { panic!("EngineData") };
let at = engine.windows(11).position(|w| w == b"/AntiAlias ").expect("AntiAlias");
let Item::Enum(_, method) = item(&t.text, "AntA") else { panic!("AntA") };
(method.clone(), engine[at + 11])
};
let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() });
for (aa, key, number) in [
(TypeAntiAlias::None, "Anno", b'0'),
(TypeAntiAlias::Sharp, "AnSh", b'4'),
(TypeAntiAlias::Crisp, "AnCr", b'1'),
(TypeAntiAlias::Strong, "AnSt", b'2'),
] {
let mut b = DocBuilder::new(100.0, 60.0);
let t = type_node(&mut b, (10.0, 30.0), "Edges", |t| t.anti_alias = aa);
b.add(t);
let doc = b.build();
assert_eq!(engine_anti_alias(&doc, &o), (key.to_string(), number), "{aa:?}");
let hard = RasterExportOptions { anti_alias: crate::AntiAlias::None, ..o.clone() };
assert_eq!(engine_anti_alias(&doc, &hard), ("Anno".to_string(), b'0'), "{aa:?} exported without anti-aliasing");
}
}
#[test]
fn variation_selectors_and_joiners_need_no_glyph() {
let mut b = DocBuilder::new(100.0, 60.0);
// In English: USA, the default language, given by its tag.
let t = type_node(&mut b, (10.0, 30.0), "A\u{FE0F}\u{200D}B\u{E0100}", |t| t.runs[0].style.language = Some("en-US".into()));
b.add(t);
let file = export(&b.build(), &opts(PsdOptions { preserve_text: true, ..PsdOptions::default() }));
assert_eq!(parse(&file).records.iter().filter(|r| r.type_tool.is_some()).count(), 1);
}
#[test]
fn hidden_type_left_out_keeps_its_layer_whole() {
let mut b = DocBuilder::new(100.0, 60.0);
b.rect(Rect::new(0.0, 0.0, 30.0, 30.0), Color::rgb8(255, 0, 0), |_| {});
let t = type_node(&mut b, (20.0, 40.0), "Hidden", |_| {});
b.add(Node { visible: false, ..t });
b.rect(Rect::new(60.0, 10.0, 90.0, 40.0), Color::rgb8(0, 0, 255), |_| {});
let doc = b.build();
let with = |o: PsdOptions| export(&doc, &opts(o));
assert_eq!(with(PsdOptions { preserve_text: true, ..PsdOptions::default() }), with(PsdOptions::default()), "one pixel layer either way");
let shown = parse(&with(PsdOptions { preserve_text: true, hidden_layers: true, ..PsdOptions::default() }))
.records
.iter()
.filter(|r| r.type_tool.is_some() && r.hidden)
.count();
assert_eq!(shown, 1, "with hidden layers: a hidden type layer");
}
#[test]
fn blending_art_keeps_its_layer_whole() {
use vectorcraft_color::BlendMode;
use vectorcraft_doc::AppearanceItem;
// The square's blend mode, on the object (`fill`: false) or on its fill.
let build = |blend: BlendMode, above: bool, fill: bool| {
let mut b = DocBuilder::new(100.0, 60.0);
let square = |b: &mut DocBuilder| {
b.rect(Rect::new(0.0, 0.0, 60.0, 40.0), Color::rgb8(255, 0, 0), |n| {
if !fill {
n.blend = blend;
} else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.blend = blend;
}
});
};
if !above {
square(&mut b);
}
let t = type_node(&mut b, (10.0, 30.0), "Type", |_| {});
b.add(t);
if above {
square(&mut b);
}
b.build()
};
let o = opts(PsdOptions { preserve_text: true, ..PsdOptions::default() });
for (above, fill) in [(true, false), (false, false), (true, true)] {
let normal = export(&build(BlendMode::Normal, above, fill), &o);
assert_eq!(parse(&normal).records.iter().filter(|r| r.type_tool.is_some()).count(), 1, "normal art (above: {above}): a type layer");
let doc = build(BlendMode::Multiply, above, fill);
let file = export(&doc, &o);
assert!(parse(&file).records.iter().all(|r| r.type_tool.is_none()), "multiplied art (above: {above}, fill: {fill}): one pixel layer");
assert_eq!(file, export(&doc, &opts(PsdOptions::default())));
}
}
#[test]
fn long_unicode_name_is_cut_on_a_character_boundary() {
let mut b = DocBuilder::new(100.0, 60.0);