diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 4a3ca6265a..524e178552 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index c5b8858f98..c2140477ad 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -268,6 +268,8 @@ struct RasterOptions { /// PSD: Write Layers. layers: Option, max_editability: Option, + /// PSD: Preserve Text Editability (with layers). + preserve_text: Option, hidden_layers: Option, /// Appearance of Black › Printing / Exporting (`prefs.blackOutput`); agents can set it here too. rich_black: Option, @@ -350,6 +352,7 @@ impl RasterOptions { color_model, layers: self.layers.unwrap_or(true), max_editability: self.max_editability.unwrap_or(false), + preserve_text: self.preserve_text.unwrap_or(false), hidden_layers: self.hidden_layers.unwrap_or(false), embed_icc, }, @@ -374,6 +377,7 @@ fn check_options(format: RasterFormat, o: &RasterExportOptions) -> Result<()> { let r = match format { RasterFormat::Bmp if model == jpeg::ColorModel::Cmyk => Err("BMP files are RGB or grayscale: colorModel rgb or gray".to_string()), RasterFormat::Tga if model != jpeg::ColorModel::Rgb => Err("Targa files are RGB: colorModel rgb".to_string()), + RasterFormat::Psd if o.psd.preserve_text && !o.psd.layers => Err("preserveText writes type layers: it needs layers: true".to_string()), RasterFormat::Bmp => o.bmp.check(), RasterFormat::Tga => o.tga.check(), _ => Ok(()), diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 75b202c8ab..2429d5763f 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -318,6 +318,13 @@ const MAX_EDITABILITY: FormatOption = FormatOption { description: "with layers: layers and sublayers become groups and every object a layer of its own, named as the Layers panel names it (text by its text); clipping, masked or knockout layers stay one layer", }; +const PRESERVE_TEXT: FormatOption = FormatOption { + name: "preserveText", + ty: "boolean", + default: "false", + description: "with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers (with their pixels); a layer holding such 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; refused with layers: false", +}; + const PSD_HIDDEN_LAYERS: FormatOption = FormatOption { name: "hiddenLayers", ty: "boolean", @@ -339,6 +346,7 @@ const PSD_OPTIONS: &[FormatOption] = &[ ANTI_ALIAS, COLOR_MODEL, PSD_LAYERS, + PRESERVE_TEXT, MAX_EDITABILITY, PSD_HIDDEN_LAYERS, EMBED_ICC, diff --git a/crates/engine/src/cmd/fileio/tests_psd.rs b/crates/engine/src/cmd/fileio/tests_psd.rs index d4f03d78a3..42f87af488 100644 --- a/crates/engine/src/cmd/fileio/tests_psd.rs +++ b/crates/engine/src/cmd/fileio/tests_psd.rs @@ -69,6 +69,23 @@ fn psd_writes_layers_groups_and_text_named_after_it() { assert!(s.execute("document.export", &json!({"format": "psd", "colorModel": "lab"})).is_err()); } +#[test] +fn preserve_text_writes_point_type_as_type_layers_and_needs_layers() { + let mut s = session(); + let file = export(&mut s, json!({"preserveText": true})); + let (_, count, names) = layers(&file); + assert_eq!((count, names), (-4, vec!["Layer 1".into(), "".into(), "Hello".into(), "Words".into()]), "Words becomes a group"); + assert_eq!(file.windows(8).filter(|w| w == b"8BIMTySh").count(), 1, "one type layer"); + assert_eq!(export(&mut s, json!({"preserveText": false})), export(&mut s, json!({}))); + // Without layers there are no type layers to write. + let err = s.execute("document.export", &json!({"format": "psd", "layers": false, "preserveText": true})).unwrap_err().to_string(); + assert!(err.contains("preserveText") && err.contains("layers: true"), "{err}"); + assert!(s.execute("document.export", &json!({"format": "psd", "preserveText": "yes"})).is_err()); + // Other formats don't take it. + let r = s.execute("document.export", &json!({"format": "png", "preserveText": true})).unwrap(); + assert!(r["warnings"].to_string().contains("preserveText"), "{r}"); +} + #[test] fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { let mut s = Session::new(); @@ -79,7 +96,7 @@ fn psd_is_listed_with_its_options_and_writes_one_file_per_artboard() { (psd["label"].as_str(), psd["write"].as_bool(), psd["read"].as_bool(), psd["raster"].as_bool()), (Some("PSD"), Some(true), Some(true), Some(true)) ); - for k in ["colorModel", "layers", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { + for k in ["colorModel", "layers", "preserveText", "maxEditability", "hiddenLayers", "embedIcc", "ppi", "antiAlias", "background"] { assert!(psd["options"].get(k).is_some(), "psd takes {k}"); } let r = s.execute("document.export", &json!({"format": "psd", "useArtboards": true})).unwrap(); diff --git a/crates/render/src/encode.rs b/crates/render/src/encode.rs index 635f906839..decff12a65 100644 --- a/crates/render/src/encode.rs +++ b/crates/render/src/encode.rs @@ -10,6 +10,7 @@ pub mod gif; pub mod jpeg; pub mod png; pub mod psd; +mod psd_type; pub mod quantize; pub mod tga; pub mod tiff; diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index 98c031c89a..f52fefd7d5 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -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, + /// A type layer's type tool object (`TySh`). + type_tool: Option>, } /// 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> = 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>) { + 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))) diff --git a/crates/render/src/encode/psd_type.rs b/crates/render/src/encode/psd_type.rs new file mode 100644 index 0000000000..928df932a3 --- /dev/null +++ b/crates/render/src/encode/psd_type.rs @@ -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), + 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) { + let tabs = |out: &mut Vec, 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), +} + +/// 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, 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, s: &str, nul: bool) { + let units: Vec = 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, 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 { + let text = t.plain_text().replace('\n', "\r"); + let mut fonts: Vec = 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 { + 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 +} diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index a488cceff2..12c21f3831 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -58,6 +58,8 @@ struct Rec { opacity: u8, hidden: bool, divider: Option, + /// The type tool object of a type layer. + type_tool: Option>, } /// 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::>()).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), +} + +/// 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 = (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 { + [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, bool)> = p.records.iter().map(|r| (r.name.as_str(), r.divider, r.type_tool.is_some())).collect(); + assert_eq!( + rows, + [ + ("", 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, + [("", 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); diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 98d6225c17..ec99667fbb 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -344,5 +344,9 @@ pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, ids: &[&str], fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (format, path) = (d.str("format"), d.str("path")); app.ui.dialog = None; - io::export(app, Some(&format), Some(path), &super::export_as::exported(d, form::params(d))) + let mut params = form::params(d); + if format == "psd" { + psd_options::drop_unused(&mut params); + } + io::export(app, Some(&format), Some(path), &super::export_as::exported(d, params)) } diff --git a/crates/ui-egui/src/dialogs/psd_options.rs b/crates/ui-egui/src/dialogs/psd_options.rs index df31d80bb0..68aad6bf58 100644 --- a/crates/ui-egui/src/dialogs/psd_options.rs +++ b/crates/ui-egui/src/dialogs/psd_options.rs @@ -1,5 +1,5 @@ -//! The options of PSD (colour model, a flat image or layers, Maximum Editability, hidden layers, -//! profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the +//! The options of PSD (colour model, a flat image or layers, Preserve Text Editability, Maximum +//! Editability, hidden layers, profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the //! `psdOptions` dialog. use serde_json::{Map, Value, json}; @@ -17,12 +17,23 @@ pub(super) fn defaults(cmyk: bool, o: &mut Map) { o.extend([ ("colorModel".into(), json!(model.id())), ("layers".into(), json!(p.layers)), + ("preserveText".into(), json!(p.preserve_text)), ("maxEditability".into(), json!(p.max_editability)), ("hiddenLayers".into(), json!(p.hidden_layers)), ("embedIcc".into(), json!(p.embed_icc)), ]); } +/// Flat Image writes no layers: the options that need them are left out of the export's params +/// (`preserveText`, which the export refuses without layers). +pub(super) fn drop_unused(p: &mut Value) { + if p["layers"] == json!(false) + && let Some(o) = p.as_object_mut() + { + o.remove("preserveText"); + } +} + /// The grid rows of PSD's own options. pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) { label(ui, tl!("Color Model:")); @@ -36,7 +47,11 @@ pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui:: d.fields.insert("layers".into(), json!(layers)); } ui.add_enabled_ui(layers, |ui| { - for (key, text) in [("maxEditability", tl!("Maximum Editability")), ("hiddenLayers", tl!("Include Hidden Layers"))] { + for (key, text) in [ + ("preserveText", tl!("Preserve Text Editability")), + ("maxEditability", tl!("Maximum Editability")), + ("hiddenLayers", tl!("Include Hidden Layers")), + ] { ui.horizontal(|ui| { ui.add_space(22.0); form::check(ui, d, key, text); diff --git a/crates/ui-egui/src/dialogs/tests_psd.rs b/crates/ui-egui/src/dialogs/tests_psd.rs index a59cf58901..1816d56342 100644 --- a/crates/ui-egui/src/dialogs/tests_psd.rs +++ b/crates/ui-egui/src/dialogs/tests_psd.rs @@ -14,8 +14,8 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((spec(&d.kind).heading)(d), "PSD Options"); assert_eq!( - (d.str("colorModel"), d.bool("layers"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")), - ("rgb".into(), true, false, false, true) + (d.str("colorModel"), d.bool("layers"), d.bool("preserveText"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")), + ("rgb".into(), true, false, false, false, true) ); assert!(tiff_bmp_tga::keeps_alpha("psd", d), "layers keep transparency"); frame(&mut app); @@ -30,9 +30,11 @@ fn psd_options_pick_flat_or_layers_and_the_colour_model() { assert_eq!(i16::from_be_bytes([psd[at + 8], psd[at + 9]]), -3); assert!(app.ui.dialog.is_none()); - // Flat: flattened on white, so the background list starts at White. + // Flat: flattened on white, so the background list starts at White. Preserve Text + // Editability, still ticked, isn't sent: the export refuses it without layers. app.run("file.exportAs", json!({"format": "psd"})).unwrap(); confirm(&mut app).unwrap(); + set(&mut app, "preserveText", json!(true)); set(&mut app, "layers", json!(false)); set(&mut app, "colorModel", json!("gray")); assert!(!tiff_bmp_tga::keeps_alpha("psd", app.ui.dialog.as_ref().unwrap())); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b0bd90eb59..8bdbfa7a39 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -867,8 +867,8 @@ writes the HTML page to a temporary folder and opens it in the default browser ( PSD Options: Export As… with the PSD format (`file.exportAs {format: "psd"}`, then the save dialog) opens `psdOptions`: the raster rows of PNG Options (`ppi`, `background`, `antiAlias`), then `colorModel` (`rgb`, `cmyk`, `gray`; a CMYK document starts on `cmyk`), `layers` (true: Write Layers; false: Flat Image, whose background list starts at White), -`maxEditability` and `hiddenLayers` (with layers) and `embedIcc`. `ui.dialog.set` the fields and `ui.dialog.confirm` -writes the file(s) with `document.export`. +`preserveText`, `maxEditability` and `hiddenLayers` (with layers) and `embedIcc`. `ui.dialog.set` the fields and +`ui.dialog.confirm` writes the file(s) with `document.export`; with Flat Image it leaves `preserveText` out. Print: File → Print… (`file.print` with no params, Ctrl/Cmd+P) opens the `print` dialog on the document's print settings. Its fields are the `print.setup` settings (`copies`, `artboards`, `range`, `media`, `orientation`, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7a73bdc4c1..20eab1c0dd 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -294,7 +294,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | -| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | +| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | | WebP | export (Export for Screens) | yes | yes (lossless only; lossy written lossless with a warning) | | diff --git a/docs/mcp.md b/docs/mcp.md index ac0a768306..0168893606 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8616,6 +8616,25 @@ appearance of their own or knockout stay one pixel layer. Hidden layers and obje `hiddenLayers: true` writes them as hidden layers. `layers: false` writes one flat image, on white where nothing is drawn. Files are at most 30000 pixels a side. +`preserveText: true` (with layers; refused with `layers: false`) writes horizontal and vertical point type as type +layers that a reader can edit: each holds the text, its fonts (by PostScript name), sizes, leading, tracking, scaling, +baseline shift, caps, underline, strikethrough, fill color, Fractional Widths, paragraph alignment and orientation, at +the export's resolution, and keeps its pixels for readers that show them. The font is the installed version the +character style names, if any. VectorCraft writes only point type in solid colors with whole-number tracking that +sets no other character attribute (no stroke, kerning, rotation, OpenType feature, small caps, position or East Asian setting), whose +paragraphs set nothing but their alignment and line breaking (no indents, spacing, tabs, bullets or numbers, Auto +Leading, word or letter spacing) and run left to right (set, or from their first strong character), and that has no +inline graphics, ruby, System Layout, Optical Margin Alignment, effects, appearance of its own or opacity mask as a +type layer; other type, area type and type on a path stay pixels. Without `maxEditability`, a layer or sublayer that +holds such type becomes a group of its type layers and one pixel layer for each stretch of art between them, unless +other art in it blends in a mode other than Normal: then the layer stays one pixel layer. With +`maxEditability`, every object is a layer as above. The PSD Options dialog has the option as Preserve Text Editability +(). + +```json +{"name":"export","arguments":{"path":"/tmp/poster.psd","options":{"ppi":300,"preserveText":true}}} +``` + PSD files (`.psd`, and `.psb`, the large document format) place as their merged image, the flattened picture every PSD file carries: Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK (converted with the colour settings' CMYK) and Lab, at 1, 8, 16 and 32 bits per channel, sized by their resolution.