mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 16:42:33 +00:00
PSD: Preserve Text Editability writes point type as editable type layers
The PSD Options dialog gets Preserve Text Editability, and document.export takes preserveText (with layers). Horizontal and vertical point type is written as a type layer (a TySh block with its EngineData) that a reader can edit, and keeps its pixels. The layer holds the text, its fonts by PostScript name, size, leading, tracking, scaling, baseline shift, caps, underline, strikethrough, fill color, Fractional Widths, paragraph alignment and orientation. Type that a type layer would draw differently stays pixels: area type, type on a path, strokes, non-solid fills, fractional tracking, character attributes the layer does not carry, paragraphs that set more than their alignment or run right to left, System Layout, Optical Margin Alignment, ruby, effects, an appearance of its own and opacity masks. A layer that holds type becomes a group of its type layers and pixel layers of the art between them, unless other art in it blends in a mode other than Normal.
This commit is contained in:
@@ -8,12 +8,13 @@ use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, cms};
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind};
|
||||
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;
|
||||
@@ -33,6 +34,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,
|
||||
@@ -42,7 +48,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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +147,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.
|
||||
@@ -159,6 +167,7 @@ impl Record {
|
||||
opacity: 255,
|
||||
hidden: false,
|
||||
divider: None,
|
||||
type_tool: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,6 +247,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(())
|
||||
@@ -451,13 +463,39 @@ 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 smooth = self.ro.anti_alias != AntiAlias::None;
|
||||
let type_tool = Some(psd_type::type_block(t, origin, self.scale, Rect::new(left, top, right, bottom), smooth));
|
||||
self.records.push(Record { blend: blend_key(n.blend), opacity, hidden, type_tool, ..record });
|
||||
return;
|
||||
}
|
||||
let per_object = self.o.max_editability;
|
||||
if (per_object || self.o.preserve_text && holds_type(n))
|
||||
&& 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 psd_type::editable(c).is_some() || holds_type(c) {
|
||||
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) };
|
||||
@@ -468,6 +506,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();
|
||||
@@ -532,6 +586,23 @@ 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.
|
||||
fn holds_type(n: &Node) -> bool {
|
||||
let Some(children) = n.children().filter(|_| splits(n)) else { return false };
|
||||
let mut held = false;
|
||||
for c in children {
|
||||
if psd_type::editable(c).is_some() || holds_type(c) {
|
||||
held = true;
|
||||
} else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
held
|
||||
}
|
||||
|
||||
/// 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)))
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
//! 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::{CharStyle, 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, 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 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);
|
||||
plain.then_some(&**t)
|
||||
}
|
||||
|
||||
/// 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 (hyphenation,
|
||||
/// kinsoku, Bunri-Kinshi, breaking Korean anywhere) and the paragraph style's name may be set.
|
||||
fn flat(p: &ParaStyle) -> bool {
|
||||
let only = ParaStyle {
|
||||
justify: p.justify,
|
||||
style_name: p.style_name.clone(),
|
||||
hyphenate: p.hyphenate,
|
||||
hyphenation: p.hyphenation.clone(),
|
||||
kinsoku: p.kinsoku,
|
||||
kinsoku_type: p.kinsoku_type,
|
||||
bunri_kinshi: p.bunri_kinshi,
|
||||
korean_line_break_anywhere: p.korean_line_break_anywhere,
|
||||
..ParaStyle::default()
|
||||
};
|
||||
only == *p
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn carried(s: &CharStyle) -> bool {
|
||||
let only = CharStyle {
|
||||
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) = vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref()) {
|
||||
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 `EngineData` of `t` at `px` pixels per point: 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, smooth: bool) -> 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",
|
||||
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(if smooth { 3 } else { 0 })),
|
||||
("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; `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, smooth: bool) -> 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", if smooth { "AnSm" } else { "Anno" })),
|
||||
("bounds", rect("bounds")),
|
||||
("boundingBox", rect("boundingBox")),
|
||||
("TextIndex", V::Long(0)),
|
||||
("EngineData", V::Raw(engine_data(t, px, smooth))),
|
||||
],
|
||||
);
|
||||
// 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
|
||||
}
|
||||
@@ -58,6 +58,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.
|
||||
@@ -95,7 +97,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);
|
||||
@@ -103,11 +105,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
|
||||
@@ -344,6 +347,303 @@ 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!(::psd::Psd::from_bytes(&file).unwrap().layers().len(), 3);
|
||||
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);
|
||||
// Hebrew: right to left from its first strong character, so Auto alignment is right.
|
||||
let hebrew = type_node(&mut b, (70.0, 10.0), "שלום", |_| {});
|
||||
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 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), "縦", |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), ("縦", 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 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);
|
||||
|
||||
Reference in New Issue
Block a user