From 78058a35219d34becd09fad78aaaabe5b36ce764 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:50:09 -0800 Subject: [PATCH] PSD: type layers keep the type's anti-aliasing, and fallback-font type stays pixels A type layer now records the type's own anti-aliasing method (None, Sharp, Crisp or Strong; None when the export draws without anti-aliasing) instead of Smooth. Type with a character that its font lacks, and so is drawn with a fallback font, stays pixels; breaks, joiners and variation selectors do not count. Hidden type that the export leaves out (Include Hidden Layers off) no longer splits its layer, and a fill or stroke that blends in a mode other than Normal keeps the layer whole like an object that does. The reader test uses craft-psd, which replaced the psd crate on main. --- crates/render/src/encode/psd.rs | 23 +++++--- crates/render/src/encode/psd_type.rs | 60 +++++++++++++++------ crates/render/src/encode/tests_psd.rs | 75 +++++++++++++++++++++++++-- docs/mcp.md | 23 ++++---- 4 files changed, 142 insertions(+), 39 deletions(-) diff --git a/crates/render/src/encode/psd.rs b/crates/render/src/encode/psd.rs index f52fefd7d5..1dec0423e4 100644 --- a/crates/render/src/encode/psd.rs +++ b/crates/render/src/encode/psd.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, cms}; +use vectorcraft_doc::text::TypeAntiAlias; use vectorcraft_doc::{Document, Knockout, LayerColor, Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; @@ -469,13 +470,14 @@ impl Parts<'_> { 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)); + 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; - if (per_object || self.o.preserve_text && holds_type(n)) + 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() { @@ -488,7 +490,7 @@ impl Parts<'_> { // 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) { + if type_layer(c, hidden_layers) { self.add_stretch(n, std::mem::take(&mut stretch)); self.add(c); } else { @@ -589,12 +591,13 @@ fn splits(n: &Node) -> bool { /// 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 { +/// 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 psd_type::editable(c).is_some() || holds_type(c) { + if type_layer(c, hidden) { held = true; } else if Node::children_blend(std::slice::from_ref(c), &mut |c| c.blends_through()) { return false; @@ -603,6 +606,12 @@ fn holds_type(n: &Node) -> bool { 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))) diff --git a/crates/render/src/encode/psd_type.rs b/crates/render/src/encode/psd_type.rs index 928df932a3..323242f4a7 100644 --- a/crates/render/src/encode/psd_type.rs +++ b/crates/render/src/encode/psd_type.rs @@ -5,14 +5,16 @@ //! The layer keeps its pixels for readers that show them. use vectorcraft_color::Paint; +use vectorcraft_doc::text::TypeAntiAlias; 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. +/// 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(); @@ -33,10 +35,25 @@ pub(super) fn editable(n: &Node) -> Option<&TextObject> { .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); + && 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> { + 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 (hyphenation, @@ -266,7 +283,7 @@ fn descriptor(out: &mut Vec, class: &str, items: &[(&str, V)]) { /// 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()) { + 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() }; @@ -317,10 +334,21 @@ fn paragraph_data(j: Justify) -> E { 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 { +/// 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 { let text = t.plain_text().replace('\n', "\r"); let mut fonts: Vec = vec![]; let (mut styles, mut lengths) = (vec![], vec![]); @@ -410,7 +438,7 @@ fn engine_data(t: &TextObject, px: f64, smooth: bool) -> 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 })), + ("AntiAlias", E::Int(anti_alias(aa).1)), ("UseFractionalGlyphWidths", E::Bool(t.fractional_widths)), ( "Rendered", @@ -431,10 +459,10 @@ fn engine_data(t: &TextObject, px: f64, smooth: bool) -> Vec { } /// 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 { +/// 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 { 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. @@ -473,11 +501,11 @@ pub(super) fn type_block(t: &TextObject, origin: Point, px: f64, ink: Rect, smoo ("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" })), + ("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, smooth))), + ("EngineData", V::Raw(engine_data(t, px, aa))), ], ); // Warp version 1, descriptor version 16: no warp. diff --git a/crates/render/src/encode/tests_psd.rs b/crates/render/src/encode/tests_psd.rs index 5c3c05768a..ce9aebc6f5 100644 --- a/crates/render/src/encode/tests_psd.rs +++ b/crates/render/src/encode/tests_psd.rs @@ -526,7 +526,7 @@ fn preserve_text_writes_point_type_as_a_type_layer_between_pixel_layers() { 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); + 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"); @@ -562,11 +562,20 @@ fn type_a_type_layer_cant_draw_stays_pixels() { 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), "שלום", |_| {}); + // 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); + // 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"); @@ -585,7 +594,7 @@ fn type_a_type_layer_cant_draw_stays_pixels() { 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); + 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 }); @@ -597,7 +606,7 @@ fn vertical_type_and_maximum_editability() { 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)], + [("", 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()); @@ -620,6 +629,62 @@ fn type_layer_keeps_fractional_widths_off() { 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); + let t = type_node(&mut b, (10.0, 30.0), "A\u{FE0F}\u{200D}B\u{E0100}", |_| {}); + 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; diff --git a/docs/mcp.md b/docs/mcp.md index 6a6ba60b62..361bd08178 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8641,17 +8641,18 @@ 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 +baseline shift, caps, underline, strikethrough, fill color, Fractional Widths, paragraph alignment, orientation and +anti-aliasing method (None with `antiAlias: none`), 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 whose characters are all in their own font (none drawn with a fallback font), +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. Hidden +type counts only with `hiddenLayers`. With `maxEditability`, every object is a layer as above. The PSD Options dialog has the option as Preserve Text Editability (). ```json