diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index de9e7aea25..eafb4616f1 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -444,8 +444,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { return Err("the export region is not finite".into()); } // Symbols' art is placed without clipping, as the scene places it. - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 5aa43b0a67..a0ad0eb1e4 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> { let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits))); for h in &mut feed.0 { h.write_u8(u8::from(text.first_para_continues)); + h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from)); for b in inline_bounds.clone() { match b { None => h.write_u8(0), diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 2b44af5c8d..9de39458b0 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -67,6 +67,12 @@ pub struct TextObject { /// it on a frame that leaves its thread and on a copy. Not saved. #[serde(skip)] pub first_para_continues: bool, + /// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the + /// last character of that paragraph in the frames before that a repeat mark could stand for + /// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout + /// reads it only while `first_para_continues` is on. Not saved. + #[serde(skip)] + pub first_para_lead: Option, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 46f86b68ca..5bd31f7699 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -94,6 +94,7 @@ impl TextObject { para: ParaStyle::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: AreaOptions::default(), path_effect: PathEffect::default(), path_align: PathAlign::default(), diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index c3db242ed0..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -271,6 +271,9 @@ pub struct ParaStyle { /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept /// with kinsoku None, where it has no effect. Off by default. pub bunri_kinshi: bool, + /// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts + /// a line is drawn as the character it repeats, and the text keeps the mark. Off by default. + pub kurikaeshi_moji_shori: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -375,6 +378,8 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] bunri_kinshi: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kurikaeshi_moji_shori: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, @@ -412,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -439,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -470,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -496,6 +504,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 294c08962a..aca35c2330 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -167,7 +167,7 @@ struct Placing { layers: WrittenLayers, } -/// The layers an exporter writes besides the shown, printing ones +/// The layers and objects an exporter writes besides the shown, printing ones /// ([`bake_document_placing_symbols`]). Template layers are never written. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WrittenLayers { @@ -175,16 +175,19 @@ pub struct WrittenLayers { pub hidden: bool, /// Layers that do not print. pub non_printing: bool, + /// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden + /// layers). + pub hidden_objects: bool, } /// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] -/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer /// that does not print when the export leaves those out ([`WrittenLayers`]). fn unwritten(n: &Node) -> bool { PLACING.with(|p| { p.borrow().as_ref().is_some_and(|p| match n.kind { NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), - _ => !n.visible, + _ => !(n.visible || p.layers.hidden_objects), }) }) } @@ -1047,13 +1050,14 @@ pub fn bake_document(doc: &Document) -> Option { /// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or /// in the art of the symbols it places) replaced by that art as the instance places it, baked /// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For -/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than -/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped -/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the -/// exporter places other instances. `layers`: the hidden layers and layers that do not print -/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden -/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The -/// symbols' own art is left as it is. +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and +/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`: +/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not +/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`: +/// the hidden layers, layers that do not print and hidden objects that the exporter writes. +/// Instances the export does not write (template layers, and the hidden objects and layers +/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as +/// it is. pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index 7e442b96ed..deb705752f 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() { } /// Every layer written, as DXF writes them (template layers are never written). -const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true }; +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; fn is_instance(d: &Document, id: u64) -> bool { d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) @@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() { } // An export that writes the layers that do not print, or the hidden layers, places that // layer's instance first; the template layer's instance is never placed. - for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + for (layers, first) in + [(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)] + { let out = bake(&d, Some((true, each, layers))).unwrap(); assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); } + // An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance + // first, and the instance in the hidden group would come next; the hidden layer's instance + // stays, since that layer is still left out. + let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap(); + assert!(!is_instance(&out, 901), "the hidden instance is placed"); + for id in [900, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } } /// `leaf` in `levels` groups, with ids from `id` up. diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 313d4f65ed..b8e3226ab5 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,21 +210,21 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( CLASSIC_ROTATE, "Rotate (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e3915797f2..aa95c8cfdd 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -103,8 +103,8 @@ pub use solids::{ with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, - rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, + graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index 7e73594d89..e62e34b55e 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -175,6 +175,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed /// in a clip of its footprint, neither with an opacity mask. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { + use std::sync::Arc; + use vectorcraft_doc::{Node, NodeKind}; + let (clip, mut underlay) = underlay(id, faces)?; + underlay.extend(faces.iter().cloned()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) +} + +/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to, +/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same +/// conditions as [`sealed`]. +pub(crate) fn underlay( + id: vectorcraft_doc::NodeId, + faces: &[std::sync::Arc], +) -> Option<(vectorcraft_doc::Node, Vec>)> { use std::sync::Arc; use vectorcraft_doc::{Appearance, Node, NodeKind}; let mut outline = vectorcraft_geom::BezPath::new(); @@ -207,9 +221,7 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc return None, } } - let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()); - underlay.extend(faces.iter().cloned()); - Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) + Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay)) } /// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a49e817ef2..0b760ee552 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -296,11 +296,35 @@ fn paint_copies(faces: usize, paint: &Paint) -> usize { faces.saturating_mul(4).saturating_mul(paint_bytes(paint)) } +/// Do Revolve's `options` light its surface with colored lights? +fn colored(options: &Revolve) -> bool { + options.light_color != [1.0; 3] || options.lights.is_some() +} + +/// Do Revolve's `faces` in `paint` lie over an underlay of themselves ([`sealed_run`])? Under +/// colored lights (`colored`), in a solid color or a gradient, when a face takes a smooth light +/// ramp ([`crate::lighting::rgb_gradient_art`], [`crate::lighting::gradient_art`], +/// [`crate::lighting::smooth_paint`]). Not in a gradient with transparent stops: its composed faces +/// carry its opacity mask, which the underlay does not take ([`crate::lighting::underlay`]). +fn seals(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> bool { + colored + && (matches!(paint, Paint::Gradient(_)) || paint.color().is_some()) + && faces.iter().any(|f| f.rgb_gradient.is_some() || f.light_gradient.is_some()) + && crate::lighting::opaque_paint(paint).1.is_none() +} + +/// The bytes the copies of `paint` take on Revolve's `faces` ([`paint_copies`]), twice that when the +/// faces lie over an underlay of themselves ([`seals`]). +fn surface_copies(faces: &[vectorcraft_three_d::Face], paint: &Paint, colored: bool) -> usize { + let copies = paint_copies(faces.len(), paint); + if seals(faces, paint, colored) { copies.saturating_mul(2) } else { copies } +} + /// An error when `path` does not revolve or when its surface in `item`'s paint takes `copies`, the /// bytes of an object's paint copies so far, past [`MAX_PAINT_COPIES`]. fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&AppearanceItem>, copies: &mut usize) -> Result<(), String> { let faces = vectorcraft_three_d::revolve(path, b, options)?; - *copies = copies.saturating_add(item.map_or(0, |i| paint_copies(faces.len(), &paint_of(i).0))); + *copies = copies.saturating_add(item.map_or(0, |i| surface_copies(&faces, &paint_of(i).0, colored(&options)))); if *copies > MAX_PAINT_COPIES { return Err("Revolve paint is too complex for this surface; reduce Segments or simplify the gradient".into()); } @@ -438,7 +462,9 @@ fn group_shadow( /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep -/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last +/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them +/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them. #[allow(clippy::too_many_arguments)] fn surface( doc: Option<&Document>, @@ -453,7 +479,7 @@ fn surface( expand: bool, copies: &mut Copies, cast: bool, -) -> Option<(Vec, Node, Option)> { +) -> Option<(Vec, Node, Option, bool)> { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead @@ -473,15 +499,16 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept)); + return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false)); } - let colored = options.light_color != [1.0; 3] || options.lights.is_some(); + let colored = colored(&options); let (faces, kept) = if cast { vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? } else { (vectorcraft_three_d::revolve(path, b, options).ok()?, None) }; - copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); + let seal = seals(&faces, &paint, colored); + copies.surfaces = copies.surfaces.saturating_add(surface_copies(&faces, &paint, colored)); if copies.surfaces > MAX_PAINT_COPIES { return None; } @@ -604,7 +631,62 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group, kept)) + Some((keys, group, kept, seal)) +} + +/// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal` +/// ([`sealed_run`]), keeping the surface's opacity and blending mode. +fn sealed_surface(id: NodeId, surface: Node, seal: bool) -> Node { + let NodeKind::Group { children, clip: false } = &surface.kind else { return surface }; + let Some(mut out) = seal.then(|| sealed_run(id, children)).flatten() else { return surface }; + out.opacity = surface.opacity; + out.blend = surface.blend; + out +} + +/// The faces `run` of one surface, in drawing order, over an underlay of themselves, all clipped +/// once to the faces' outline, as [`crate::lighting::sealed`] draws them. A face drawn with a part +/// of a graphic, a group of the face and that part, takes its face's underlay and stays in the +/// order with its part; the part is cut to its face's outline ([`crate::solids::graphics::surface_parts`]), +/// so the clip keeps it. `None` when [`crate::lighting::underlay`] does not take the faces. +fn sealed_run(id: NodeId, run: &[Arc]) -> Option { + let faces: Vec> = run + .iter() + .map(|face| match &face.kind { + NodeKind::Group { children, clip: false } => children.first().cloned(), + _ => Some(face.clone()), + }) + .collect::>()?; + if faces.is_empty() { + return None; + } + let (clip, mut underlay) = crate::lighting::underlay(id, &faces)?; + underlay.extend(run.iter().cloned()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) +} + +/// `faces` in their drawing order, each with the index of its surface. Each run of consecutive +/// faces of one surface that `seal` takes lies over an underlay of its own faces ([`sealed_run`]), +/// so no underlay reaches under another surface's faces, as Inflate's surfaces do +/// (`crate::solids::underlaid_runs`). A run the underlay does not take keeps its faces. +fn sealed_runs(id: NodeId, faces: Vec<(usize, Arc)>, seal: impl Fn(usize) -> bool) -> Vec> { + let mut out = Vec::with_capacity(faces.len()); + let mut run: Vec> = vec![]; + let mut faces = faces.into_iter().peekable(); + while let Some((surface, face)) = faces.next() { + run.push(face); + if faces.peek().is_some_and(|(next, _)| *next == surface) { + continue; + } + match seal(surface).then(|| sealed_run(id, &run)).flatten() { + Some(sealed) => { + out.push(Arc::new(sealed)); + run.clear(); + } + None => out.append(&mut run), + } + } + out } /// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the @@ -636,7 +718,8 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) + surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast) + .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) } /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of @@ -1055,6 +1138,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let mut surfaces = vec![]; // The faces each member's surface kept for the shadow, member by member. let mut kept = vec![]; + // Whether each member's faces lie over an underlay of themselves ([`surface`]). + let mut seals = vec![]; let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. @@ -1072,10 +1157,14 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); - let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; + let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); + seals.push(seal); } + // The faces of a member whose surface takes an underlay lie over one, run by run in the one + // order of every member's faces ([`sealed_runs`]). + let seal = |member: usize| seals.get(member) == Some(&true); if surfaces.is_empty() { return None; } @@ -1101,7 +1190,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let order = crate::solids::surface_order(faces.iter().map(|(d, ..)| (d.points.as_slice(), d.plane, d.depth))); let faces = in_order(faces, &order); if opaque { - vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(.., face)| face).collect()))] + vec![Arc::new(Node::group(n.id, sealed_runs(n.id, faces.into_iter().map(|(_, member, .., face)| (member, face)).collect(), seal)))] } else { // An opaque member's face goes in the order on its own. The faces of a member with // transparency share a run, one group with the opacity and blending mode of its fill or @@ -1110,6 +1199,8 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { // where one group can't be both behind and in front of another face. struct Run<'a> { member: Option, + // The member the faces are of. + of: usize, scopes: &'a [Scope], bounds: Rect, faces: Vec>, @@ -1125,12 +1216,12 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let paints = opacity > 0.0 && scopes.iter().all(|s| s.opacity > 0.0); let Some(cover) = Coverage::of(&face).filter(|_| paints) else { // A face that paints nothing goes in the order on its own and overlaps nothing. - runs.push(Run { member: None, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); + runs.push(Run { member: None, of: member, scopes, bounds: Rect::ZERO, faces: vec![face], cover: vec![], opacity, blend }); continue; }; let masked = masks.get(member).is_some_and(Option::is_some); if opacity >= 1.0 && blend == Default::default() && scopes.is_empty() && !masked { - runs.push(Run { member: None, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + runs.push(Run { member: None, of: member, scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); continue; } let mut clear = |r: &Run| { @@ -1153,24 +1244,49 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { if let Some(last) = last_run.get_mut(member) { *last = Some(runs.len()); } - runs.push(Run { member: Some(member), scopes, bounds: cover.bounds, faces: vec![face], cover: vec![cover], opacity, blend }); + runs.push(Run { + member: Some(member), + of: member, + scopes, + bounds: cover.bounds, + faces: vec![face], + cover: vec![cover], + opacity, + blend, + }); } } } - let runs = runs.into_iter().filter_map(|mut r| { + // Consecutive faces of opaque members on their own wait in `solo` and go over an + // underlay of their member's faces, run by run ([`sealed_runs`]). + let mut out: Vec<(&[Scope], Arc)> = Vec::with_capacity(runs.len()); + let mut solo: Vec<(usize, Arc)> = vec![]; + for mut r in runs { // A face on its own needs a group only for the opacity or blending mode of its fill or stroke. if r.member.is_none() && r.opacity >= 1.0 && r.blend == Default::default() { - return r.faces.pop().map(|face| (r.scopes, face)); + let Some(face) = r.faces.pop() else { continue }; + if r.scopes.is_empty() && !r.cover.is_empty() { + solo.push((r.of, face)); + } else { + out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face))); + out.push((r.scopes, face)); + } + continue; } - let mut group = Node::group(n.id, r.faces); + out.extend(sealed_runs(n.id, std::mem::take(&mut solo), seal).into_iter().map(|face| (&[][..], face))); + let mut group = match r.member.filter(|m| seal(*m)).and_then(|_| sealed_run(n.id, &r.faces)) { + Some(sealed) => sealed, + None => Node::group(n.id, r.faces), + }; group.opacity = r.opacity; group.blend = r.blend; if let Some(mask) = r.member.and_then(|m| masks.get(m)).cloned().flatten() { group.extras_mut().mask = Some(mask); } - Some((r.scopes, Arc::new(group))) - }); - scoped(n.id, runs.collect(), 0) + out.push((r.scopes, Arc::new(group))); + } + out.extend(sealed_runs(n.id, solo, seal).into_iter().map(|face| (&[][..], face))); + scoped(n.id, out, 0) } }; // One shadow for every member's surface, behind them all. @@ -1693,6 +1809,156 @@ mod tests { assert_eq!(revolve_art(&two), None, "past the budget the source draws"); let object = painted(3, 0.0, stops * 2); assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget"); + // Under a colored light the faces lie over an underlay of themselves, which copies their + // paints again: the gradient that fits in white light is past the budget. + let lit = json!({"lightColor": "#ff0000"}); + let object = painted(4, 0.0, stops); + assert_eq!(validate_revolve(&object, &json!({})), Ok(())); + let refused = validate_revolve(&object, &lit).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + let mut drawn = (*object).clone(); + drawn.appearance.effects.push(crate::new_effect(REVOLVE, &lit).unwrap()); + assert_eq!(revolve_art(&drawn), None, "past the budget the source draws"); + } + + /// Is `u` the underlay [`crate::lighting::underlay`] draws for `face`, a face [`surface`] draws? + fn underlies(u: &Node, face: &Node) -> bool { + match (&u.kind, &face.kind) { + (NodeKind::Path { .. }, NodeKind::Path { .. }) => { + u.path_data() == face.path_data() + && u.appearance.items.iter().all(|i| !matches!(i, AppearanceItem::Stroke(s) if s.width != crate::lighting::UNDERLAY_SEAM)) + } + (NodeKind::Group { children: under, clip: true }, NodeKind::Group { children, clip: true }) => { + matches!((under.get(1), children.get(1)), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) + } + (_, NodeKind::Group { children, clip: false }) => children.first().is_some_and(|f| underlies(u, f)), + _ => false, + } + } + + /// The runs of faces in `art` that lie over an underlay of themselves ([`sealed_run`]), each + /// run's faces in drawing order. + pub(super) fn sealed_faces(art: &Node) -> Vec>> { + let mut out = vec![]; + art.walk(&mut |n| { + let NodeKind::Group { children, clip: true } = &n.kind else { return }; + let [clip, inner] = &children[..] else { return }; + let NodeKind::Group { children: drawn, clip: false } = &inner.kind else { return }; + let (under, faces) = drawn.split_at(drawn.len() / 2); + if clip.path_data().is_some() && !inner.isolate && drawn.len() % 2 == 0 && under.iter().zip(faces).all(|(u, f)| underlies(u, f)) { + out.push(faces.to_vec()); + } + }); + out + } + + /// `n`'s surface as [`surface`] draws it before its faces are sealed, and whether they are. + fn unsealed(n: &Node) -> (Node, bool) { + let path = n.path_data().unwrap(); + let fx = n.appearance.effects.first().unwrap(); + let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap()); + let (_, art, _, seal) = + surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap(); + (art, seal) + } + + #[test] + fn colored_light_faces_lie_over_an_underlay_of_themselves_once_per_surface() { + use vectorcraft_doc::color::{BlendMode, Gradient, GradientKind, GradientPaint, GradientStop}; + let lit = |params: Value, paint: Paint| { + let mut n = profile_node(); + n.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + n.appearance.effects.push(crate::new_effect(REVOLVE, ¶ms).unwrap()); + n + }; + let red = Paint::solid(Color::rgb(0.8, 0.2, 0.1)); + let ramp = |opacity: f32| { + let stops = [Color::WHITE, Color::rgb(0.5, 0.5, 0.5)].into_iter().enumerate(); + let stops = stops.map(|(i, c)| GradientStop { opacity, ..GradientStop::new(i as f32, c) }).collect(); + Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))) + }; + let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]); + // In white light nothing is sealed. + let white = lit(json!({}), red.clone()); + assert!(!unsealed(&white).1); + assert!(sealed_faces(&revolve_art(&white).unwrap()).is_empty()); + for (name, n) in [ + ("solid", lit(json!({"lightColor": "#ff0000"}), red.clone())), + ("gradient", lit(json!({"lightColor": "#ff0000"}), ramp(1.0))), + ("two lights", lit(json!({"lights": lights}), ramp(1.0))), + ("edge-on", lit(json!({"lightColor": "#ff0000", "rotationX": -80}), red.clone())), + ] { + // Every face of the surface, in its order, lies over its underlay, once. + let (plain, seal) = unsealed(&n); + assert!(seal, "{name}"); + let faces = plain.children().unwrap().to_vec(); + assert_eq!(sealed_faces(&revolve_art(&n).unwrap()), vec![faces], "{name}"); + } + // The surface's opacity and blending mode apply once, to the sealed surface. + let mut n = lit(json!({"lightColor": "#ff0000"}), ramp(1.0)); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.5; + f.blend = BlendMode::Multiply; + } + let art = revolve_art(&n).unwrap(); + assert_eq!(sealed_faces(&art).len(), 1); + // Inside the surface only a face's own lit art blends (its light multiplied over its paint). + let once = |chain: &Chain| chain.first() == Some(&(0.5, BlendMode::Multiply)) && chain.iter().skip(1).all(|(o, _)| *o == 1.0); + let faces = faces_in_order(&art); + assert!(faces.iter().all(|(_, chain)| once(chain)), "{:?}", faces.iter().map(|f| &f.1).find(|c| !once(c))); + // Faces in a gradient with transparent stops carry its opacity mask, which the underlay + // does not take: the surface keeps its faces as they are, and their paints are not + // counted twice. + let n = lit(json!({"lightColor": "#ff0000"}), ramp(0.6)); + let (plain, seal) = unsealed(&n); + assert!(!seal); + assert_eq!(sealed_surface(n.id, plain.clone(), true), plain); + assert!(sealed_faces(&revolve_art(&n).unwrap()).is_empty()); + let path = n.path_data().unwrap(); + let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), fx_options(&n.appearance.effects[0])).unwrap(); + assert_eq!(surface_copies(&faces, &ramp(0.6), true), paint_copies(faces.len(), &ramp(0.6))); + assert_eq!(surface_copies(&faces, &ramp(1.0), true), 2 * paint_copies(faces.len(), &ramp(1.0))); + // Revolve (Classic) takes no colored light, so none of its faces are sealed. + assert!(!colored(&classic::options(&json!({"lightColor": "#ff0000"})))); + } + + #[test] + fn each_members_run_of_faces_lies_over_an_underlay_of_its_own() { + // Rings one above the other: their faces alternate in the one order, so each ring's + // faces go over underlays run by run, and no run holds faces of both. + let ring = |id, y: f64, opacity: f32| { + let mut n = (*member(id, 40.0)).clone(); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = opacity; + } + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = PathData::from_bezpath(&(Affine::translate((0.0, y)) * path.to_bezpath())); + } + Arc::new(n) + }; + let lit = json!({"segments": 16, "lightColor": "#ff0000"}); + for opacity in [1.0, 0.5] { + let members = vec![ring(1, 0.0, 1.0), ring(2, 200.0, opacity)]; + let art = revolve_art(&group_with(lit.clone(), members.clone())).unwrap(); + let runs = sealed_faces(&art); + assert!(runs.len() >= 2, "{opacity}: {} runs", runs.len()); + for run in &runs { + let ys: Vec = run.iter().filter_map(|f| f.visual_bounds()).map(|b| b.center().y).collect(); + assert!(ys.iter().all(|y| *y < 100.0) || ys.iter().all(|y| *y > 100.0), "{opacity}: a run holds one ring's faces: {ys:?}"); + } + // Each ring's opacity applies once, to its faces and their underlays; inside, only a + // face's own lit art blends. + let faded = |chain: &Chain| chain.iter().filter(|(o, _)| *o != 1.0).count(); + let chains: Vec = faces_in_order(&art).into_iter().map(|(_, c)| c).collect(); + assert!(chains.iter().all(|c| faded(c) <= 1 && c.iter().all(|(o, _)| *o == 1.0 || *o == opacity)), "{opacity}"); + assert_eq!(chains.iter().any(|c| faded(c) == 1), opacity < 1.0, "{opacity}"); + if opacity == 1.0 { + // Opaque rings share one order, and every face in it lies over an underlay. + let white = revolve_art(&group_with(json!({"segments": 16}), members)).unwrap(); + let count = white.children().unwrap()[0].children().unwrap().len(); + assert_eq!(runs.iter().map(Vec::len).sum::(), count); + } + } } #[test] diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 8dc013e9dc..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -164,6 +164,41 @@ mod tests { } } + /// With Black Overprint every face keeps the blue, and the faces that darken get black over it, + /// overprinting, as strong as the darkening of the shading color Black. + #[test] + fn black_overprint_keeps_the_blue_under_overprinting_black() { + let darkened = revolved(json!({"surface": "diffuse"})); + let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"})); + let (darkened, drawn) = (faces(&darkened), faces(&art)); + assert_eq!(darkened.len(), drawn.len()); + let mut shaded = 0; + for (face, black) in drawn.iter().zip(&darkened) { + let fills: Vec<&vectorcraft_doc::FillLayer> = face + .appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }) + .collect(); + assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false)); + let k = match fills.get(1) { + Some(shadow) => { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + shaded += 1; + k + } + None => 0.0, + }; + let b = fill(black).unwrap().to_rgb()[2]; + assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}"); + } + assert!(shaded > 0, "faces turned from the light get black"); + } + #[test] fn angle_offset_edge_and_cap_shape_the_surface() { let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 5d9500628b..e21a88a26e 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -279,6 +279,23 @@ fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() { assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}"); } +#[test] +fn under_a_colored_light_each_part_of_a_graphic_stays_right_after_its_face_over_the_underlay() { + let d = document(); + let n = revolved(&CYLINDER, json!({"shade": true, "lightColor": "#ff8040", "graphics": [{"symbol": "Red"}]})); + let art = revolve_art_in(Some(&d), &n).unwrap(); + // One run holds every face; a face with a part of the bar is a group of the face and that part. + let runs = super::tests::sealed_faces(&art); + assert_eq!(runs.len(), 1); + let carrying: Vec<&Arc> = runs[0].iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).collect(); + assert!(!carrying.is_empty()); + assert!(carrying.iter().all(|f| f.children().is_some_and(|c| c.len() > 1 && parts(&c[0], false).is_empty()))); + // Every part of the bar is drawn in the run, after its face, and none in the underlay. + let in_run: usize = carrying.iter().map(|f| parts(f, false).len()).sum(); + assert!(in_run > 0); + assert_eq!(in_run, parts(&art, false).len()); +} + #[test] fn graphics_past_the_point_limit_are_refused() { let mut d = document(); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index e10771a8d0..06f6951791 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -102,6 +102,21 @@ pub fn has_solid(n: &Node) -> bool { solid(&n.appearance.effects).is_some() || n.appearance.items.iter().any(|i| i.visible() && solid(i.effects()).is_some()) } +/// Does `n` carry a 3D effect that [`three_d_meshes`] builds solids from: a visible Revolve, or +/// else a visible Extrude & Bevel, Inflate or Rotate effect, which on a group or layer must be on +/// the object itself (one on a group's fill or stroke draws nothing to export)? It does not build +/// the solids, so [`three_d_meshes`] can still refuse an object it passes. +pub fn exports_three_d(n: &Node) -> bool { + let container = is_container(n); + if crate::has_revolve(n) { + !container || n.appearance.effects.iter().any(|e| e.visible && crate::is_revolve(&e.id)) + } else if container { + solid(&n.appearance.effects).is_some() + } else { + has_solid(n) + } +} + /// The Position presets: (id, [rotation X, Y, Z]). Front, Back, Left, Right, Top and Bottom face /// the art that way; Off-Axis tilts each 20° down and 25° aside (showing the top and right); /// Isometric lays the art on the left, right, top or bottom plane of an isometric view (the diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 0d867462fc..79d87fdb25 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; -/// The Shading Color choices: black, a custom color, or none. -pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; +/// The Shading Color choices: black, a custom color, none, or black overprinting the paint. +pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"]; /// The surface settings of Extrude & Bevel (Classic)'s parameters. pub fn classic_shading(p: &Value) -> ClassicShading { @@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { } } -/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only -/// the highlight lightens them). +/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces +/// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { match text(p, "shadingColor", "black") { "none" => None, @@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool { /// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower /// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where -/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`, -/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam +/// tone `tone` is below full light and the faces darken (`shade`), black over it as +/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam /// stroke each layer draws around the face. fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option, seam: f64) -> Vec { let Paint::Solid { color, swatch, tint } = paint else { return vec![] }; let keep = (1.0 - spec).clamp(0.0, 1.0) as f32; let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep }; let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]; - if shade.is_some() && tone < 1.0 { - let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); - let mut layer = FillLayer::new(black.clone()); - layer.blend = BlendMode::Multiply; - layer.overprint = true; - let mut edge = crate::lighting::seam_stroke(black, seam); - edge.blend = BlendMode::Multiply; - edge.overprint = true; - items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]); + if shade.is_some() { + items.extend(overprinting_black(tone, seam)); } items } +/// The black that shades a face at tone `tone` on the black plate, when the tone is below full +/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam` +/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a +/// neighbor's, the face is not darkened twice. +fn overprinting_black(tone: f64, seam: f64) -> Vec { + if tone >= 1.0 { + return vec![]; + } + let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); + let mut layer = FillLayer::new(black.clone()); + layer.blend = BlendMode::Multiply; + layer.overprint = true; + let mut edge = crate::lighting::seam_stroke(black, seam); + edge.blend = BlendMode::Darken; + edge.overprint = true; + vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)] +} + +/// Whether the shading color of parameters `p` is Black Overprint. +fn black_overprint(p: &Value) -> bool { + text(p, "shadingColor", "black") == "blackOverprint" +} + +/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full +/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they +/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of +/// the seam stroke each layer draws around the face. +fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + items.extend(overprinting_black(tone, seam)); + items +} + /// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on /// Wireframe, else the seam between faces. pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { @@ -229,15 +256,17 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by -/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] -/// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage; without a placement of its -/// own, it is placed once on all the faces ([`crate::lighting::opaque_surface_paint`]). +/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot +/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops +/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's +/// coverage; without a placement of its own, it is placed once on all the faces +/// ([`crate::lighting::opaque_surface_paint`]). pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); + let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; let paint = &paint; @@ -252,6 +281,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. let seam = super::seam_width(&face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); + } let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 319cdf2949..9c783b26cb 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1908,6 +1908,89 @@ fn classic_shading_color_blend_steps_and_lights() { assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); } +/// The fills, then the strokes, of face `face`. +fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) { + let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect(); + (fills, strokes) +} + +/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in +/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice); +/// `None` when the face has none. +fn overprinted_black(face: &Node) -> Option { + let (fills, strokes) = layers_of(face); + assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke"); + let shadow = fills.get(1)?; + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true)); + assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out"); + Some(k) +} + +/// Black Overprint keeps the paint on every face and draws the shading over it as black, +/// overprinting, as strong as the darkening of the shading color Black; the +/// highlight is not drawn, and No Shading adds no black. +#[test] +fn classic_black_overprint_keeps_the_paint_under_overprinting_black() { + let diffuse = json!({"surface": "diffuse", "ambient": 20}); + let mut over = diffuse.clone(); + over["shadingColor"] = json!("blackOverprint"); + let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect(); + let faces = classic_faces(over); + assert_eq!(faces.len(), darkened.len()); + let mut shaded = 0; + for (face, rgb) in faces.iter().zip(&darkened) { + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept"); + let k = overprinted_black(face).unwrap_or(0.0); + assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}"); + shaded += usize::from(k > 0.0); + } + assert!(shaded > 0, "faces turned from the light get black"); + // Plastic: no white layer for the highlight. + let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + for face in classic_faces(shiny) { + let (fills, _) = layers_of(&face); + assert_eq!(fills[0].paint, Paint::solid(RED)); + assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}"); + } + // No Shading: the paint alone. + for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) { + assert_eq!(overprinted_black(&face), None); + assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED)); + } +} + +/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate +/// (Classic) draws its plane the same way. +#[test] +fn classic_black_overprint_keeps_gradients_and_shades_rotate() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)], + )))); + let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = gradient.clone(); + } + let art = solid_art(&n).unwrap(); + let mut shaded = 0; + for face in faces(&art) { + assert_eq!(layers_of(face).0[0].paint, gradient); + shaded += usize::from(overprinted_black(face).is_some()); + } + assert!(shaded > 0); + // Rotate (Classic), turned from the light: red with black over it; facing it: red alone. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + let face = &turned[0].children().unwrap()[0]; + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED)); + assert!(overprinted_black(face).is_some_and(|k| k > 0.05)); + let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None); +} + #[test] fn classic_bevel_height_extent_and_cap_shape_the_solid() { let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); @@ -2134,9 +2217,12 @@ fn classic_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), + (json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"), + (json!({"shadingColor": true}), "`shadingColor` must be one of"), (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), @@ -2213,11 +2299,12 @@ fn classic_rotate_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), (json!({"surface": 2}), "`surface` must be one of"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index cb990e4857..fcb251347d 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use serde_json::{Map, Value, json}; use vectorcraft_doc::{ExportAsset, NodeId}; -use super::edit::{roots_of, selected_roots}; +use super::edit::{refuse_symbol_part, roots_of, selected_roots}; use super::fileio::{ DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, with_screen_export_preset, write_file, @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Export 3D Object", [], None, - "{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}", + "{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object in ids without such an effect is refused. Without ids, the selected objects without one (on a group or layer, one on its fill or stroke draws nothing and does not count), and a selected object inside another selected object that has one, are left out; refused when none is left → {assets: [asset id…] (in order), added: n}", has_doc, add_3d ), @@ -203,10 +203,36 @@ fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: & Ok(ids) } +/// The selected objects `assets.add3D` collects without `ids`: those with a 3D effect it exports +/// ([`vectorcraft_render::effects::exports_three_d`]; a path of a compound path counts as the +/// compound path), layers included, in tree order, dropping +/// each one inside another of them (that one's asset holds it). Refused while an object of a +/// dynamic symbol instance's art is selected, as [`selected_roots`] is. +fn selected_3d_roots(s: &Session) -> Result> { + refuse_symbol_part(s)?; + let st = s.doc()?; + // A path of a compound path stands for the compound path, which holds the paint and effects. + let found = st + .selection + .objects + .iter() + .map(|id| super::path::compound_or_self(&st.doc, *id)) + .filter(|id| st.doc.node(*id).is_some_and(vectorcraft_render::effects::exports_three_d)); + let mut paths: Vec<(Vec, NodeId)> = st.doc.index_paths(found).into_iter().map(|(id, path)| (path, id)).collect(); + paths.sort_by(|a, b| a.0.cmp(&b.0)); + let mut kept: Vec<(Vec, NodeId)> = Vec::with_capacity(paths.len()); + for (path, id) in paths { + if !kept.last().is_some_and(|(outer, _)| path.starts_with(outer)) { + kept.push((path, id)); + } + } + Ok(kept.into_iter().map(|(_, id)| id).collect()) +} + fn add_3d(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.add3D"; let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?; - let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? }; + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_3d_roots(s)? }; if ids.is_empty() { return Err(bad(C, "select an object with a 3D effect (or give its ids)")); } diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index e98dbd5619..c17d6a4428 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -173,7 +173,7 @@ pub fn specs() -> Vec { "Clipboard Formats", [], None, - "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut", + "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); under read roots, SVG and its markup as text are left out when clipboard.exportSvg would refuse; the app publishes them on Copy and Cut", always, flavours ), @@ -369,13 +369,20 @@ impl Session { /// The MIME types of [`Self::clipboard_flavours`], without making them. pub fn clipboard_flavour_types(&self) -> Vec<&'static str> { - self.clipboard.flavour_types(self.prefs.copy_as_svg, self.prefs.copy_as_pdf) + self.clipboard.flavour_types(self.clipboard_svg_offered(), self.prefs.copy_as_pdf) } /// What Copy offers other apps, best first (see `clipboard.flavours`): [`Clipboard::flavours`] - /// by the Clipboard Handling preferences. + /// by the Clipboard Handling preferences, without the SVG (and the SVG markup as text) that + /// [`Self::clipboard_svg_refused`] withholds from the caller asking now. pub fn clipboard_flavours(&self) -> Vec { - self.clipboard.flavours(self.prefs.copy_as_svg, self.prefs.copy_as_pdf) + self.clipboard.flavours(self.clipboard_svg_offered(), self.prefs.copy_as_pdf) + } + + /// Does Copy offer the SVG: Include SVG Code is on and the SVG is not withheld from the caller + /// asking now. + fn clipboard_svg_offered(&self) -> bool { + self.prefs.copy_as_svg && !self.clipboard_svg_refused() } /// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 5fe3211e2b..78f40a0072 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; any other image whose colors are converted but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index 2d8d0c951f..85fa6ae7e9 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -501,8 +501,13 @@ fn damaged_slices_never_panic() { let mut f = base.clone(); f[at] = v; let mut s = Session::new(); - let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})); - let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})); + // The engine's guard reports a panic as an internal error. + for r in [ + s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)})), + s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)})), + ] { + assert!(!matches!(r, Err(crate::EngineError::Internal { .. })), "byte {at} set to {v}: {r:?}"); + } } } } diff --git a/crates/engine/src/cmd/flatten.rs b/crates/engine/src/cmd/flatten.rs index cc803c59b9..399f2ec4bd 100644 --- a/crates/engine/src/cmd/flatten.rs +++ b/crates/engine/src/cmd/flatten.rs @@ -40,7 +40,7 @@ use vectorcraft_render::effects; use super::edit::roots_of; use super::menucmds::{MAX_PIXELS, isolated_doc, unique_key}; -use super::pathops::{node_path, outline_strokes, outline_strokes_under, separate, shape_node}; +use super::pathops::{leaves, node_path, outline_strokes, separate, shape_node}; use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, targets, unique_name}; mod analysis; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index b159fa7361..b8aebf8324 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -1,9 +1,11 @@ +use std::collections::HashSet; + use super::analysis::{Scratch, finite, flatten_groups, has_effects, masked, outlined_text, overlapping, painted, reach}; use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE}; use super::options::FlattenOptions; use super::{ Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks, - MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po, + MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, leaves, outline_strokes, planes_cmyk, po, separate, shape_node, shapes, unique_key, }; @@ -14,6 +16,8 @@ pub(super) struct Plan { pub(super) flat: Vec, /// Objects without transparency (they stay, but for the outline options). pub(super) kept: Vec, + /// What the outline and overprint options do to each of `kept`, in its order. + pub(super) work: Vec, /// The objects with transparency of their own. pub(super) transparent: Vec, } @@ -112,7 +116,12 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: let reaches: Vec> = plain.iter().zip(&clipped).map(|(n, c)| reach(n).zip(reach(c)).map(|(a, b)| a.intersect(b))).collect(); let see_through: Vec = plain.iter().map(|n| o.shows_transparency(&baked, n) || o.draws_see_through_image(n)).collect(); let cmyk = src.color_mode == ColorMode::Cmyk; - let mut out = Plan { flat: vec![], kept: vec![], transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect() }; + let mut out = Plan { + flat: vec![], + kept: vec![], + work: vec![], + transparent: roots.iter().zip(&see_through).filter(|(_, t)| **t).map(|(id, _)| *id).collect(), + }; // Baking above stopped early when cancelled; each group is a place to stop (a plan changes nothing). vectorcraft_doc::cancel::check()?; let mut queue = groups(src, roots, &plain, &reaches, &see_through, o)?; @@ -193,9 +202,101 @@ pub(super) fn plan(src: &Document, roots: &[NodeId], o: &FlattenOptions, render: }; out.flat.push(Flat { roots: ids, regions, area, raster, lines }); } + out.work = out.kept.iter().map(|id| Kept::of(src, *id, o)).collect(); Ok(out) } +/// What the outline and overprint options do to one object without transparency, found in one +/// walk of it. +pub(super) struct Kept { + pub(super) id: NodeId, + /// Whether the options change it. + pub(super) changes: bool, + /// The type the text option outlines and the stroked paths the stroke option outlines, those + /// that show and are not pieces of a compound path: what the Flattener Preview highlights. + pub(super) shown_text: Vec, + pub(super) shown_strokes: Vec, + /// In paint order: the type the text option outlines and the leaf shapes ([`leaves`]) other + /// than type that the stroke option outlines. + steps: Vec, + /// The objects with overprints, each with the type or leaf shape that holds it (itself + /// included) when a step replaces that. + overprinted: Vec<(NodeId, Option)>, +} + +/// One object [`apply`] outlines. +enum Step { + /// Type; `leaf`: only groups and layers hold it, so its outlines are leaf shapes for the + /// stroke option. + Text { id: NodeId, leaf: bool }, + /// A leaf shape other than type. + Leaf(NodeId), +} + +/// Where [`Kept::visit`] is in the object it walks. +#[derive(Clone, Copy)] +struct At { + /// Neither the node nor what holds it is hidden, and it is not a piece of a compound path. + shown: bool, + /// Only groups and layers hold the node. + leaf: bool, + /// The type or leaf shape holding the node that a step replaces. + holder: Option, +} + +impl Kept { + /// What the options `o` do to `root` of `d`: nothing when `d` doesn't hold it. + fn of(d: &Document, root: NodeId, o: &FlattenOptions) -> Kept { + let mut k = Kept { id: root, changes: false, shown_text: vec![], shown_strokes: vec![], steps: vec![], overprinted: vec![] }; + if let Some(n) = d.node(root) { + k.visit(n, o, At { shown: true, leaf: true, holder: None }); + } + k + } + + /// Note what the options `o` do to `n` and to everything under it. + fn visit(&mut self, n: &Node, o: &FlattenOptions, at: At) { + kept_seen(n); + let shown = at.shown && n.visible; + let mut holder = at.holder; + if matches!(n.kind, NodeKind::Text(_)) { + if o.text_to_outlines { + self.changes = true; + if shown { + self.shown_text.push(n.id); + } + self.steps.push(Step::Text { id: n.id, leaf: at.leaf }); + holder = Some(n.id); + } + } else { + if o.strokes_to_outlines && stroked(n) { + self.changes = true; + if shown { + self.shown_strokes.push(n.id); + } + } + if o.strokes_to_outlines && at.leaf && matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) + { + self.steps.push(Step::Leaf(n.id)); + holder = Some(n.id); + } + } + if !o.preserve_overprints && overprints(n) { + self.changes = true; + self.overprinted.push((n.id, holder)); + } + let Some(children) = n.children() else { return }; + let inside = At { + shown: shown && !matches!(n.kind, NodeKind::Compound { .. }), + leaf: at.leaf && matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }), + holder, + }; + for c in children { + self.visit(c, o, inside); + } + } +} + /// `roots` of `src` (`plain`: as plain art; `reaches`: where each can paint, clipped) in the /// groups that flatten together ([`flatten_groups`]), each in paint order, by their first object. /// Objects that overlap (as [`overlapping`] groups them) stay in one group when one of them is @@ -668,7 +769,7 @@ pub(crate) fn flatten_expanded(doc: &Document, o: &FlattenOptions) -> Result> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Note that [`Kept::of`] looked at `n`. +#[cfg(test)] +fn kept_seen(n: &Node) { + KEPT_SEEN.with(|s| s.borrow_mut().push(n.id)); +} + +#[cfg(not(test))] +fn kept_seen(_: &Node) {} + /// An image of `r` (in a clip group when it is clipped). fn raster_node(d: &mut Document, r: Raster) -> Node { let key = unique_key(d, "flattened"); @@ -858,38 +963,65 @@ fn raster_node(d: &mut Document, r: Raster) -> Node { crate::cmd::rasterfx::clip_group(d, path, FillRule::NonZero, image) } -/// Replace the type under `root` by its outlines: → the id now standing for `root`. -fn outline_texts_under(d: &mut Document, root: NodeId) -> Result { - let mut texts = vec![]; - if let Some(n) = d.node(root) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::Text(_)) { - texts.push(c.clone()); +/// Do what [`Kept`] `k` found to its object of `d` (`brushes`: the document's brushes, for the +/// stroke option): its type outlined, then the strokes of its leaf shapes, the outlines of its +/// type included, then its overprints dropped. → the id now standing for the object. +fn outline_kept(d: &mut Document, brushes: &[vectorcraft_brush::Brush], k: Kept, o: &FlattenOptions) -> Result { + let mut root = k.id; + let mut replaced = HashSet::new(); + let dropping = !o.preserve_overprints; + // Each replacement loses its overprints before it goes in: no new object is looked up. + let mut put = |d: &mut Document, old: NodeId, mut new: Node, root: &mut NodeId| -> Result<()> { + if dropping { + drop_overprints(&mut new); + } + let nid = new.id; + *d.node_mut(old).ok_or(EngineError::NoNode(old))? = new; + replaced.insert(old); + if old == *root { + *root = nid; + } + Ok(()) + }; + // The leaf shapes of each outlined type that only groups and layers hold, by step. + let mut outlined: Vec> = Vec::with_capacity(k.steps.len()); + for step in &k.steps { + let mut lv = vec![]; + if let Step::Text { id, leaf } = *step + && let Some(out) = d.node(id).and_then(outlined_text) + { + let out = d.reid(&out); + if leaf && o.strokes_to_outlines { + leaves(&out, &mut lv); } - }); + put(d, id, out, &mut root)?; + } + outlined.push(lv); } - let mut out = root; - for t in texts { - let Some(o) = outlined_text(&t) else { continue }; - let o = d.reid(&o); - let nid = o.id; - *d.node_mut(t.id).ok_or(EngineError::NoNode(t.id))? = o; - if t.id == root { - out = nid; + if o.strokes_to_outlines { + for (step, lv) in k.steps.iter().zip(outlined) { + let shapes = match *step { + Step::Leaf(id) => d.node(id).cloned().into_iter().collect(), + Step::Text { .. } => lv, + }; + for l in shapes.iter().filter(|l| !matches!(l.kind, NodeKind::Text(_))) { + if let Some(new) = outline_strokes(d, brushes, l) { + put(d, l.id, new, &mut root)?; + } + } } } - Ok(out) -} - -/// Whether the outline and overprint options change `n`, an object without transparency. -pub(super) fn kept_work(n: &Node, o: &FlattenOptions) -> bool { - let mut any = false; - n.walk(&mut |c| { - any |= (o.text_to_outlines && matches!(c.kind, NodeKind::Text(_))) - || (o.strokes_to_outlines && stroked(c)) - || (!o.preserve_overprints && overprints(c)); - }); - any + if dropping { + for (id, holder) in k.overprinted { + if holder.is_some_and(|h| replaced.contains(&h)) { + continue; + } + if let Some(n) = d.node_mut(id) { + drop_own_overprints(n); + } + } + } + Ok(root) } /// Whether `n` is a path with a visible stroke (outlining turns it into a fill). @@ -898,12 +1030,8 @@ pub(super) fn stroked(n: &Node) -> bool { && n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() && s.width > 0.0)) } -fn overprints(n: &Node) -> bool { - n.appearance.items.iter().any(AppearanceItem::overprint) - || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) -} - -fn drop_overprints(n: &mut Node) { +/// Drop the overprints of `n` itself. +fn drop_own_overprints(n: &mut Node) { if overprints(n) { for i in &mut n.appearance.items { *i.overprint_mut() = false; @@ -914,6 +1042,16 @@ fn drop_overprints(n: &mut Node) { } } } +} + +fn overprints(n: &Node) -> bool { + n.appearance.items.iter().any(AppearanceItem::overprint) + || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke)) +} + +/// Drop the overprints of `n` and of everything under it. +fn drop_overprints(n: &mut Node) { + drop_own_overprints(n); if let Some(ch) = n.children_mut() { for c in ch { drop_overprints(Arc::make_mut(c)); @@ -994,6 +1132,208 @@ mod tests { assert_eq!(run(&[deep, deep]).0, vec![(sub, g2), (sub, g2)]); } + /// The objects [`kept_session`] makes. + struct KeptArt { + /// Each group with its stroked rectangle (its fill overprints) and its stroked type. + groups: Vec<(NodeId, NodeId, NodeId)>, + /// A stroked rectangle and stroked type with an overprint, on their own. + rect: NodeId, + text: NodeId, + /// A stroked compound path and its pieces. + compound: NodeId, + pieces: Vec, + /// A group holding an unstroked rectangle and a hidden stroked rectangle. + hidden_group: NodeId, + hidden: NodeId, + /// An unstroked rectangle. + plain: NodeId, + } + + /// A document without transparency: `n` groups, then the other objects of [`KeptArt`]. + fn kept_session(n: usize) -> (Session, KeptArt) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap()); + let rect = |s: &mut Session, x: f64| id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + let text = |s: &mut Session, x: f64| { + let t = id(s.execute("text.create", &json!({"x": x, "y": 80, "text": "Hi", "size": 24})).unwrap()); + s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [t.0]})).unwrap(); + t + }; + let select = |s: &mut Session, ids: &[NodeId]| { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + }; + let overprint = |s: &mut Session, on: NodeId| { + s.execute("attributes.set", &json!({"ids": [on.0], "overprintFill": true})).unwrap(); + }; + let unstroked = |s: &mut Session, on: NodeId| { + s.execute("paint.setStroke", &json!({"none": true, "ids": [on.0]})).unwrap(); + }; + let mut groups = vec![]; + for i in 0..n { + let x = (i % 10) as f64 * 30.0; + let (r, t) = (rect(&mut s, x), text(&mut s, x)); + overprint(&mut s, r); + select(&mut s, &[r, t]); + groups.push((id(s.execute("object.group", &json!({})).unwrap()), r, t)); + } + let (r, t) = (rect(&mut s, 0.0), text(&mut s, 100.0)); + overprint(&mut s, t); + let (a, b) = (rect(&mut s, 200.0), rect(&mut s, 210.0)); + select(&mut s, &[a, b]); + let compound = id(s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("paint.setStroke", &json!({"color": "#000000", "ids": [compound.0]})).unwrap(); + let pieces = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + let (shown, hidden) = (rect(&mut s, 300.0), rect(&mut s, 310.0)); + unstroked(&mut s, shown); + select(&mut s, &[shown, hidden]); + let hidden_group = id(s.execute("object.group", &json!({})).unwrap()); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + let plain = rect(&mut s, 350.0); + unstroked(&mut s, plain); + (s, KeptArt { groups, rect: r, text: t, compound, pieces, hidden_group, hidden, plain }) + } + + /// Every option on: type and strokes outlined, overprints dropped. + fn outlining() -> FlattenOptions { + FlattenOptions { text_to_outlines: true, strokes_to_outlines: true, preserve_overprints: false, ..FlattenOptions::default() } + } + + /// The top-level objects of `d`'s first layer, in paint order. + fn top_level(d: &Document) -> Vec { + d.layers[0].children().unwrap().iter().map(|c| c.id).collect() + } + + fn sorted(mut ids: Vec) -> Vec { + ids.sort(); + ids + } + + /// The nodes [`Kept::of`] looked at while `f` ran, sorted. + fn kept_seen_by(f: impl FnOnce()) -> Vec { + KEPT_SEEN.with(|v| v.borrow_mut().clear()); + f(); + sorted(KEPT_SEEN.with(|v| v.take())) + } + + /// The Flattener Preview, `object.flattenTransparency` and flattening a whole document each look + /// at every node of the objects without transparency once, with type and strokes outlined and + /// overprints dropped, an object they leave as it is included. + #[test] + fn kept_objects_are_looked_at_once() { + let (mut s, _) = kept_session(100); + let o = outlining(); + let doc = s.doc().unwrap().doc.clone(); + let roots = top_level(&doc); + let mut nodes = vec![]; + for r in &roots { + doc.node(*r).unwrap().walk(&mut |c| nodes.push(c.id)); + } + nodes.sort(); + assert_eq!(nodes.len(), 309); + let preview = kept_seen_by(|| drop(super::super::report::report(&doc, &roots, &o).unwrap())); + assert!(preview == nodes, "the preview looked at {} nodes of {}", preview.len(), nodes.len()); + let whole = kept_seen_by(|| drop(flatten_document(&doc, &o).unwrap().unwrap())); + assert!(whole == nodes, "flattening the document looked at {} nodes of {}", whole.len(), nodes.len()); + let ids: Vec = roots.iter().map(|r| r.0).collect(); + let command = kept_seen_by(|| { + s.execute( + "object.flattenTransparency", + &json!({"ids": ids, "textToOutlines": true, "strokesToOutlines": true, "preserveOverprints": false}), + ) + .unwrap(); + }); + assert!(command == nodes, "object.flattenTransparency looked at {} nodes of {}", command.len(), nodes.len()); + } + + /// [`apply`]'s outlining of `kept` (objects of `d` without transparency) with `o`, done as a + /// walk of each object for each option: → the ids standing for them, in paint order. + fn outlined_walk_by_walk(d: &mut Document, kept: &[NodeId], o: &FlattenOptions) -> Vec { + let brushes = if o.strokes_to_outlines { vectorcraft_brush::library(d) } else { vec![] }; + let mut ids = vec![]; + for &root in kept { + let mut id = root; + if o.text_to_outlines { + let mut texts = vec![]; + d.node(id).unwrap().walk(&mut |c| { + if matches!(c.kind, NodeKind::Text(_)) { + texts.push(c.clone()); + } + }); + for t in texts { + let Some(out) = outlined_text(&t) else { continue }; + let out = d.reid(&out); + if t.id == root { + id = out.id; + } + *d.node_mut(t.id).unwrap() = out; + } + } + if o.strokes_to_outlines { + id = crate::cmd::pathops::outline_strokes_under(d, &brushes, id).unwrap().0; + } + if !o.preserve_overprints { + drop_overprints(d.node_mut(id).unwrap()); + } + ids.push(id); + } + ids.sort_by_key(|id| d.index_path(*id)); + ids + } + + /// With each mix of the text, stroke and overprint options, the objects without transparency + /// end as a walk of each of them for each option leaves them: the same art, ids and selection. + #[test] + fn kept_objects_change_as_a_walk_per_option_changes_them() { + let (s, _) = kept_session(3); + let doc = Document::clone(&s.doc().unwrap().doc); + let roots = top_level(&doc); + for bits in 0..8u8 { + let o = FlattenOptions { + text_to_outlines: bits & 1 != 0, + strokes_to_outlines: bits & 2 != 0, + preserve_overprints: bits & 4 != 0, + ..FlattenOptions::default() + }; + let p = plan(&doc, &roots, &o, true).unwrap(); + assert!(p.flat.is_empty(), "{o:?}"); + // In the order the plan's groups come in. + let kept = p.kept.clone(); + assert_eq!(sorted(kept.clone()), sorted(roots.clone()), "{o:?}"); + let mut once = doc.clone(); + let mut sel = vectorcraft_doc::Selection::default(); + let (ids, ..) = apply(&mut once, &mut sel, p, &o).unwrap(); + let mut walked = doc.clone(); + let want = outlined_walk_by_walk(&mut walked, &kept, &o); + assert_eq!(ids, want, "{o:?}"); + assert!(once == walked, "{o:?}"); + assert_eq!(once == doc, bits == 4, "{o:?}: only with every option off does nothing change"); + } + } + + /// The Flattener Preview lists the kept objects the options change, and of those the type and + /// the stroked paths that show and are not pieces of a compound path. + #[test] + fn the_preview_lists_what_the_options_change_in_kept_objects() { + let (s, a) = kept_session(2); + let doc = &s.doc().unwrap().doc; + let roots = top_level(doc); + let r = super::super::report::report(doc, &roots, &outlining()).unwrap(); + let (g, rects, texts): (Vec<_>, Vec<_>, Vec<_>) = + (a.groups.iter().map(|g| g.0).collect(), a.groups.iter().map(|g| g.1).collect(), a.groups.iter().map(|g| g.2).collect()); + assert_eq!(r.affected, [g.clone(), vec![a.rect, a.text, a.compound, a.hidden_group]].concat()); + // Both lists come in the order the plan's groups do. + assert_eq!(sorted(r.text.clone()), sorted([texts, vec![a.text]].concat())); + assert_eq!(sorted(r.strokes.clone()), sorted([rects, vec![a.rect, a.compound]].concat())); + assert!(!r.strokes.contains(&a.hidden) && !r.strokes.iter().any(|id| a.pieces.contains(id)) && !r.affected.contains(&a.plain)); + // Dropping overprints alone changes the objects that overprint. + let o = FlattenOptions { preserve_overprints: false, ..FlattenOptions::default() }; + let r = super::super::report::report(doc, &roots, &o).unwrap(); + assert_eq!((r.affected, r.text, r.strokes), ([g, vec![a.text]].concat(), vec![], vec![])); + // With every option off, nothing. + assert!(super::super::report::report(doc, &roots, &FlattenOptions::default()).unwrap().affected.is_empty()); + } + /// In a file without transparency with Clip Complex Regions on, art under a group's opaque /// image within one of its pixels joins the group, also where a long image is made at a lower /// resolution and its pixels are wider than at the preset's. diff --git a/crates/engine/src/cmd/flatten/options.rs b/crates/engine/src/cmd/flatten/options.rs index 16cf8e5de7..2d558ea2e2 100644 --- a/crates/engine/src/cmd/flatten/options.rs +++ b/crates/engine/src/cmd/flatten/options.rs @@ -1,5 +1,5 @@ use super::analysis::draws_image; -use super::apply::{apply, kept_work, plan}; +use super::apply::{apply, plan}; use super::presets::{FlattenerPreset, saved_preset}; use super::report::target_roots; use super::{BTreeSet, Deserialize, Document, EngineError, Node, NodeKind, Paint, Result, Serialize, Session, Value, bad, json, str_param}; @@ -194,7 +194,7 @@ pub(super) fn flatten(s: &mut Session, p: &Value) -> Result { let plan = plan(&src, &roots, &o, true)?; let warning = crate::cmd::rasterfx::undecoded_warning(failed); let options = serde_json::to_value(&o).unwrap_or_default(); - if plan.flat.is_empty() && !plan.kept.iter().any(|id| src.node(*id).is_some_and(|n| kept_work(n, &o))) { + if plan.flat.is_empty() && !plan.work.iter().any(|k| k.changes) { return Ok(json!({ "ids": roots.iter().map(|i| i.0).collect::>(), "rasterized": 0, "vector": 0, "options": options })); } let (ids, vector, rasterized) = s.edit("Flatten Transparency", |d, sel| { diff --git a/crates/engine/src/cmd/flatten/report.rs b/crates/engine/src/cmd/flatten/report.rs index 41b08b7a05..650309d424 100644 --- a/crates/engine/src/cmd/flatten/report.rs +++ b/crates/engine/src/cmd/flatten/report.rs @@ -1,4 +1,4 @@ -use super::apply::{kept_work, opaque, plan, stroked}; +use super::apply::{opaque, plan, stroked}; use super::options::FlattenOptions; use super::{ Appearance, Color, Deserialize, Document, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Serialize, Session, Value, bad, isolated_doc, @@ -263,15 +263,10 @@ pub fn report(doc: &Document, roots: &[NodeId], o: &FlattenOptions) -> Result Plot<'a> { series_marks(self.g, i, series_fill, stroke, width) } + /// The stroke paint and width series `s`'s filled marks and its legend swatch get when the series keeps no stroke + /// of its own: a white line between stacked segments, area bands and pie wedges, none on other marks. + fn mark_stroke(&self, s: usize) -> (Paint, f64) { + match self.kind(s) { + GraphKind::StackedColumn | GraphKind::StackedBar | GraphKind::Area => (Paint::solid(Color::WHITE), 0.25), + GraphKind::Pie => (Paint::solid(Color::WHITE), 0.5), + _ => (Paint::None, 0.0), + } + } + fn series_label(&self, i: usize) -> String { self.g.series.get(i).cloned().unwrap_or_default() } @@ -471,7 +481,8 @@ impl<'a> Plot<'a> { } let sweep = v / total * std::f64::consts::TAU; let bp = wedge_path(ring, a0, sweep); - let (fill, stroke, sw) = self.mark(s, true, Paint::solid(Color::WHITE), 0.5); + let (stroke, width) = self.mark_stroke(s); + let (fill, stroke, sw) = self.mark(s, true, stroke, width); let dark = is_dark(&fill); let n = self.b.path(PathData::from_bezpath(&bp), fill, stroke, sw); self.push_shadowed(s, n); @@ -887,7 +898,8 @@ impl<'a> Plot<'a> { let Some(base) = (if v >= 0.0 { pos.get_mut(ax) } else { neg.get_mut(ax) }) else { continue }; let (v0, v1) = (geo.vpos(ax, *base), geo.vpos(ax, *base + v)); *base += v; - let paint = self.mark(s, true, Paint::solid(Color::WHITE), 0.25); + let (stroke, width) = self.mark_stroke(s); + let paint = self.mark(s, true, stroke, width); let rect = bar_rect(geo.horizontal, a, w, v0, v1); // A segment of 0 has no area to shade. let n = self.bar_node(Bar { s, rect, value: v, down: v1 < v0, per_unit: geo.per_unit(ax) }, paint, v != 0.0); @@ -907,7 +919,8 @@ impl<'a> Plot<'a> { let at = |c: usize, v: &[f64]| Point::new(geo.cat_mid(c), geo.vpos(a, v.get(c).copied().unwrap_or(0.0))); let mut pts: Vec = (0..ncat).map(|c| at(c, &above)).collect(); pts.extend((0..ncat).rev().map(|c| at(c, below))); - let (fill, stroke, w) = self.mark(s, true, Paint::solid(Color::WHITE), 0.25); + let (stroke, width) = self.mark_stroke(s); + let (fill, stroke, w) = self.mark(s, true, stroke, width); let n = self.b.path(polyline(&pts, true), fill, stroke, w); self.push_series(s, n); *below = above; @@ -951,10 +964,11 @@ impl<'a> Plot<'a> { } /// The swatch of series `s` at `(x, y)`: series drawn with markers show their marker design in the legend, and - /// series drawn with a column design that design. + /// series drawn with a column design that design. A default swatch has the stroke of its series' marks. fn legend_swatch(&mut self, s: usize, (x, y): (f64, f64)) { let marked = matches!(self.g.kind, GraphKind::Scatter | GraphKind::Radar) || self.kind(s) == GraphKind::Line; - let paint = self.mark(s, true, Paint::None, 0.0); + let (stroke, width) = self.mark_stroke(s); + let paint = self.mark(s, true, stroke, width); let column = nth(self.column_looks, s).filter(|_| self.columnar(s)); let swatch = self.b.swatch(column, nth(&self.designs, s).filter(|_| marked), Rect::new(x, y, x + 8.0, y + 8.0), paint); self.push_series(s, swatch); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index d171224d14..3b18820f4b 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -8449,7 +8449,102 @@ fn a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns() { } } } - assert!(live.contains(&"column v7.ai".to_string()) && live.contains(&"column pdf.ai".to_string()), "{live:?}"); + for ty in ["column", "stackedColumn", "area"] { + assert!(live.contains(&format!("{ty} v7.ai")) && live.contains(&format!("{ty} pdf.ai")), "{ty}: {live:?}"); + } +} + +/// A default legend swatch has the stroke paint and weight of its series' marks, beside the plot or across the top: the +/// thin white line of stacked columns and bars, areas and pie wedges, and none on columns and bars. A stroke color kept +/// on the series, with or without a weight of its own, is on the swatch too. +#[test] +fn a_legend_swatch_has_the_stroke_of_its_series_marks() { + let white = |w: f64| (Paint::solid(vectorcraft_color::Color::WHITE), w); + let cases = [ + ("stackedColumn", white(0.25)), + ("stackedBar", white(0.25)), + ("area", white(0.25)), + ("pie", white(0.5)), + ("column", (Paint::None, 0.0)), + ("bar", (Paint::None, 0.0)), + ]; + for (ty, stroke) in cases { + for across_top in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = NodeId( + s.execute("graph.create", &json!({"type": ty, "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("graph.setType", &json!({"id": id.0, "legendAcrossTop": across_top})).unwrap(); + for i in 0..2 { + let marks = marks_of(&s, id, i); + assert!(marks.len() > 1, "{ty} {i}: marks and a swatch"); + assert!(marks.iter().all(|m| (m.1.clone(), m.2) == stroke), "{ty} across top {across_top}, series {i}: {marks:?}"); + } + // A stroke color kept on series 0 without a weight keeps the default weight, then with one. + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone(); + let row = bar.appearance.items.iter().rposition(|it| !it.is_fill()); + let Some(row) = row else { continue }; + s.execute("appearance.setItem", &json!({"ids": [bar.id.0], "index": row, "color": "#ff0000"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let marks = marks_of(&s, id, 0); + assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].1 != stroke.0, "{ty} across top {across_top}, red: {marks:?}"); + let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.execute("appearance.setItem", &json!({"ids": [bar.0], "index": row, "weight": 3})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let marks = marks_of(&s, id, 0); + assert!(marks.iter().all(|m| *m == marks[0]) && marks[0].2 == 3.0, "{ty} across top {across_top}, 3 pt: {marks:?}"); + } + } +} + +/// A stacked column graph the graph tools draw, saved as `.ai` in either form, opens again as the same graph without a +/// warning, and its data can be edited there. +#[test] +fn a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data() { + let dir = vectorcraft_testkit::temp_dir("graph-ai-stacked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,1,6"; + let id = s.execute("graph.create", &json!({"type": "stackedColumn", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + let written = spec(&s, NodeId(id)); + for (name, version) in [("v7.ai", Some("7")), ("pdf.ai", None)] { + let path = dir.join(name); + let mut p = json!({"path": path, "format": "ai"}); + if let Some(v) = version { + p["aiVersion"] = json!(v); + } + let r = s.execute("file.saveAs", &p).unwrap(); + let notes = r["warnings"].as_array().cloned().unwrap_or_default(); + assert!(!notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); + let mut again = Session::new(); + again.execute("document.open", &json!({"path": path})).unwrap(); + let mut found = vec![]; + again.doc().unwrap().doc.walk(|n| { + if n.extras().graph.is_some() { + found.push(n.id); + } + }); + assert_eq!(found.len(), 1, "{name}"); + let g = spec(&again, found[0]); + assert_eq!((g.kind, g.cells()), (written.kind, written.cells()), "{name}"); + assert_eq!((g.series.as_slice(), g.categories.as_slice()), (&written.series[..], &written.categories[..]), "{name}"); + again.execute("select.set", &json!({"ids": [found[0].0]})).unwrap(); + again.execute("graph.setData", &json!({"id": found[0].0, "csv": ",2024,2025\nQ1,8,1\nQ2,2,7"})).unwrap(); + let after = spec(&again, found[0]); + assert_eq!((after.kind, after.rows.as_slice()), (written.kind, &[vec![8.0, 1.0], vec![2.0, 7.0]][..]), "{name}"); + // Each series keeps one fill and the thin white stroke on its marks and its swatch. + for i in 0..2 { + let marks = marks_of(&again, found[0], i); + let white = Paint::solid(vectorcraft_color::Color::WHITE); + assert!(marks.len() > 1 && marks.iter().all(|m| *m == marks[0] && (&m.1, m.2) == (&white, 0.25)), "{name} series {i}: {marks:?}"); + } + } } /// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 7062407c79..a155245fbc 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Character / Paragraph", [], None, - "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away, down the column for an upright character in vertical type), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options, as text.setRangeStyle: the mark glyphs among the characters move right or up relative to their letters), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, as text.setRangeStyle), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options, as text.setRangeStyle: the characters drawn in one OpenType form of the font, or its default glyphs; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -522,6 +522,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "romanHangingPunctuation", "koreanLineBreakAnywhere", "bunriKinshi", + "kurikaeshiMojiShori", ], C, )?; @@ -597,6 +598,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "kinsoku", "kinsokuType", "bunriKinshi", + "kurikaeshiMojiShori", "direction", "leadingModel", "charAlign", @@ -995,6 +997,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = flag("bunriKinshi") { para.bunri_kinshi = v; } + // An omitted or null value keeps the paragraph's own. + para.kurikaeshi_moji_shori = flag("kurikaeshiMojiShori").unwrap_or(para.kurikaeshi_moji_shori); if let Some(v) = direction { para.direction = v; } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index b5267fa990..5b7f22abd9 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -318,7 +318,7 @@ pub(crate) fn style_of(n: &Node) -> Style { /// Leaf shapes (paths, compound paths, text) of a subtree in paint order; guides and clipping /// paths are skipped. -fn leaves(n: &Node, out: &mut Vec) { +pub(crate) fn leaves(n: &Node, out: &mut Vec) { each_leaf(n, &mut |l| out.push(l.clone())); } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 4f3b814760..9079f7b892 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1830,6 +1830,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { para: super::create::new_type_para(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), @@ -2136,6 +2137,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { para: Default::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index efcc078e65..3e8a7e163b 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -255,6 +255,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), + ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ad41d1d220..f4f807cb15 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); - for (id, part) in live.iter().zip(parts) { + let texts: Vec = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect(); + let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::>()); + for ((id, part), lead) in live.iter().zip(parts).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { let mut next = (**t).clone(); next.runs = part.runs; @@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { || part.list_count != t.list_count || part.list_level_counts != t.list_level_counts || continues != t.first_para_continues + || lead != t.first_para_lead { t.runs = next.runs; t.para = next.para; @@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.list_count = part.list_count; t.list_level_counts = part.list_level_counts; t.first_para_continues = continues; + t.first_para_lead = lead; refresh_bounds(t); } } @@ -384,17 +388,42 @@ pub(crate) fn mark_continued(doc: &mut Document) { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect(); let marks = vectorcraft_text::thread::continued(&frames); - for (id, on) in live.iter().zip(marks) { + let texts: Vec = frames.iter().map(|t| t.plain_text()).collect(); + let leads = first_para_leads(&texts, &marks); + for ((id, on), lead) in live.iter().zip(marks).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) - && t.first_para_continues != on + && (t.first_para_continues != on || t.first_para_lead != lead) { t.first_para_continues = on; + t.first_para_lead = lead; refresh_bounds(t); } } } } +/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and +/// whether each one's first paragraph `continues` from the frame before: the last character of +/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over +/// the frames: each frame's lead is carried forward to the next. +fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { + // The lead the next frame takes when its first paragraph continues from this one. + let mut carry = None; + texts + .iter() + .enumerate() + .map(|(k, text)| { + #[cfg(test)] + LEAD_SCANS.with(|c| c.set(c.get() + 1)); + let lead = carry.filter(|_| continues.get(k) == Some(&true)); + let tail = text.rsplit('\n').next().unwrap_or(text); + // A paragraph break in this frame ends the paragraph the lead came from. + carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len())); + lead + }) + .collect() +} + #[cfg(test)] thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's @@ -402,6 +431,8 @@ thread_local! { static THREAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`story_in`] went through a thread's frames on this thread. static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many frame texts [`first_para_leads`] went through on this thread. + static LEAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -417,6 +448,12 @@ pub(crate) fn story_builds() -> usize { STORY_BUILDS.with(std::cell::Cell::get) } +/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread. +#[cfg(test)] +pub(crate) fn lead_scans() -> usize { + LEAD_SCANS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2694a61e6c..82ac2f9f76 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2226,3 +2226,57 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); } + +/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of +/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that +/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph +/// carries none. Flowing the story and opening a file both set it. +#[test] +fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { + let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::>(), continues); + assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]); + assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]); + assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]); + assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]); + assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]); + assert_eq!(leads(&[], &[]), Vec::>::new()); + // Opening a file marks the frames as they were saved. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (x, text) in [(10, "日時"), (200, "々す")] { + let id = + s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + ids.push(NodeId(id)); + } + let mut d = (*s.doc().unwrap().doc).clone(); + d.text_threads = vec![ids.clone()]; + mark_continued(&mut d); + let tb = text_of(&d, ids[1]).unwrap(); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, Some('時')); + // Flowing the story through the frames sets it from the text each frame now holds. + reflow(&d.clone(), &mut d); + let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap()); + assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す"); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); +} + +/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one +/// pass over the frames, each frame's text gone through once, not once for every frame after it. +#[test] +fn continued_frame_leads_go_through_each_frame_once() { + let n = 2000; + let mut texts = vec!["時".to_string()]; + texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1)); + let continues: Vec = (0..n).map(|k| k > 0).collect(); + let before = lead_scans(); + let leads = first_para_leads(&texts, &continues); + assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before); + assert_eq!(leads.first(), Some(&None)); + assert!(leads.iter().skip(1).all(|l| *l == Some('時'))); + // A paragraph break stops the carry, and a frame that starts a paragraph carries nothing. + let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]); + assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]); +} diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 9339e1d8c4..aa6b75032d 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); } +/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before +/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one +/// undo step, records nothing when the paragraphs already have the value, refuses a value that is +/// not true or false, and paragraph styles carry it. The text keeps its repeat marks. +#[test] +fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.kurikaeshi_moji_shori, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "時々\n".len(); + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks"); + // The same value again records nothing. + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["kurikaeshi_moji_shori"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.kurikaeshi_moji_shori); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).kurikaeshi_moji_shori); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err()); + assert!( + text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, + "a refused call changes nothing" + ); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap(); + assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index cdef5b1dfc..2d1fbd7761 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -89,6 +89,45 @@ fn export_3d_object_refuses_objects_without_a_3d_effect_and_bad_formats() { assert_eq!(r["added"], 1); } +/// Without `ids`, the selected objects without a 3D effect, a group whose 3D effect is on its fill +/// (it draws nothing to export) and a 3D object inside another selected one are left out; a +/// selection with none left is refused. +#[test] +fn export_3d_object_leaves_flat_objects_in_the_selection_out() { + let mut s = session(); + let plain = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 100.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + let filled = run(&mut s, "shape.rectangle", json!({"x": 10.0, "y": 200.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [filled]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [group]})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"})); + // `effect.apply` puts a group's 3D effect on the group itself; a file can hold one on its fill. + s.edit("fill", |d, _| { + let n = d.node_mut(vectorcraft_doc::NodeId(group)).unwrap(); + let fx = n.appearance.effects.remove(0); + n.appearance.items[0].effects_mut().push(fx); + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [plain, group]})); + let before = undo_len(&s); + assert!(s.execute("assets.add3D", &json!({})).is_err(), "no object with a 3D effect to export"); + assert_eq!(undo_len(&s), before); + let inner = extruded(&mut s, 100.0, "Inner"); + let other = run(&mut s, "shape.rectangle", json!({"x": 200.0, "y": 10.0, "width": 40.0, "height": 30.0}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [inner, other]})); + let outer = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [outer]})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude"})); + run(&mut s, "select.set", json!({"ids": [plain, group, inner, outer]})); + let r = run(&mut s, "assets.add3D", json!({})); + assert_eq!(r["added"], 1, "{r}"); + let nodes: Vec = run(&mut s, "assets.list", json!({}))["assets"].as_array().unwrap().iter().map(|a| a["nodes"].clone()).collect(); + assert_eq!(nodes, [json!([outer])]); + assert!(s.execute("assets.add3D", &json!({"ids": [plain, outer]})).is_err(), "ids are still refused"); +} + #[test] fn the_format_is_set_per_asset_and_only_a_change_is_an_undo_step() { let mut s = session(); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 931c011d40..6ae474cc8b 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2117,6 +2117,35 @@ fn confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots() { assert!(svg.contains(&format!("xlink:href=\"{photo}\"")), "{svg}"); } +/// `clipboard.flavours` and the session's flavors leave out the SVG, and its markup as text, that +/// `clipboard.exportSvg` withholds from a confined caller; the PNG is still listed. The SVG is listed +/// while its image's pixels are held, and for a caller with no read roots. +#[test] +fn confined_clipboard_flavours_leave_out_a_withheld_svg() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("clip-flavours-away"); + let home = Folder::new("clip-flavours-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let a = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let (text, svg, png) = ("text/plain", "image/svg+xml", "image/png"); + let listed = |s: &mut Session| confine(roots.as_ref(), || s.execute("clipboard.flavours", &json!({}))).unwrap()["flavours"].clone(); + assert_eq!(listed(&mut s), json!([text, svg, png])); + + without_pixels(&mut s, a); + s.execute("edit.copy", &json!({})).unwrap(); + assert_eq!(listed(&mut s), json!([png])); + let made = confine(roots.as_ref(), || s.clipboard_flavours()); + assert!(made.iter().all(|f| f.mime != svg && f.mime != text), "{:?}", made.iter().map(|f| f.mime).collect::>()); + assert_eq!(confine(roots.as_ref(), || s.clipboard_flavour_types()), [png]); + assert_eq!(s.execute("clipboard.flavours", &json!({})).unwrap()["flavours"], json!([text, svg, png])); +} + /// A confined caller's SVG with Preserve Editing Capabilities is refused while the stored brush /// library holds an entry that does not read as a brush, or is not a list: the native document /// carries it as it is, and its links cannot be checked. Without Preserve Editing the SVG is written. diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 15fbb721e2..3f18ddf644 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap(); assert!(fill(&s, g) && fill(&s, spot)); } + +/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per +/// pixel (0 full ink, 255 none). +fn plate(doc: &Document, plate: &str) -> Vec { + let mut r = Renderer::new(); + r.threads = 0; + let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; + let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts); + (0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect() +} + +/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows +/// it as the cyan darkened, and writes it to PDF as overprinting fills. +#[test] +fn classic_3d_black_overprint_shades_on_the_black_plate() { + let doc = |params: Value| { + let mut s = session(); + rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0); + s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap(); + s + }; + let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"})); + let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"})); + let black = doc(json!({"surface": "diffuse", "depth": 20})); + let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); + let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); + assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); + assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. + let image = |d: &Document| { + let mut r = Renderer::new(); + r.threads = 0; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let (shaded, unshaded) = (image(over_doc), image(flat_doc)); + let mut darker = 0; + for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) { + let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y)); + // Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it. + if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 { + darker += 1; + assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}"); + } + } + assert!(darker > 100, "the faces turned from the light are darker"); + + let pdf_overprints = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count() + }; + let (mut over, mut black) = (over, black); + assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting"); + assert_eq!(pdf_overprints(&mut black), 0); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 8de519fa4e..5614aef56a 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -1,5 +1,5 @@ //! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF, DXF and HP-GL input, -//! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset +//! mutated raster images (Photoshop documents and JPEG XL images among them) placed with File → Place, Photoshop documents' slices (damaged or cut short) opened and placed, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`), flattener preset //! (`.vcflattener`) and export preset (`.vcexportpresets`) libraries, shortcut sets and action sets other apps save as text (`.kys`, `.aia`), and native files (compressed, damaged, saved for older versions), //! must load as an error or as a document that then renders and exports, without a panic; nor may //! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records @@ -1939,6 +1939,271 @@ proptest! { } } +// ---------- PSD slices ---------- + +/// A Unicode string as a PSD file stores it: a count of UTF-16 units, then the units. +fn psd_unicode(s: &str) -> Vec { + let units: Vec = s.encode_utf16().collect(); + let mut b = (units.len() as u32).to_be_bytes().to_vec(); + b.extend(units.iter().flat_map(|u| u.to_be_bytes())); + b +} + +/// A descriptor key or class ID: length 0 and its four characters, or its length and its characters. +fn psd_key(k: &str) -> Vec { + let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec(); + b.extend(k.as_bytes()); + b +} + +/// A descriptor's class (an empty name and the ID `null`), then the count of its items. +fn psd_class(count: usize) -> Vec { + let mut b = psd_unicode(""); + b.extend(psd_key("null")); + b.extend((count as u32).to_be_bytes()); + b +} + +/// A descriptor of `items`, each a key and a typed value. +fn psd_descriptor(items: &[(&str, Vec)]) -> Vec { + let mut b = psd_class(items.len()); + for (k, v) in items { + b.extend(psd_key(k)); + b.extend(v); + } + b +} + +/// A typed descriptor value: its four-character type, then `body`. +fn psd_value(kind: &[u8; 4], body: &[u8]) -> Vec { + [kind.as_slice(), body].concat() +} + +fn psd_long(v: i32) -> Vec { + psd_value(b"long", &v.to_be_bytes()) +} + +fn psd_text(t: &str) -> Vec { + psd_value(b"TEXT", &psd_unicode(t)) +} + +fn psd_enum(kind: &str, v: &str) -> Vec { + psd_value(b"enum", &[psd_key(kind), psd_key(v)].concat()) +} + +/// A bounds object: left, top, right and bottom (px), stored top, left, bottom, right. +fn psd_bounds([l, t, r, b]: [i32; 4]) -> Vec { + psd_value(b"Objc", &psd_descriptor(&[("Top ", psd_long(t)), ("Left", psd_long(l)), ("Btom", psd_long(b)), ("Rght", psd_long(r))])) +} + +/// The slices of the samples: origin (0: generated automatically, 1: follows a layer, 2: made by +/// the user), name, and left, top, right and bottom on the 12 × 10 px canvas. Two come in; the +/// automatic one between them is left out. +const PSD_SLICES: [(u32, &str, [i32; 4]); 3] = [(2, "a", [1, 2, 5, 6]), (0, "auto", [0, 0, 12, 1]), (1, "b", [6, 3, 11, 9])]; + +/// The data of an image resource 1050 holding [`PSD_SLICES`]. +struct SliceSample { + version: u32, + data: Vec, + /// Where the slice count starts in `data`. + count_at: usize, +} + +/// Version 6: the bounds of all the slices, the group's name, the count and one record per slice. +/// The first record is followed by a Photoshop 7 descriptor (version 16) with a nested object, which +/// the reader reads past to the second record. +fn psd_slices_v6() -> SliceSample { + let mut b = 6u32.to_be_bytes().to_vec(); + b.extend([0i32, 0, 10, 12].iter().flat_map(|v| v.to_be_bytes())); + b.extend(psd_unicode("group")); + let count_at = b.len(); + b.extend((PSD_SLICES.len() as u32).to_be_bytes()); + for (i, (origin, name, rect)) in PSD_SLICES.iter().enumerate() { + // The ID, the group ID and the origin; a slice that follows a layer gives the layer's ID. + b.extend((i as u32 + 1).to_be_bytes()); + b.extend(0u32.to_be_bytes()); + b.extend(origin.to_be_bytes()); + if *origin == 1 { + b.extend(4u32.to_be_bytes()); + } + b.extend(psd_unicode(name)); + // An Image slice: its rectangle, link, target, message, alternative text, plain cell text, + // alignment and background color (alpha, red, green, blue). + b.extend(1u32.to_be_bytes()); + b.extend(rect.iter().flat_map(|v| v.to_be_bytes())); + for t in ["https://example.com/", "_blank", "", "alt"] { + b.extend(psd_unicode(t)); + } + b.push(0); + b.extend(psd_unicode("")); + b.extend([0u8; 8]); + b.extend([255, 10, 20, 30]); + if i == 0 { + b.extend(16u32.to_be_bytes()); + let color = psd_value(b"Objc", &psd_descriptor(&[("Rd ", psd_value(b"doub", &128f64.to_be_bytes()))])); + b.extend(psd_descriptor(&[("topOutset", psd_long(0)), ("bgColor", color)])); + } + } + SliceSample { version: 6, data: b, count_at } +} + +/// Versions 7 and 8: a version 16 descriptor with the slices' bounds, base name and `slices` list, +/// each slice an object with a nested bounds and background color object. +fn psd_slices_descriptor(version: u32) -> SliceSample { + let mut b = version.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(psd_class(3)); + b.extend(psd_key("bounds")); + b.extend(psd_bounds([0, 0, 12, 10])); + b.extend(psd_key("baseName")); + b.extend(psd_text("sheet")); + b.extend(psd_key("slices")); + b.extend(b"VlLs"); + let count_at = b.len(); + b.extend((PSD_SLICES.len() as u32).to_be_bytes()); + for (i, (origin, name, rect)) in PSD_SLICES.iter().enumerate() { + let origin = match origin { + 0 => "autoGenerated", + 1 => "layerGenerated", + _ => "userGenerated", + }; + let doub = |v: f64| psd_value(b"doub", &v.to_be_bytes()); + let color = psd_value(b"Objc", &psd_descriptor(&[("Rd ", doub(10.0)), ("Grn ", doub(20.0)), ("Bl ", doub(30.0))])); + b.extend(psd_value( + b"Objc", + &psd_descriptor(&[ + ("sliceID", psd_long(i as i32 + 1)), + ("groupID", psd_long(0)), + ("origin", psd_enum("ESliceOrigin", origin)), + ("Type", psd_enum("ESliceType", "Img ")), + ("bounds", psd_bounds(*rect)), + ("Nm ", psd_text(name)), + ("url", psd_text("https://example.com/")), + ("bgColorType", psd_enum("ESliceBGColorType", "Clr ")), + ("bgColor", color), + ]), + )); + } + SliceSample { version, data: b, count_at } +} + +/// Resource 1050 in versions 6, 7 and 8. +fn psd_slice_samples() -> Vec { + vec![psd_slices_v6(), psd_slices_descriptor(7), psd_slices_descriptor(8)] +} + +/// A flat 12 × 10 px RGB PSD file whose one image resource is 1050 holding `data`, and where +/// `data` lies in it. +fn sliced_psd(data: &[u8]) -> (Vec, std::ops::Range) { + // The signature, version 1, reserved bytes, 3 channels, 10 rows, 12 columns, 8 bits, RGB, and + // no color mode data. + let mut f = b"8BPS\0\x01\0\0\0\0\0\0\0\x03".to_vec(); + f.extend(10u32.to_be_bytes()); + f.extend(12u32.to_be_bytes()); + f.extend([0, 8, 0, 3]); + f.extend([0; 4]); + let mut block = b"8BIM".to_vec(); + block.extend(1050u16.to_be_bytes()); + block.extend([0, 0]); + block.extend((data.len() as u32).to_be_bytes()); + let start = f.len() + 4 + block.len(); + block.extend(data); + block.resize(block.len().next_multiple_of(2), 0); + f.extend((block.len() as u32).to_be_bytes()); + f.extend(block); + // No layer and mask information, then the merged image, raw. + f.extend([0; 4]); + f.extend([0, 0]); + f.extend((0..360u32).map(|v| (v * 7) as u8)); + (f, start..start + data.len()) +} + +/// PSD file `f` opened (the names of the document's slices, and the open's warnings), counted by +/// `document.psdInfo`, and placed embedded in a new document (the count of the slices it brings in). +fn sliced_psd_imports(f: &[u8]) -> (Vec, Value, Value, usize) { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(f)}); + let r = s.execute("document.open", &p).unwrap(); + let names = s.doc().unwrap().doc.slices.iter().map(|x| x.options.name.clone()).collect(); + let info = s.execute("document.psdInfo", &p).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + let placed = s.execute("file.place", &json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(f), "link": false})).unwrap(); + (names, r["warnings"].clone(), info["slices"].clone(), placed["slices"].as_array().map_or(0, Vec::len)) +} + +/// Each sample reaches the slice reader: its two user slices open and place, without a warning, +/// and `document.psdInfo` counts them; the automatic one is left out. +#[test] +fn the_sliced_psd_samples_bring_in_their_user_slices() { + for sample in psd_slice_samples() { + let (names, warnings, info, placed) = sliced_psd_imports(&sliced_psd(&sample.data).0); + assert_eq!(names, ["a", "b"], "version {}: {warnings}", sample.version); + assert_eq!(warnings.as_array().map_or(0, Vec::len), 0, "version {}: {warnings}", sample.version); + assert_eq!((info, placed), (json!(2), 2), "version {}", sample.version); + } +} + +/// A slice count past the 10,000 read, or one larger than the slices stored, and resource data cut +/// short, open and place the file without its slices, with a warning, and `document.psdInfo` +/// counts none. +#[test] +fn sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices() { + for sample in psd_slice_samples() { + let mut damaged = vec![]; + for count in [10_001u32, 0x7fff_ffff, u32::MAX] { + let mut d = sample.data.clone(); + d[sample.count_at..sample.count_at + 4].copy_from_slice(&count.to_be_bytes()); + damaged.push((format!("count {count}"), d)); + } + damaged.push(("one byte short".into(), sample.data[..sample.data.len() - 1].to_vec())); + damaged.push(("cut in the count".into(), sample.data[..sample.count_at + 2].to_vec())); + for (what, d) in damaged { + let (names, warnings, info, placed) = sliced_psd_imports(&sliced_psd(&d).0); + let warned = warnings.as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains("the slices can't be read")))); + assert!(warned, "version {}, {what}: {warnings}", sample.version); + assert_eq!((names.len(), info, placed), (0, json!(0), 0), "version {}, {what}", sample.version); + } + } +} + +proptest! { + #![proptest_config(config())] + + /// Mutated copies of the slice samples never crash opening the file, `document.psdInfo` or + /// placing it embedded: the resource's data mutated, then kept whole, cut short with the + /// resource's length saying so, or with the file cut short in the resource's block. + #[test] + fn mutated_psd_slices_never_panic(which in 0usize..3, mode in 0u8..3, cut in any::(), edits in prop::collection::vec((any::(), any::()), 0..12)) { + let SliceSample { version, mut data, .. } = psd_slice_samples().swap_remove(which); + let len = data.len(); + for (at, b) in edits { + data[at % len] = b; + } + let bytes = match mode { + 0 => sliced_psd(&data).0, + 1 => { + data.truncate(cut % (len + 1)); + sliced_psd(&data).0 + } + _ => { + let (mut f, at) = sliced_psd(&data); + f.truncate(at.start - 12 + cut % (len + 13)); + f + } + }; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("document.open", &p)); + let _ = no_panic(s.execute("document.psdInfo", &p)); + let _ = no_panic(s.execute("file.new", &json!({}))); + let p = json!({"name": "sheet.psd", "dataBase64": vectorcraft_format::base64_encode(&bytes), "link": false}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "version {version}, mode {mode}: panicked: {:?}", r.err()); + } +} + /// 1-bit TIFFs compressed with CCITT Group 3: modified Huffman (Compression 2) in three strips, T.4 /// (Compression 3) with two-dimensional rows, fill bits, six EOLs at the end and each byte's lowest /// bit first, and T.4 two-dimensional rows in 16 × 16 tiles. diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index 381bc92f15..fb5903c411 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -648,6 +648,107 @@ fn batched_colored_inflate_preserves_compound_holes_and_surface_opacity() { assert_eq!(image.pixels, render(doc(&s)).pixels); } +/// The alpha of `d` drawn at 1:1 against a 3x render averaged down. Inside the art, on each pixel +/// whose 3x average and its eight neighbors' share one alpha, a pixel is off when it is below 255 +/// where that alpha is 255, otherwise more than 3 levels away from it. Outside the art, a pixel is +/// painted past the outline when it has an alpha above 3 where it and its eight neighbors are empty +/// at 3x. Returns (pixels measured inside, pixels off, the largest alpha off, pixels painted past the +/// outline, the first few of either). +fn alpha_against_supersampled(d: &Document) -> (usize, usize, u8, usize, Vec) { + let image = render(d); + let fine = vectorcraft_render::Renderer::new().render( + d, + 1200, + 1200, + kurbo::Affine::scale(3.0), + &vectorcraft_render::RenderOptions { background: None, artboards: false, ..Default::default() }, + ); + let average = fine.area_resized(400, 400).unwrap(); + let (mut measured, mut off, mut worst, mut past) = (0, 0, 0, 0); + let mut first = vec![]; + for y in 1..399 { + for x in 1..399 { + let q = average.pixel(x, y)[3]; + if !(y - 1..=y + 1).all(|y| (x - 1..=x + 1).all(|x| average.pixel(x, y)[3] == q)) { + continue; + } + let p = image.pixel(x, y)[3]; + let wrong = if q == 0 { + let painted = p > 3; + past += usize::from(painted); + painted + } else { + measured += 1; + let hole = if q == 255 { p < 255 } else { p.abs_diff(q) > 3 }; + off += usize::from(hole); + worst = worst.max(p.abs_diff(q)); + hole + }; + if wrong && first.len() < 4 { + first.push(format!("({x},{y}) {p} vs {q}")); + } + } + } + (measured, off, worst, past, first) +} + +/// Revolve under colored lights draws each face of a gradient-lit surface on its own, over an +/// underlay of its faces clipped to the surface's outline: at 1:1, no pixel inside the art lets the +/// background through where a 3x render averaged down is opaque, none paints past the outline, and +/// a surface's opacity, its gradient's transparent stops and its blending mode apply once. The same +/// holds for the art read back from SVG and PDF and for Expand Appearance. +#[test] +fn colored_revolve_faces_leave_no_alpha_holes_at_one_to_one() { + let gradient = |opacity: f64| { + json!({"gradient":{"kind":"linear","start":[100,150],"end":[200,150],"stops":[ + {"offset":0,"color":"#ffffff","opacity":opacity},{"offset":1,"color":"#808080","opacity":opacity} + ]}}) + }; + let lights = json!([ + {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, + {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} + ]); + let cases = [ + ("red light, gradient", gradient(1.0), json!({}), None), + ("red light, solid", json!({"color":"#ffcc66"}), json!({}), None), + ("two lights, gradient", gradient(1.0), json!({"ambient":10,"lights":lights}), None), + ("two lights, solid", json!({"color":"#ffcc66"}), json!({"ambient":10,"lights":lights}), None), + ("red light, edge-on faces", gradient(1.0), json!({"rotationX":-80}), None), + ("red light, gradient at 60%", gradient(0.6), json!({}), None), + ("red light, fill at 60%", gradient(1.0), json!({}), Some(json!({"item":0,"opacity":60}))), + ("red light, multiply", gradient(1.0), json!({}), Some(json!({"item":0,"blend":"Multiply"}))), + ]; + let mut failures = vec![]; + for (name, fill, params, transparency) in cases { + let (mut s, _) = capped_profile(); + s.execute("effect.setParams", &json!({"index":0,"item":null,"params":params})).unwrap(); + s.execute("paint.setFill", &fill).unwrap(); + if let Some(t) = transparency { + s.execute("transparency.set", &t).unwrap(); + } + let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap()["text"].as_str().unwrap().to_owned(); + assert!(!svg.contains(" 10_000, "{name} {of}: {measured} pixels inside"); + if off > 0 || past > 0 { + failures.push(format!("{name} {of}: of {measured} pixels, {off} off (at most {worst}), {past} past the outline: {first:?}")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + /// Under colored lights, an Inflate fill and stroke in solid colors draw each face on its own, in /// one depth order: zoomed in, the fill's faces show the colors the one composite of the surface /// shows (drawn when the stroke is translucent), with no seam between faces; at 1x, where a pixel diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index e36422b759..39737dae3a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -232,8 +232,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 86d268cee1..61126ef228 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -74,15 +74,18 @@ pub struct Output { } /// Write the visible art of `doc` over `region` (document space: its top-left corner is the -/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first; -/// template layers, hidden objects and guides are left out. Raster effects should be turned into -/// images before (the engine does); the ones left are reported and left out. +/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first, +/// in symbols' art too, where each instance places that art (EMF clips 9-slice cells, WMF does +/// not); template layers, hidden objects and guides are left out. Raster effects should be turned +/// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { let r = region.abs(); if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { return Err("the export region is empty".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // The scene writes layers that do not print and leaves hidden layers and objects out. + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); let bytes = match kind { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f5870c5f95..622a800414 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -85,6 +85,43 @@ fn wmf_output_round_trips() { assert!(near(ellipse.geometric_bounds().unwrap(), Rect::new(100.0, 20.0, 180.0, 80.0), 0.1)); } +/// A symbol's square that a Transform effect moves 100 pt right is written where the canvas draws +/// it, in EMF and in WMF, read back: art whose own place is off the artboard is written where the +/// effect moves it onto it, and an instance that doubles the art's width places it first, so the +/// effect still moves it 100 pt (to x = 120, not 220). A stained instance keeps its stain. +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let moved = |rect: Rect| { + let mut art = path(shapes::rectangle(rect), red(), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: [("moveH", 100.0)].into_iter().collect(), + visible: true, + }); + art + }; + // The art's square, the instance's transform and fill, and the square and color it draws. + let cases = [ + (Rect::new(-90.0, 10.0, -80.0, 20.0), Affine::IDENTITY, None, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]), + (Rect::new(10.0, 30.0, 20.0, 40.0), Affine::scale_non_uniform(2.0, 1.0), Some(blue()), Rect::new(120.0, 30.0, 140.0, 40.0), [0, 0, 255]), + ]; + for (square, xf, stain, want, rgb) in cases { + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf }); + if let Some(p) = stain { + inst.appearance = vectorcraft_doc::Appearance::basic(p, Paint::None, 0.0).into(); + } + let mut d = doc_with(200.0, 100.0, vec![inst]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: std::sync::Arc::new(moved(square)) }); + for kind in [Kind::Emf, Kind::Wmf] { + let back = import(&export(&d, d.artboards[0].rect, kind).unwrap().bytes).unwrap(); + let drawn: Vec<(Option, Option<[u8; 3]>)> = paths(&back.document).iter().map(|n| (n.geometric_bounds(), fill_rgb(n))).collect(); + assert_eq!(drawn.len(), 1, "{kind:?} {xf:?}: {drawn:?}"); + assert!(drawn[0].0.is_some_and(|b| near(b, want, 0.1)), "{kind:?} {xf:?}: {drawn:?}"); + assert_eq!(drawn[0].1, Some(rgb), "{kind:?} {xf:?}"); + } + } +} + #[test] fn freeform_points_that_share_a_model_are_written_as_their_mix() { use vectorcraft_color::{Color, Freeform, FreeformPoint, GradientKind}; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 00ac16a3fe..fcdcd01f63 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -57,6 +57,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let layers = vectorcraft_effects::WrittenLayers { hidden: set.writes_layers() && !doc.page_knockout, non_printing: set.include_non_printing || set.create_layers, + hidden_objects: false, }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); // Baking stops early when cancelled, leaving a half-baked copy that must not be written. diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index f280f02ee5..3da2079b9b 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -143,7 +143,9 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = out.source_profiles(); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let then = out.converts_tagged_pixels().then_some(&*out); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 872080bfb5..eaff6c781f 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -12,7 +12,9 @@ //! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose //! converted levels are grey is compressed as greyscale. A colour image the Output settings also //! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the -//! destination; a grey one keeps its profile there, as grey pixels are not converted. +//! destination, and so does one converted from its profile to an RGB destination whose untagged +//! images keep their numbers (Preserve Numbers); a grey one keeps its profile there, as grey +//! pixels are not converted. //! //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output @@ -325,15 +327,23 @@ pub(crate) struct Recoded { pub unconverted: bool, } -/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to -/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, -/// else the step before the image's [`Pixels`] conversion. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ToSrgb { +/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB +/// ([`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, else the +/// step before the image's [`Pixels`] conversion. +#[derive(Clone, Copy)] +pub(crate) struct ToSrgb<'a> { /// The rendering intent of the conversion. pub intent: Intent, /// 16-bit samples may be written (PDF 1.5 and later). pub sixteen_bit: bool, + /// The colour output whose [`crate::output::ColorOut::tagged_pixels`] then convert a colour + /// image converted from its profile, when other colour images are not converted (`recode`'s + /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve + /// Numbers). Its table is built when the first such image needs it. + pub then: Option<&'a crate::output::ColorOut>, + /// Gray images are converted too: with an sRGB destination + /// ([`crate::output::ColorOut::converts_grey_images`]). In the others they keep their profile. + pub grey: bool, } /// What happens to the ICC profile a gray or RGB image carries @@ -521,13 +531,15 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile -/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a gray or RGB profile other than sRGB are converted from it to sRGB -/// instead ([`ToSrgb`]), and colour ones then by `convert`; grey ones that `convert` leaves as -/// they are keep their profile. `interpolate` lets viewers smooth it. An image that can't be -/// decoded is kept as it is, with a warning when its pixels were to be converted to sRGB. When -/// `convert` was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read -/// (it may be in color) or its pixels are beyond the decode allowance; a color image whose pixel -/// data can't be read is not. +/// they carry when `profiles` keeps it ([`SourceProfiles::Keep`]); with `to_srgb`, pixels in a +/// gray or RGB profile other than sRGB are converted from it to sRGB instead ([`ToSrgb`]), and +/// colour ones then by `convert`, or without it by the conversion `to_srgb` gives +/// ([`ToSrgb::then`]); grey ones keep their profile unless the destination is sRGB +/// ([`ToSrgb::grey`]). `interpolate` lets viewers smooth it. An image that can't be decoded is +/// kept as it is, with a warning when its pixels were to be converted to sRGB. When `convert` +/// was to convert its colors, it is [`Recoded::unconverted`] if its header can't be read (it may +/// be in color) or its pixels are beyond the decode allowance; a color image whose pixel data +/// can't be read is not. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -545,8 +557,9 @@ pub(crate) fn recode( use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. - // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. - let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some())); + // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). + let then = to_srgb.and_then(|t| t.then); + let to_srgb = to_srgb.filter(|t| !grey || t.grey); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { @@ -589,6 +602,8 @@ pub(crate) fn recode( Ok(img) => img, Err(limited) => return Recoded { unconverted: limited && convert.is_some(), ..keep }, }; + // Converted from its profile: then by `convert`, else by the conversion `to_srgb` gives. + let mut from_profile = false; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -606,8 +621,9 @@ pub(crate) fn recode( if kind == Kind::Mono && !bilevel(&srgb) { (kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray)); } + from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); + let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.is_none(); // A JPEG kept as JPEG whose samples the conversion leaves unchanged (an sRGB // profile): its JPEG data, without the profile (and, with `Remove`, without its // segments: encoded again when those can't be taken out). @@ -632,6 +648,7 @@ pub(crate) fn recode( }, }; } + let convert = if from_profile { convert.or_else(|| then.and_then(crate::output::ColorOut::tagged_pixels)) } else { convert }; // Pixels that keep their colours keep the profile they are in; converted ones are in the // destination's. let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 454e41c5ac..f5e4bb6e36 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -14,7 +14,10 @@ //! that carries an ICC profile is converted from it to sRGB with the same intent and written //! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its //! pixels are converted to (CMYK, another RGB space), a colour image is converted from its -//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The +//! profile to sRGB and then to the destination. With `preserveNumbers` (and PDF/X-1a), which +//! keeps the numbers of untagged colours only, such an image is converted from its profile +//! whatever the destination: to sRGB, and then to a CMYK or other RGB destination +//! ([`ColorOut::tagged_pixels`]). Without conversion it keeps its profile. The //! destination is a profile name; empty, the document's profile for its colour mode. //! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a //! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK @@ -84,6 +87,9 @@ pub(crate) struct ColorOut { pub srgb_note: Option, /// The image transform, built when the first image needs it. pixels: OnceLock>, + /// The transform of images converted from their profile, when it isn't `pixels` + /// ([`Self::tagged_pixels`]). + tagged_pixels: OnceLock>, /// The CMYK image transform, built when the first CMYK image needs it. cmyk_pixels: OnceLock>, intent: Intent, @@ -128,6 +134,7 @@ impl Default for ColorOut { cmyk_profile, srgb_note: None, pixels: OnceLock::new(), + tagged_pixels: OnceLock::new(), cmyk_pixels: OnceLock::new(), intent, catalog: None, @@ -361,13 +368,49 @@ impl ColorOut { /// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB /// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination /// and an sRGB destination, also when the document's RGB space is sRGB, or a destination - /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space). - /// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB - /// profile (which leaves RGB colours and RGB images as they are) included: such an image - /// keeps its profile, or its numbers are converted as sRGB ones. + /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space); + /// and with Preserve Numbers (and PDF/X-1a's own conversion), whatever the destination, as + /// only untagged colours of the destination's model keep their numbers. The pixels are then + /// converted by [`Self::tagged_pixels`]. `None` otherwise, an RGB destination that is the + /// document's own RGB profile with Convert to Destination (which leaves RGB colours and RGB + /// images as they are) included: such an image keeps its profile. pub(crate) fn image_srgb_intent(&self) -> Option { - let d = self.dest.as_ref().filter(|d| d.destination)?; - ((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent) + let d = self.dest.as_ref()?; + let rgb = d.model == Model::Rgb && (d.srgb || !d.destination); + (rgb || self.pixels().is_some()).then_some(self.intent) + } + + /// Are gray images that carry an ICC profile converted from it to sRGB grays too + /// ([`Self::image_srgb_intent`])? Only with an sRGB destination; in the others, RGB tagged as + /// sRGB included, grey pixels are not converted and keep their profile. + pub(crate) fn converts_grey_images(&self) -> bool { + self.dest.as_ref().is_some_and(|d| d.model == Model::Rgb && d.srgb) + } + + /// The destination a colour image converted from its ICC profile to sRGB + /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not + /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose + /// untagged RGB images keep their numbers (unless RGB is tagged as sRGB). + fn tagged_rgb_dest(&self) -> Option<&Dest> { + self.dest.as_ref().filter(|d| !d.destination && d.model == Model::Rgb && !d.srgb && !self.tagged) + } + + /// Are colour images converted from their ICC profile then converted by + /// [`Self::tagged_pixels`]? + pub(crate) fn converts_tagged_pixels(&self) -> bool { + self.tagged_rgb_dest().is_some() + } + + /// How a colour image converted from its ICC profile to sRGB is then converted into that + /// destination's RGB space ([`Self::converts_tagged_pixels`]), built when the first such image + /// needs it; `None` when there is no such destination. + pub(crate) fn tagged_pixels(&self) -> Option<&Pixels> { + self.tagged_pixels + .get_or_init(|| { + let d = self.tagged_rgb_dest()?; + Some(Pixels::Rgb(Box::new(ProofLut::build(|rgb| d.cms.srgb_to_rgb(rgb))))) + }) + .as_ref() } /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 2a3cbf98af..54e85f44b4 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -187,7 +187,7 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D // the art that prints; the layers kept are shown. let mut kept = doc.clone(); keep_layers(&mut kept.layers, set.print_layers); - let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); Cow::Owned(d) diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 90cc66bc5f..9f7c8560cf 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -282,7 +282,9 @@ fn a_color_image_beyond_the_allowance_for_a_conversion_is_unconverted() { let settings: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})).unwrap(); let out = crate::output::ColorOut::new(&d, &settings).unwrap(); assert!(out.pixels().is_some()); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: false }); + let then = out.converts_tagged_pixels().then_some(&out); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: false, then, grey }); assert!(to_srgb.is_some()); let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); let half = |mut bytes: Vec| { @@ -898,7 +900,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None, grey: true }); for (what, png) in [("RGB", declared(&colour(), &p3)), ("gray", declared(&colour().grayscale(), &gray))] { let keep = crate::images::SourceProfiles::Keep; let r = crate::images::recode(&png, (100.0, 100.0), &c, false, None, keep, srgb_out); @@ -1103,3 +1105,127 @@ fn convert_to_destination_converts_tagged_images_from_their_profile() { let as_srgb = converted_samples(&img, to_cmyk); assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB"); } + +/// With Preserve Numbers, an RGB image that carries an ICC profile is converted from that profile +/// whatever the destination, while an untagged one keeps its numbers in an RGB destination (and +/// converts from sRGB to a CMYK one, as before): to Generic CMYK, sRGB, Wide Gamut RGB, and Wide +/// Gamut RGB that is also the document's RGB profile, and in PDF/X-1a, which converts the same way. +/// A gray image keeps its profile, except in an sRGB destination, where it is converted to sRGB +/// grays. An RGB profile the CMS can't read leaves the image as it is in an RGB destination, and +/// its numbers converted as sRGB ones to a CMYK destination, with a warning. +#[test] +fn preserve_numbers_converts_tagged_images_from_their_profile() { + use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, SRGB, WIDE_GAMUT_RGB, icc_bytes}; + let intent = Intent::RelativeColorimetric; + let settings_with = + |rgb: &str| std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: rgb.into(), ..ColorSettings::default() }).unwrap()); + let (active, own) = (settings_with(SRGB), settings_with(WIDE_GAMUT_RGB)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap(); + let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8); + let img = colour_blocks(); + let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png"); + let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png"); + let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }]; + let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let cmy = cms::ProofLut::build(|rgb| { + let v = cmyk.srgb_to_cmyk(rgb, intent); + [v[0], v[1], v[2]] + }); + let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]); + let wide_lut = cms::ProofLut::build(|rgb| own.srgb_to_rgb(rgb)); + let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat(); + let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec(); + let to_srgb = |rgb: [u8; 3]| rgb.to_vec(); + type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec; + // Each case: what, the color settings, the export settings, the space images are written in, + // how an sRGB pixel converts to the destination, and whether untagged images keep their numbers. + type Case<'a> = (&'a str, &'a std::sync::Arc, Value, &'a str, ToDest<'a>, bool); + let cases: [Case<'_>; 5] = [ + ("CMYK", &active, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}), "DeviceCMYK", &to_cmyk, false), + ("sRGB", &active, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}), "DeviceRGB", &to_srgb, true), + ("Wide Gamut", &active, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ("own RGB", &own, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ( + "PDF/X-1a", + &active, + json!({"standard": "pdfX1a", "compatibility": "1.3", "output": {"destination": GENERIC_CMYK}}), + "DeviceCMYK", + &to_cmyk, + false, + ), + ]; + for (what, color, settings, space, to_dest, keeps) in cases { + let export = |d: &Document| { + let mut s: PdfSettings = serde_json::from_value(settings.clone()).unwrap(); + s.compression.compress_text = false; + let r = cms::with_active((*color).clone(), || export_with_report(d, &PdfOptions { settings: s, ..Default::default() })).unwrap(); + assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings); + if what == "PDF/X-1a" { + crate::pdfx::verify(&r.bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{what}: {e}")); + } + (image_spaces(&r.bytes), image_samples(&r.bytes)) + }; + let (spaces, samples) = export(&tagged_png); + assert_eq!(spaces, device(space), "{what}: tagged"); + let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb))); + let as_numbers = converted_samples(&img, to_dest); + assert!( + samples.len() == 1 && samples_close(&samples[0], &want, false, 1), + "{what}: converted from the profile, {}", + max_diff(&samples[0], &want) + ); + assert!(!samples_close(&samples[0], &as_numbers, false, 8), "{what}: not converted as its numbers"); + let (spaces, samples) = export(&untagged_png); + assert_eq!(spaces, device(space), "{what}: untagged"); + let untagged = if keeps { img.to_rgb8().into_raw() } else { as_numbers }; + assert!(samples.len() == 1 && samples_close(&samples[0], &untagged, false, 1), "{what}: untagged, {}", max_diff(&samples[0], &untagged)); + } + // With RGB colours ICC-tagged as sRGB, the tagged image is written as its sRGB samples, in an + // ICC-based colour space with the sRGB profile. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}}); + let (spaces, pdf) = cms::with_active(active.clone(), || export_images(&tagged_png, settings)); + let is_srgb = |icc: &[u8]| { + let p = cms::IccProfile::from_bytes(None, icc).unwrap(); + [[0.2, 0.5, 0.9], [0.9, 0.1, 0.4]].iter().all(|v| p.to_srgb(v, intent).unwrap().iter().zip(v).all(|(a, b)| (a - b).abs() < 0.01)) + }; + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref().is_some_and(is_srgb), "tagged as sRGB: {spaces:?}"); + let samples = image_samples(&pdf); + let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); + assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); + // A gray image keeps its gray profile, in a CMYK and in an RGB destination, and in an RGB one + // with RGB colours ICC-tagged as sRGB (`all` profiles, PDF/A-2b). + let gray = gray_profile(&[0x01CD]); + let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); + for (what, settings) in [ + (GENERIC_CMYK, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}})), + (WIDE_GAMUT_RGB, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ("all profiles", json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}})), + ("PDF/A-2b", json!({"standard": "pdfA2b", "output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ] { + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray, {what}: {spaces:?}"); + } + // In an sRGB destination it is converted to sRGB grays and written without it. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(), "gray, sRGB: {spaces:?}"); + // A profile the CMS can't read: the image keeps it and its numbers in an RGB destination, and + // its numbers are converted as sRGB ones to a CMYK destination, with a warning each. + let unread = icc_profile(b"RGB ", 600); + let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png"); + let unread_export = |destination: &str| { + let mut s: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "preserveNumbers", "destination": destination}})).unwrap(); + s.compression.compress_text = false; + cms::with_active(active.clone(), || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap() + }; + let r = unread_export(WIDE_GAMUT_RGB); + assert!(r.warnings.iter().any(|w| w.contains("the image keeps it")), "{:?}", r.warnings); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}"); + let r = unread_export(GENERIC_CMYK); + assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings); + let as_srgb = converted_samples(&img, to_cmyk); + assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile, CMYK: converted as sRGB"); +} diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 05107bfb65..4c1f8f0ec2 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -38,7 +38,13 @@ const UNIQUE_PLACEHOLDER: &str = "u_vc_unique_-"; pub(crate) fn export(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>) -> Output { // Live geometry effects (Roughen, Warp, Offset Path, Effect → Pathfinder…) export as their result. - let baked = vectorcraft_effects::bake_document(doc); + // An instance of a symbol whose art has such effects is written as that art placed by the + // instance and then baked, as the canvas draws it; other symbols keep one `` def. + // Hidden layers and objects are written when the options keep them; layers that do not print + // always are. `native` (Preserve Editing) is the document as it is, with its live effects. + let hidden = opts.hidden_layers; + let layers = vectorcraft_effects::WrittenLayers { hidden, non_printing: true, hidden_objects: hidden }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); if opts.object_ids != ObjectIds::Unique { return write(doc, opts, native, ""); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index ea1d5ab95b..b9af2a6c06 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1061,8 +1061,8 @@ impl Writer<'_> { (self.xf, self.instance_xf) = saved; return; } - if let Some(def) = self.symbol_use(sym, n, *xf) { - let m = self.xf * *xf; + let m = self.xf * *xf; + if let Some(def) = self.symbol_use(sym, n, m) { let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) }; self.line(&format!("")); return; @@ -1103,7 +1103,8 @@ impl Writer<'_> { } } - /// The id of the `` def instance `inst` (transform `xf`) can ``, written on first + /// The id of the `` def instance `inst` can `` with transform `xf` (the ``'s + /// own: the instance's transform after those of the instances it sits in), written on first /// use. `None` when the instance needs its own copy of the art: stained by its fill, or moved /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option { diff --git a/crates/svg/src/export/output.rs b/crates/svg/src/export/output.rs index 818a64e293..3ed101340a 100644 --- a/crates/svg/src/export/output.rs +++ b/crates/svg/src/export/output.rs @@ -164,14 +164,22 @@ impl Writer<'_> { } /// Reserve ids for every named object up front so generated def ids never collide with them. + /// Symbols' art takes no ids, also where the drawing holds it placed by an instance (every + /// instance of the symbol writes it). pub(super) fn assign_name_ids(&mut self) { if self.opts.object_ids == ObjectIds::Minimal { return; } + let mut art = HashSet::new(); + for s in &self.doc.symbols { + s.art.walk(&mut |n| { + art.insert(n.id); + }); + } let mut named: Vec<(NodeId, String)> = Vec::new(); self.doc.walk(|n| { // Ruler guides are not written, so their names reserve no id. - if n.is_ruler_guide() { + if n.is_ruler_guide() || art.contains(&n.id) { return; } if let Some(name) = &n.name { diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index f325387033..672005bdf6 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -298,6 +298,11 @@ impl Writer<'_> { self.warn("type on a path with bullets or numbers is outlined to keep its look"); return self.text_outlines(n, t); } + // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). + if !lay.repeat_marks.is_empty() { + self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); + return self.text_outlines(n, t); + } return self.text_on_path(n, t, path, *start); } self.note_fonts(t, &lay); @@ -438,7 +443,8 @@ impl Writer<'_> { // reader would draw elsewhere, the next segment is placed. place = seg.brk || (!fewer && !base.anchored && positioned); if (st.h_scale - st.v_scale).abs() > 1e-9 || seg.scale != 1.0 { - attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance * seg.scale))); + let length = seg.advance * seg.scale + seg.repeat_widen; + attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(length))); } if st.rotation != 0.0 { attrs.push_str(&format!(" rotate=\"{}\"", self.num(-st.rotation))); @@ -495,7 +501,11 @@ impl Writer<'_> { }); let Some(chars) = self.fonts.get_mut(at).map(|u| &mut u.chars) else { continue }; // As written: a list marker's characters, a hyphen where a line breaks, capitals for All - // Caps, the style's Digits. + // Caps, the style's Digits, the character a repeat mark is drawn as. + if let Some(c) = shown_repeat(lay, i, g) { + chars.insert(c); + continue; + } let src = lay.marker_text(i).unwrap_or_else(|| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") }); for c in src.chars().filter(|c| !c.is_control() && *c != '\u{ad}').map(|c| st.digits.map(c)) { if st.all_caps { @@ -711,6 +721,9 @@ struct Segment { /// Glyph Scaling of the segment's one glyph (Justification…), which a reader stretches it to /// (`textLength`); 1 for other segments. scale: f64, + /// How much wider than the repeat mark the canvas draws the character the mark is drawn as + /// (Kurikaeshi Moji Shori), which a reader stretches it to (`textLength`); 0 for other segments. + repeat_widen: f64, /// A list marker's characters and tab, written in /// [`vectorcraft_doc::text::ParaList::marker_style`] of the run's style. marker: bool, @@ -720,6 +733,41 @@ struct Segment { /// given its own position (points). const PLACE_TOLERANCE: f64 = 1e-6; +/// Kurikaeshi Moji Shori: the character glyph `i` of `lay` shows when the layout drew a repeat mark +/// as the character it repeats ([`vectorcraft_text::TextLayout::repeat_marks`]), or None. +fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_text::PositionedGlyph) -> Option { + if lay.repeat_marks.is_empty() || g.len == 0 || lay.marker_text(i).is_some() { + return None; + } + // The marks are in text order, one per line. + let at = lay.repeat_marks.binary_search_by_key(&g.byte, |&(byte, _)| byte).ok()?; + lay.repeat_marks.get(at).map(|&(_, c)| c) +} + +/// Kurikaeshi Moji Shori: how much wider than repeat mark `cluster` the canvas draws glyph `g`, the +/// character the mark is drawn as in the mark's place (text space), or 0 when the face or the +/// mark's glyph is not found. +fn repeat_widen(g: &vectorcraft_text::PositionedGlyph, cluster: &str) -> f64 { + let Some(face) = FontDb::global().face_by_id(g.font_id) else { return 0.0 }; + // ゝ or ヽ with a combining voicing mark is drawn as one glyph, the voiced mark's. + let mark = match cluster { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + _ => match cluster.chars().next() { + Some(c) => c, + None => return 0.0, + }, + }; + let mark_gid = face.glyph_for(mark); + if mark_gid == 0 { + return 0.0; + } + // Font units along the baseline → text space (size, Horizontal Scale and Glyph Scaling). + let [a, b, ..] = g.xf.as_coeffs(); + let widen = (face.advance(g.gid) - face.advance(mark_gid)) * a.hypot(b); + if widen.is_finite() { widen } else { 0.0 } +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -808,9 +856,16 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - } None => (g.advance, g.origin.x), }; - let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); + let repeat = shown_repeat(lay, line.glyph_start + k, g); + let src: String = match repeat { + Some(c) => c.to_string(), + None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), + }; + let widen = if repeat.is_some() { repeat_widen(g, source(line.glyph_start + k, g)) } else { 0.0 }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; - let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)); + // The character a repeat mark is drawn as takes the mark's width on the canvas, which a + // reader does not know: the text after it is placed anew. + let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)) || repeat.is_some(); // A glyph Glyph Scaling widens or narrows is a segment of its own, stretched to its width. let scale = if reader.is_some() && (g.scale - 1.0).abs() > 1e-9 && g.scale.is_finite() { g.scale } else { 1.0 }; let fresh = std::mem::take(&mut after_inline) || scale != 1.0 || segs.last().is_some_and(|last| last.scale != 1.0); @@ -824,7 +879,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let marker = lay.marker_of(line.glyph_start + k).is_some(); let tab_apart = piece == "\t" && (run.style.h_scale - run.style.v_scale).abs() > 1e-9; match segs.last_mut() { - Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart => { + // The character a repeat mark is drawn as is a segment of its own, stretched to its width. + Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart && repeat.is_none() => { last.text.push_str(&piece); last.advance += advance; last.brk = brk; @@ -834,7 +890,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - last.brk |= moved || last.marker != marker; end_segment(last, tail, t, lay, &mut unkerned); } - segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, marker }); + segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, repeat_widen: widen, marker }); } } tail = set.map(|_| (g.byte, advance)); diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 005a03e0fa..ff594e7ce9 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -299,6 +299,109 @@ fn a_stained_instance_with_a_geometry_effect_keeps_its_stain() { } } +/// Symbol "Moved": a red square whose Transform effect moves it `dx` pt right. +fn add_moved_symbol(d: &mut Document, square: Rect, dx: f64) { + let mut art = Node::path(d.alloc_id(), shapes::rectangle(square), Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 0.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": dx}), visible: true }); + d.symbols.push(Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); +} + +/// Instances of a symbol whose art has a geometry effect are written as their art placed by the +/// instance and then baked, where the canvas draws it: moved by the instance, doubled in width +/// (the effect still moves it 100 pt, not 200 pt) and turned. They use no ``, while the +/// instances of a symbol without effects still share one. +#[test] +fn symbol_art_effects_are_written_where_the_canvas_draws_them() { + let mut d = symbol_doc(0.0, &[Affine::translate((30.0, 100.0)), Affine::translate((60.0, 100.0))]); + add_moved_symbol(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), 100.0); + instance(&mut d, "Moved", Affine::IDENTITY); + instance(&mut d, "Moved", Affine::translate((0.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Moved", Affine::translate((-60.0, 40.0)) * Affine::rotate(0.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!((svg.matches("