mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 14:03:16 -05:00
Merge remote-tracking branch 'origin/main' into feat/cutover-remaining-codecs
# Conflicts: # crates/engine/src/cmd/menucmds.rs
This commit is contained in:
commit
bfe5c253f4
281 files changed
+26222
-1840
No files matched your search
+252
-13
@@ -1,19 +1,22 @@
|
||||
//! PSD export: a layered bitmap at 8 bits per channel, written from the format's public
|
||||
//! specification. The file holds the header, the resolution and colour profile resources, the
|
||||
//! layer records and their channels (PackBits row by row; groups as section dividers), then the
|
||||
//! specification. The file holds the header, the resolution, colour profile and slices resources,
|
||||
//! the layer records and their channels (PackBits row by row; groups as section dividers), then the
|
||||
//! merged image, which readers that skip layers show. RGB, CMYK (stored as 255 − ink, as the
|
||||
//! format keeps inks) or grayscale.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, cms};
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeId, NodeKind, SliceKind, SliceOptions, SliceSource};
|
||||
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 +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,
|
||||
@@ -42,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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,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.
|
||||
@@ -159,6 +169,7 @@ impl Record {
|
||||
opacity: 255,
|
||||
hidden: false,
|
||||
divider: None,
|
||||
type_tool: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,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(())
|
||||
@@ -289,6 +303,8 @@ struct File {
|
||||
records: Vec<Record>,
|
||||
ppi: f64,
|
||||
icc: Option<Arc<[u8]>>,
|
||||
/// Image resource 1050's data, when the file has slices.
|
||||
slices: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Refuse a size the format can't store.
|
||||
@@ -319,7 +335,8 @@ impl File {
|
||||
out.extend(mode(self.model).to_be_bytes());
|
||||
// No colour mode data.
|
||||
out.extend(0u32.to_be_bytes());
|
||||
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the profile.
|
||||
// Image resources: the resolution (16.16 fixed point, pixels per inch shown in inches), the
|
||||
// profile, the slices.
|
||||
let ppi = if self.ppi.is_finite() && self.ppi > 0.0 { self.ppi } else { 72.0 };
|
||||
let fixed = (ppi.min(30_000.0) * 65536.0).round() as u32;
|
||||
let res = [fixed.to_be_bytes(), [0, 1, 0, 1], fixed.to_be_bytes(), [0, 1, 0, 1]].concat();
|
||||
@@ -328,6 +345,9 @@ impl File {
|
||||
if let Some(icc) = &self.icc {
|
||||
resource(&mut resources, 1039, icc)?;
|
||||
}
|
||||
if let Some(slices) = &self.slices {
|
||||
resource(&mut resources, SLICES, slices)?;
|
||||
}
|
||||
out.extend(len32(resources.len())?.to_be_bytes());
|
||||
out.extend(resources);
|
||||
self.write_layers(&mut out)?;
|
||||
@@ -377,17 +397,20 @@ fn icc(o: &PsdOptions) -> Result<Option<Arc<[u8]>>, String> {
|
||||
pub fn encode(img: &Rendered, ppi: f64, o: &PsdOptions) -> Result<Vec<u8>, String> {
|
||||
let inks = (o.color_model == ColorModel::Cmyk).then(|| jpeg::separated(img));
|
||||
let merged = planes(o.color_model, &img.to_straight(), inks.as_deref(), true, false);
|
||||
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)? }.write()
|
||||
File { width: img.width, height: img.height, model: o.color_model, merged, alpha: false, records: vec![], ppi, icc: icc(o)?, slices: None }
|
||||
.write()
|
||||
}
|
||||
|
||||
/// `region` of `doc` as a PSD with `opts` (see [`PsdOptions`]). The merged image is the export's
|
||||
/// render; with Write Layers each part is also drawn alone as its own layer, cropped to what it
|
||||
/// paints, its opacity and blend mode in the layer's record.
|
||||
/// paints, its opacity and blend mode in the layer's record. The user and object slices that reach
|
||||
/// into `region` are written with or without layers ([`slices`]).
|
||||
pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &RasterExportOptions) -> Result<Vec<u8>, String> {
|
||||
let o = &opts.psd;
|
||||
let scale = opts.scale();
|
||||
let (width, height) = crate::region_pixels(region, scale);
|
||||
check_size(width, height)?;
|
||||
let slices = slices(doc, region, scale, (width, height))?;
|
||||
let ro = opts.render_options(RasterFormat::Psd);
|
||||
let (mut merged, mut alpha) = {
|
||||
let px = r.render_region_with(doc, region, scale, &ro).to_straight();
|
||||
@@ -413,7 +436,156 @@ pub(crate) fn export(r: &mut Renderer, doc: &Document, region: Rect, opts: &Rast
|
||||
merged.pop();
|
||||
alpha = false;
|
||||
}
|
||||
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)? }.write()
|
||||
File { width, height, model: o.color_model, merged, alpha, records, ppi: opts.ppi, icc: icc(o)?, slices }.write()
|
||||
}
|
||||
|
||||
/// The image resource that holds the slices.
|
||||
const SLICES: u16 = 1050;
|
||||
|
||||
/// The most slices one file holds (as many as `document.open` reads).
|
||||
pub(crate) const MAX_SLICES: usize = 10_000;
|
||||
|
||||
/// The longest text of a slice, in UTF-16 units (as long as `document.open` reads).
|
||||
pub(crate) const MAX_SLICE_TEXT: usize = 65_536;
|
||||
|
||||
/// Resource 1050's data for the user and object slices of `doc` that reach into `region`, in the
|
||||
/// "Slices resource format" of the Photoshop File Formats Specification
|
||||
/// (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>), version 6: the bounds of all
|
||||
/// the slices, the group's name, the count, then one record per slice. `None` when no slice
|
||||
/// reaches into `region`. Each rectangle is the slice as laid out ([`Document::slice_layout`]),
|
||||
/// clipped to `region` and given in the `size` canvas's pixels at `scale`, at least one pixel
|
||||
/// each way. Every slice is written as one the user made (origin 2): an object slice keeps its
|
||||
/// rectangle and options. Auto slices aren't written; a reader lays them out again. An HTML Text
|
||||
/// slice is written as No Image with its type's text as HTML. Text alignment is written as the
|
||||
/// default. An error when a slice's bounds aren't finite, or there are more than [`MAX_SLICES`]
|
||||
/// slices, a text longer than [`MAX_SLICE_TEXT`], or more than 4 GB of slices ([`room`]).
|
||||
fn slices(doc: &Document, region: Rect, scale: f64, (w, h): (u32, u32)) -> Result<Option<Vec<u8>>, String> {
|
||||
let users: HashMap<NodeId, &SliceOptions> = doc.slices.iter().map(|s| (s.id, &s.options)).collect();
|
||||
let mut found = vec![];
|
||||
for area in doc.slice_layout().iter().filter(|a| a.source != SliceSource::Auto) {
|
||||
let Some(id) = area.id else { continue };
|
||||
let r = area.rect;
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
let number = area.number;
|
||||
return Err(format!("slice {number} has no finite bounds and can't be written to PSD"));
|
||||
}
|
||||
let Some(options) = users.get(&id).copied().or_else(|| doc.slice_options(id)) else { continue };
|
||||
// The part inside `region`, found before the region is rounded to whole pixels.
|
||||
let (x0, y0, x1, y1) = (r.x0.max(region.x0), r.y0.max(region.y0), r.x1.min(region.x1), r.y1.min(region.y1));
|
||||
if !(x0 < x1 && y0 < y1) {
|
||||
continue;
|
||||
}
|
||||
let edge = |v: f64, origin: f64, max: u32| ((v - origin) * scale).clamp(0.0, f64::from(max));
|
||||
let (l, t, r, b) = (edge(x0, region.x0, w), edge(y0, region.y0, h), edge(x1, region.x0, w), edge(y1, region.y0, h));
|
||||
// Whole pixels, at least one each way.
|
||||
let span = |a: f64, b: f64, max: u32| {
|
||||
let max = i64::from(max);
|
||||
let (mut a, mut b) = ((a.round() as i64).clamp(0, max), (b.round() as i64).clamp(0, max));
|
||||
if b <= a {
|
||||
a = a.min(max - 1);
|
||||
b = a + 1;
|
||||
}
|
||||
(a as i32, b as i32)
|
||||
};
|
||||
let ((l, r), (t, b)) = (span(l, r, w), span(t, b, h));
|
||||
let text = match options.kind {
|
||||
SliceKind::HtmlText => doc.node(id).map(html_text).unwrap_or_default(),
|
||||
_ => options.text.clone(),
|
||||
};
|
||||
found.push(([l, t, r, b], options, text));
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if found.len() > MAX_SLICES {
|
||||
let count = found.len();
|
||||
return Err(format!("the document has {count} slices, more than the {MAX_SLICES} a PSD file holds"));
|
||||
}
|
||||
let (mut top, mut left, mut bottom, mut right) = (i32::MAX, i32::MAX, 0, 0);
|
||||
for ([l, t, r, b], _, _) in &found {
|
||||
(left, top, right, bottom) = (left.min(*l), top.min(*t), right.max(*r), bottom.max(*b));
|
||||
}
|
||||
let mut out = 6u32.to_be_bytes().to_vec();
|
||||
for v in [top, left, bottom, right] {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
let stem = doc.title.rsplit_once('.').map_or(doc.title.as_str(), |(s, _)| s);
|
||||
unicode(&mut out, stem)?;
|
||||
out.extend((found.len() as u32).to_be_bytes());
|
||||
// IDs from 1.
|
||||
for ((rect, o, text), id) in found.into_iter().zip(1u32..) {
|
||||
out.extend(id.to_be_bytes());
|
||||
// Group 0; made by the user.
|
||||
out.extend(0u32.to_be_bytes());
|
||||
out.extend(2u32.to_be_bytes());
|
||||
unicode(&mut out, &o.name)?;
|
||||
out.extend(u32::from(o.kind == SliceKind::Image).to_be_bytes());
|
||||
for v in rect {
|
||||
out.extend(v.to_be_bytes());
|
||||
}
|
||||
for s in [&o.url, &o.target, &o.message, &o.alt] {
|
||||
unicode(&mut out, s)?;
|
||||
}
|
||||
// The cell text is HTML, as a No Image slice shows it.
|
||||
out.push(1);
|
||||
unicode(&mut out, &text)?;
|
||||
// The default horizontal and vertical alignment.
|
||||
out.extend([0; 8]);
|
||||
out.extend(background(o));
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// A slice's background as alpha, red, green and blue: none (all 0), the matte (alpha 0 over a
|
||||
/// colour) or an opaque `#rrggbb`.
|
||||
fn background(o: &SliceOptions) -> [u8; 4] {
|
||||
let bg = o.background.trim();
|
||||
if bg.eq_ignore_ascii_case("matte") {
|
||||
return [0, 255, 255, 255];
|
||||
}
|
||||
let hex = bg.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()));
|
||||
match hex.and_then(|h| u32::from_str_radix(h, 16).ok()) {
|
||||
Some(c) => {
|
||||
let [_, r, g, b] = c.to_be_bytes();
|
||||
[255, r, g, b]
|
||||
}
|
||||
None => [0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of type object `n` as the HTML an HTML Text slice shows: `&`, `<` and `>` escaped, a
|
||||
/// line break as `<br>` (CR LF is one break). Empty for anything but type.
|
||||
fn html_text(n: &Node) -> String {
|
||||
let NodeKind::Text(t) = &n.kind else { return String::new() };
|
||||
t.plain_text()
|
||||
.replace("\r\n", "\n")
|
||||
.split(['\n', '\r', '\u{2029}'])
|
||||
.map(|l| l.replace('&', "&").replace('<', "<").replace('>', ">"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("<br>")
|
||||
}
|
||||
|
||||
/// `s` as a Unicode string: a count of UTF-16 units, then the units. An error past
|
||||
/// [`MAX_SLICE_TEXT`] units, or when the string would take `out` past [`room`].
|
||||
fn unicode(out: &mut Vec<u8>, s: &str) -> Result<(), String> {
|
||||
let units = s.encode_utf16().count();
|
||||
if units > MAX_SLICE_TEXT {
|
||||
return Err(format!("a slice's text has more than the {MAX_SLICE_TEXT} characters a PSD file holds"));
|
||||
}
|
||||
room(out.len(), units)?;
|
||||
out.extend((units as u32).to_be_bytes());
|
||||
out.extend(s.encode_utf16().flat_map(|u| u.to_be_bytes()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An error when `units` UTF-16 units and their count, added to a slices resource of `len` bytes,
|
||||
/// make it longer than the 4 GB a PSD resource holds.
|
||||
pub(crate) fn room(len: usize, units: usize) -> Result<(), String> {
|
||||
let end = units.checked_mul(2).and_then(|n| n.checked_add(4)).and_then(|n| n.checked_add(len));
|
||||
match end.map(u32::try_from) {
|
||||
Some(Ok(_)) => Ok(()),
|
||||
_ => Err("the slices are too large for PSD (at most 4 GB)".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the parts of a document as layer records, bottom first.
|
||||
@@ -451,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) };
|
||||
@@ -468,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();
|
||||
@@ -532,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)))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
//! PSD export: the header, the layer records (names, bounds, opacity, blend modes, groups,
|
||||
//! hidden layers), the merged image, the colour models, and a reader's view of the file.
|
||||
//! hidden layers), the merged image, the colour models, the slices, and a reader's view of the
|
||||
//! file.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color};
|
||||
use vectorcraft_doc::{Document, LayerColor, Node};
|
||||
use vectorcraft_doc::{Document, LayerColor, Node, NodeId, Slice, SliceKind, SliceOptions};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::DocBuilder;
|
||||
|
||||
use super::jpeg::ColorModel;
|
||||
use super::psd::{MAX_SIDE, PsdOptions};
|
||||
use super::psd::{MAX_SIDE, MAX_SLICE_TEXT, MAX_SLICES, PsdOptions, room};
|
||||
use super::*;
|
||||
|
||||
/// A 100 × 60 pt document: a red square on Layer 1, and on "Top" a half-opaque blue multiply
|
||||
@@ -58,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.
|
||||
@@ -95,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);
|
||||
@@ -103,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
|
||||
@@ -357,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);
|
||||
@@ -365,3 +736,145 @@ fn long_unicode_name_is_cut_on_a_character_boundary() {
|
||||
let file = export(&b.build(), &opts(PsdOptions::default()));
|
||||
assert_eq!(parse(&file).records.last().unwrap().name, "a".repeat(254));
|
||||
}
|
||||
|
||||
/// `doc()` with a user slice over (20, 5)–(50, 15) and the red square made an object slice.
|
||||
fn sliced() -> Document {
|
||||
let mut d = doc();
|
||||
let red = d.layers[0].children().unwrap()[0].id;
|
||||
let user = SliceOptions {
|
||||
name: "banner".into(),
|
||||
url: "https://example.com/".into(),
|
||||
target: "_blank".into(),
|
||||
message: "Go".into(),
|
||||
alt: "Banner".into(),
|
||||
background: "#123456".into(),
|
||||
..SliceOptions::default()
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.slices.push(Slice { id, rect: Rect::new(20.0, 5.0, 50.0, 15.0), options: user });
|
||||
let cell = SliceOptions { kind: SliceKind::NoImage, text: "<b>Hi</b>".into(), background: "matte".into(), ..SliceOptions::default() };
|
||||
d.node_mut(red).unwrap().extras_mut().slice = Some(Box::new(cell));
|
||||
d
|
||||
}
|
||||
|
||||
/// The slices resource of `file` as an independent reader reads it.
|
||||
fn slices_of(file: &[u8]) -> Option<craft_psd::slices::SlicesResource> {
|
||||
let psd = craft_psd::PsdFile::from_bytes(file).expect("a PSD a reader takes");
|
||||
psd.resource(1050).map(|r| craft_psd::slices::SlicesResource::from_bytes(&r.data).expect("a slices resource a reader takes"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_written_with_or_without_layers() {
|
||||
let d = sliced();
|
||||
for layers in [true, false] {
|
||||
let file = export(&d, &opts(PsdOptions { layers, ..PsdOptions::default() }));
|
||||
let res = slices_of(&file).expect("the slices resource");
|
||||
assert_eq!((res.version, res.bounds, res.group_name.as_str()), (6, [5, 10, 40, 50], "Untitled-1"));
|
||||
let s = &res.slices;
|
||||
assert_eq!(s.len(), 2, "{s:?}");
|
||||
// Laid out top to bottom: the user slice, then the object slice, both written as made by
|
||||
// the user.
|
||||
let user = &s[0];
|
||||
assert_eq!((user.id, user.origin, user.layer_id, user.kind, user.rect), (1, 2, None, 1, [20, 5, 50, 15]));
|
||||
assert_eq!(
|
||||
(user.name.as_str(), user.url.as_str(), user.target.as_str(), user.message.as_str(), user.alt.as_str()),
|
||||
("banner", "https://example.com/", "_blank", "Go", "Banner")
|
||||
);
|
||||
assert_eq!(user.color, [255, 0x12, 0x34, 0x56]);
|
||||
let cell = &s[1];
|
||||
assert_eq!((cell.id, cell.origin, cell.kind, cell.rect), (2, 2, 0, [10, 10, 40, 40]));
|
||||
assert_eq!((cell.name.as_str(), cell.cell_text.as_str(), cell.cell_text_is_html), ("", "<b>Hi</b>", true));
|
||||
assert_eq!((cell.color[0], cell.color[1..].iter().any(|c| *c != 0)), (0, true), "the matte");
|
||||
assert_eq!((cell.horizontal_align, cell.vertical_align), (0, 0));
|
||||
}
|
||||
// A document without slices has no slices resource.
|
||||
assert!(slices_of(&export(&doc(), &opts(PsdOptions::default()))).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_are_cut_to_the_exported_region_in_its_pixels() {
|
||||
let doc = sliced();
|
||||
// The right part at 2 px a point: the user slice is cut at the region's left edge, and the red
|
||||
// square's slice ends at that edge.
|
||||
let o = RasterExportOptions { ppi: 144.0, ..opts(PsdOptions::default()) };
|
||||
let file = Renderer::new().export_region(&doc, Rect::new(40.0, 0.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
let res = slices_of(&file).unwrap();
|
||||
assert_eq!(res.slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[0, 10, 20, 30]]);
|
||||
assert_eq!(res.bounds, [10, 0, 30, 20]);
|
||||
// A region no slice reaches has none.
|
||||
let file = Renderer::new().export_region(&doc, Rect::new(60.0, 30.0, 100.0, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert!(slices_of(&file).is_none());
|
||||
// A slice thinner than a pixel keeps one pixel.
|
||||
let mut thin = doc.clone();
|
||||
thin.slices[0].rect = Rect::new(20.0, 5.0, 20.2, 15.0);
|
||||
let res = slices_of(&export(&thin, &opts(PsdOptions::default()))).unwrap();
|
||||
assert_eq!(res.slices[0].rect, [20, 5, 21, 15]);
|
||||
// The overlap is found before the region is rounded to whole pixels: a slice inside a region
|
||||
// that ends at 10.4 keeps its last pixel, and one past a region that ends at 10.6 isn't written.
|
||||
let o = opts(PsdOptions::default());
|
||||
let mut edge = doc.clone();
|
||||
edge.slices[0].rect = Rect::new(10.1, 5.0, 10.3, 15.0);
|
||||
edge.node_mut(edge.layers[0].children().unwrap()[0].id).unwrap().extras_mut().slice = None;
|
||||
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.4, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert_eq!(slices_of(&file).unwrap().slices.iter().map(|s| s.rect).collect::<Vec<_>>(), [[9, 5, 10, 15]]);
|
||||
edge.slices[0].rect = Rect::new(10.7, 5.0, 10.9, 15.0);
|
||||
let file = Renderer::new().export_region(&edge, Rect::new(0.0, 0.0, 10.6, 60.0), RasterFormat::Psd, &o).unwrap();
|
||||
assert!(slices_of(&file).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_html_text_slice_writes_one_break_for_each_line_ending() {
|
||||
use vectorcraft_doc::{CharStyle, NodeKind, TextObject};
|
||||
use vectorcraft_geom::Point;
|
||||
let mut d = DocBuilder::new(100.0, 60.0).build();
|
||||
let t = TextObject::point(Point::new(10.0, 30.0), "A\r\nB\rC\nD\u{2029}E", CharStyle { size: 12.0, ..CharStyle::default() });
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.extras_mut().slice = Some(Box::new(SliceOptions { kind: SliceKind::HtmlText, ..SliceOptions::default() }));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let res = slices_of(&export(&d, &opts(PsdOptions::default()))).unwrap();
|
||||
assert_eq!(res.slices[0].cell_text, "A<br>B<br>C<br>D<br>E");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slice_ids_count_from_1_and_the_limits_are_errors() {
|
||||
let mut doc = doc();
|
||||
for i in 0..20 {
|
||||
let id = doc.alloc_id();
|
||||
let x = f64::from(i) * 5.0;
|
||||
doc.slices.push(Slice { id, rect: Rect::new(x, 0.0, x + 5.0, 5.0), options: SliceOptions::default() });
|
||||
}
|
||||
let res = slices_of(&export(&doc, &opts(PsdOptions::default()))).unwrap();
|
||||
let ids: Vec<u32> = res.slices.iter().map(|s| s.id).collect();
|
||||
assert_eq!(ids, (1..=20).collect::<Vec<_>>());
|
||||
let export_err = |d: &Document| {
|
||||
Renderer::new().export_region(d, d.artboards[0].rect, RasterFormat::Psd, &opts(PsdOptions::default())).err().unwrap_or_default()
|
||||
};
|
||||
let mut long = doc.clone();
|
||||
long.slices[0].options.alt = "a".repeat(MAX_SLICE_TEXT + 1);
|
||||
let e = export_err(&long);
|
||||
assert!(e.contains("characters"), "{e}");
|
||||
let mut many = doc.clone();
|
||||
many.slices = (0..=MAX_SLICES as u64)
|
||||
.map(|i| Slice { id: NodeId(1_000_000 + i), rect: Rect::new(0.0, 0.0, 5.0, 5.0), options: SliceOptions::default() })
|
||||
.collect();
|
||||
let e = export_err(&many);
|
||||
assert!(e.contains("slices"), "{e}");
|
||||
// Not clipped to the artboard, a slice keeps bounds that aren't finite.
|
||||
let mut bad = doc;
|
||||
bad.slices_clip_to_artboard = false;
|
||||
bad.slices[0].rect = Rect::new(f64::NAN, 0.0, 5.0, 5.0);
|
||||
let e = export_err(&bad);
|
||||
assert!(e.contains("finite"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slices_past_4_gb_are_an_error_before_they_are_written() {
|
||||
let max = u32::MAX as usize;
|
||||
assert_eq!(room(0, MAX_SLICE_TEXT), Ok(()));
|
||||
assert_eq!(room(max - 4 - 2 * 10, 10), Ok(()));
|
||||
let e = room(max - 4 - 2 * 10, 11).err().unwrap_or_default();
|
||||
assert!(e.contains("4 GB"), "{e}");
|
||||
assert!(room(max, 0).is_err());
|
||||
assert!(room(0, usize::MAX).is_err());
|
||||
}
|
||||
Reference in new issue
Block a user