diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index c7c3e408b4..6764e9d14d 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Does each pair of `keys` blended with `spec` ask for the same number of steps +/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, +/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? +/// False when a count sits that close to where it changes, and for Smooth Color by distance when +/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number. +pub fn blend_steps_settled(keys: &[Arc], spec: &BlendSpec, length: f64, color: f64) -> bool { + let rail = Rail::new(keys, spec); + keys.windows(2).enumerate().all(|(i, w)| { + let [a, b] = w else { return true }; + match spec.spacing { + BlendSpacing::Steps(_) => true, + // The count is `len / d` rounded, which grows with `len`. + BlendSpacing::Distance(d) => { + let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i)); + let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len); + count(len - length) == count(len + length) + } + BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color), + } + }) +} + +/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`] +/// takes grows with what it counts from (the color difference, the keys' reach, the distance +/// between their edges in key sizes), so the pair is settled when the least and the most of +/// these ask for the same count. +fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool { + let bounds = a.visual_bounds().zip(b.visual_bounds()); + let by_level = |d: f64| level_steps(d.max(0.0)) as usize; + match (color_distance(a, b), bounds) { + // Colors that differ, but by too little to count, or by little more: moving them may cross + // where they stop counting as the same. (The same colors stay the same.) + (Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false, + (Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => { + let (ca, cb) = (ba.center(), bb.center()); + let reach = + [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max); + // The centers and sizes move by up to twice `length`. + let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize; + let least = by_level(d - color).min(by_density(reach - 2.0 * length)); + let most = by_level(d + color).min(by_density(reach + 2.0 * length)); + reach.is_finite() && least == most + } + (Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color), + (_, Some((ba, bb))) => { + let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0); + if w <= 4.0 * length || h <= 4.0 * length { + return false; + } + let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()); + let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()); + // Each edge moves by up to `length`: the distances between them by up to twice that, + // and the mean sizes too. + let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h); + let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize; + let m = 2.0 * length; + let least = q(dx - m, dy - m, w + m, h + m); + let most = q(dx + m, dy + m, w - m, h - m); + least.is_finite() && most.is_finite() && count(least) == count(most) + } + (_, None) => true, + } +} + /// Evaluate a blend: the keys and generated steps in paint order. The steps keep to /// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]). pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 21c7fa8a15..fb5570d36d 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -5065,6 +5065,81 @@ proptest! { survive("mutated .ai brushes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; survive("mutated .ai brushes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; } + + /// A `.ai` whose blends, as the writer writes them, are damaged: the keys and spine on `%_` + /// lines with their dictionaries, the drawn steps, the record's `XP` and its hex, and the + /// blend's transparency, cut short or edited. + #[test] + fn ai_written_blends_never_panic(cut in 0usize..BLENDS_FUZZ_CHARS, edits in prop::collection::vec((0usize..BLENDS_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '8', '9', 'A', 'F', '-', '.', ' ', '\n', '(', ')', '/', ',', ';', '%', '_', 'u', 'U', 'K', 'S', 'X', 'P'])), 0..12)) { + let text = mutate_text(blends_text(), cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + survive("mutated .ai blends", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?; + survive("mutated .ai blends, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?; + } +} + +/// The range of [`ai_written_blends_never_panic`]'s cuts and edits: past the end of [`blends_text`]. +const BLENDS_FUZZ_CHARS: usize = 24_000; + +/// The editing data VectorCraft writes for a document with two blends: red to blue squares with +/// three steps and no spine of its own, at half opacity; and three squares 25 pt apart on a spine +/// edited on the canvas, aligned to the path. +fn blends_text() -> &'static str { + static TEXT: std::sync::OnceLock = std::sync::OnceLock::new(); + TEXT.get_or_init(|| { + use std::sync::Arc; + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; + use vectorcraft_doc::{Appearance, Node, NodeKind}; + use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; + let mut doc = Document::new(300.0, 200.0); + let layer = doc.layers[0].id; + let square = |doc: &mut Document, x: f64, y: f64, c: Color| { + Arc::new(Node::path( + doc.alloc_id(), + shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), + Appearance::basic(Paint::solid(c), Paint::None, 0.0), + )) + }; + let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)); + let keys = vec![square(&mut doc, 20.0, 20.0, red), square(&mut doc, 120.0, 20.0, blue)]; + let mut fade = Node::new( + doc.alloc_id(), + NodeKind::Blend { children: keys, spec: Box::new(BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) }, + ); + fade.opacity = 0.5; + doc.insert(Some(layer), usize::MAX, fade).unwrap(); + let keys = vec![square(&mut doc, 20.0, 80.0, red), square(&mut doc, 120.0, 80.0, blue), square(&mut doc, 170.0, 80.0, green)]; + let centers: Vec = [30.0, 130.0, 180.0].iter().map(|x| Point::new(*x, 90.0)).collect(); + let spec = BlendSpec { + spacing: BlendSpacing::Distance(25.0), + orientation: BlendOrientation::AlignToPath, + spine: Some(PathData::single(SubPath::polyline(¢ers, false))), + key_anchors: vec![0, 1, 2], + ..BlendSpec::default() + }; + let path = Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }); + doc.insert(Some(layer), usize::MAX, path).unwrap(); + let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap(); + String::from_utf8(out.program).unwrap() + }) +} + +/// The data [`ai_written_blends_never_panic`] damages, as it is, opens with both blends live, and +/// the property's cuts and edits reach all of it. +#[test] +fn the_written_blends_fuzz_data_opens_live() { + use vectorcraft_doc::NodeKind; + let text = blends_text(); + assert!(text.chars().count() < BLENDS_FUZZ_CHARS, "{}", text.chars().count()); + for mark in ["%AI5_BeginLayer", "%_(K) /String (ShapeBlendPathType) ,", "%_(S) /String (ShapeBlendPathType) ,", "1 0 92 XP", "1 0 116 XP"] { + assert!(text.replace("\r\n", "\n").contains(mark), "{mark}"); + } + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat(); + let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0); + assert!(layered, "{warnings:?}"); + let art = d.layers[0].children().unwrap(); + assert_eq!(art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect::>(), [true, true], "{warnings:?}"); } /// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`]. diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index b6ddb245c2..57f8d06c3a 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -147,6 +147,12 @@ //! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between //! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end; //! any other graph, and a graph with art left out, as its art, with a warning. +//! - Blends, as the reader reads them (`blend.rs`): the blend's key objects and spine as a group on +//! `%_` lines, each key's `/ArtDictionary` naming it a key and its id and the spine's naming it the +//! spine (written when the blend has a spine of its own); its steps drawn, a group; +//! `(Adobe Path Blends) 1 0 n XP` and the blend's record of its spacing, orientation and keys as hex +//! on `%` lines; its name and transparency as a group's after its end (`writer::blends`). A blend is +//! written live only when the reader reads it back with its settings. //! //! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at //! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the @@ -175,7 +181,8 @@ //! and instances of //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice -//! guides, export types and dynamic type left out, live objects (placed documents included) as their art, +//! guides, export types and dynamic type left out, blends the reader wouldn't read back live as +//! their steps, other live objects (placed documents included) as their art, //! strokes a plain line can't draw and the object's art style doesn't hold //! as their filled outlines, several fills or strokes as a group of a path for each, freeform //! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as @@ -288,6 +295,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep let links = writer::style_links(doc); // Before baking, which leaves the wrap objects that may be written as they are unchanged. let wraps_held = if keep_wraps { writer::wraps_held(doc, &styled) } else { HashSet::new() }; + // The blends baking leaves as they are, which may be written live. + let unbaked_blends = writer::unbaked_blends(doc); // Live geometry effects as their result, as the PDF part draws them. let baked = baked(doc); let doc = baked.as_ref().unwrap_or(doc); @@ -318,6 +327,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep // On a large canvas the layers' symbol instances are written as their art. w.symbols_live = scale == 1.0; w.brushes_live = scale == 1.0; + w.blends_live = scale == 1.0; + w.unbaked_blends = unbaked_blends; w.symbol_doc = symbol_doc; w.max_objects = max_objects; w.wraps_held = wraps_held; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index f8e39a4048..61ce1eb5ab 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1087,6 +1087,7 @@ fn counted() -> Vec<(&'static str, Document)> { ("styles", styles_document()), ("painted clips", painted_clips()), ("blend", blend_doc()), + ("blends", blends_document()), ("brushes", brushes_document()), ("envelopes", envelopes_document()), ("wrap bounds", wrap_bounds_doc()), @@ -1111,7 +1112,27 @@ fn wrap_bounds_doc() -> Document { doc } -/// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps. +/// A blend whose own art and steps don't all fit within the object limit is written as its steps, +/// as many as fit, with the limit's warning and the blends warning; it writes no part of its own +/// art or its record. +#[test] +fn a_blend_past_the_object_limit_is_written_as_its_steps() { + let doc = blend_doc(); + let all = export_ai_editing(&doc, &opts()).unwrap(); + assert!(String::from_utf8_lossy(&all.program).contains("ShapeBlendPathType"), "written live with room"); + let read = crate::import::objects_read(&all.program).unwrap(); + for max in 1..read { + let out = export_within(&doc, &opts(), max).unwrap(); + let text = String::from_utf8_lossy(&out.program); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "room for {max}: {:?}", out.warnings); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "room for {max}: {:?}", out.warnings); + assert!(!text.contains("ShapeBlendPathType") && !text.contains("Path Blends)"), "room for {max}: {text}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + assert!(!back.layers[0].children().unwrap().iter().any(|n| matches!(n.kind, NodeKind::Blend { .. })), "room for {max}"); + } +} + +/// A blend of two squares 20 pt apart with a step every 10 pt, written live. fn blend_doc() -> Document { let mut doc = Document::new(200.0, 100.0); let layer = doc.layers[0].id; @@ -11267,8 +11288,13 @@ fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() { assert!(!warnings.iter().any(|w| w == writer::LIVE), "{what}: {warnings:?}"); assert!(matches!(back.kind, NodeKind::Group { .. }), "{what}: {back:#?}"); } - let blend = export_ai_editing(&blend_doc(), &opts()).unwrap(); - assert!(blend.warnings.iter().any(|w| w == writer::LIVE) && !blend.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", blend.warnings); + let mut doc = Document::new(200.0, 100.0); + let a = Arc::new(square(&mut doc, Rect::new(10.0, 10.0, 20.0, 20.0), Color::gray(0.5))); + let repeat = Node::new(doc.alloc_id(), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0))); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, repeat).unwrap(); + let repeat = export_ai_editing(&doc, &opts()).unwrap(); + assert!(repeat.warnings.iter().any(|w| w == writer::LIVE) && !repeat.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", repeat.warnings); } /// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`. @@ -11694,9 +11720,9 @@ fn text_wrap_options_are_written_and_read_back() { same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 6.0, true), (None, 1000.0, false), (None, -1000.0, false)]); } -/// The art drawn for an object (a blend's steps, a stained symbol instance's art) is written -/// without the text wrap options of the objects it is made from, which wrap no type; the object -/// keeps its own. A symbol's art and a live instance keep theirs. +/// The art drawn for an object (the steps of a blend written as its steps, a stained symbol +/// instance's art) is written without the text wrap options of the objects it is made from, which +/// wrap no type; the object keeps its own. A symbol's art and a live instance keep theirs. #[test] fn drawn_art_keeps_only_its_objects_text_wrap() { let mut doc = Document::new(200.0, 100.0); @@ -11705,7 +11731,12 @@ fn drawn_art_keeps_only_its_objects_text_wrap() { Arc::new(wrapped(square(&mut doc, Rect::new(10.0, 10.0, 12.0, 12.0), Color::gray(0.5)), 2.0, true)), Arc::new(wrapped(square(&mut doc, Rect::new(30.0, 10.0, 32.0, 12.0), Color::gray(0.5)), 2.0, true)), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() }; + // With easing, written as its steps. + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; let blend = wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 8.0, false); let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), 4.0, true); doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); @@ -12302,8 +12333,8 @@ fn two_leaves(doc: &mut Document) { doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); } -/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine, -/// each written as a group of its art, wrap area type below them by their bounds after reopening, +/// A symbol instance written as its art (its isolation is a group's), a blend with easing and an +/// intertwine, each written as a group of its art, wrap area type below them by their bounds after reopening, /// as they did before saving, not by the members of that art: the text wrap options go on an /// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the /// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset @@ -12324,7 +12355,11 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false) }; let intertwine = |doc: &mut Document| { @@ -12377,21 +12412,32 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {want:?}"); } - // An envelope written live opens live and wraps by its bounds, its options its own. - let live = |doc: &mut Document| { + // An envelope and a blend written live open live and wrap by their bounds, their options their + // own. + let envelope = |doc: &mut Document| { use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true) }; - let doc = over_area_type(live); - let text_out = program(&doc); - let back = read_back(&doc); - let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); - assert_eq!(before.len(), 1); - assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}"); - let top = back.layers[0].children().unwrap(); - assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}"); - same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); + let blend = |doc: &mut Document| { + let keys = vec![ + Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), + Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), + ]; + let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), -3.0, true) + }; + for (name, doc) in [("envelope", over_area_type(envelope)), ("blend", over_area_type(blend))] { + let text_out = program(&doc); + let back = read_back(&doc); + let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back)); + assert_eq!(before.len(), 1, "{name}"); + assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}"); + let top = back.layers[0].children().unwrap(); + assert!(matches!(top[1].kind, NodeKind::Envelope { .. } | NodeKind::Blend { .. }), "{name}: {text_out}"); + assert_eq!(std::mem::discriminant(&top[1].kind), std::mem::discriminant(&doc.layers[0].children().unwrap()[1].kind), "{name}"); + same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]); + } } /// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the @@ -12405,13 +12451,17 @@ fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() { fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() { use vectorcraft_doc::{TextKind, TextObject, TextRun}; // A blend alone, without a symbol definition, so the objects are the group, the rectangle and - // the steps. + // the steps (with easing, written as its steps). let mut doc = Document::new(300.0, 200.0); let keys = vec![ Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))), Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))), ]; - let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() }; + let spec = vectorcraft_doc::BlendSpec { + spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }, + ..Default::default() + }; let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false); let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, thing).unwrap(); @@ -13004,3 +13054,845 @@ fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() { } } } + +// ---------- blends ---------- + +use vectorcraft_doc::live::{BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, BlendSpec}; + +/// A square `s` wide at (x, y) filled with `c`, as a blend's key. +fn key_square(doc: &mut Document, x: f64, y: f64, s: f64, c: Color) -> Arc { + Arc::new(Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + s, y + s)), Appearance::basic(solid(c), Paint::None, 0.0))) +} + +fn blend_of(doc: &mut Document, keys: Vec>, spec: BlendSpec) -> Node { + Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }) +} + +/// The straight lines through the centers of 20 pt squares at `xs` on y 50 (a spine edited on the +/// canvas, its keys on its anchors). +fn spine_through(xs: &[f64], y: f64) -> PathData { + let points: Vec = xs.iter().map(|x| vectorcraft_geom::Point::new(x + 10.0, y + 10.0)).collect(); + PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)) +} + +/// A 400 × 400 document with blends: `Fade`, red to blue squares, three steps, no spine of its own, +/// at half opacity in Multiply, followed by a path at 80%; `Path`, three keys (red, blue, green) on a +/// spine edited on the canvas, 25 pt apart, aligned to the path; `Smooth`, two close blues in Smooth +/// Color; `Curve` and `Bow`, two keys on a replaced curved spine with four steps; `Diagonal`, two +/// keys 45 degrees apart with no spine of their own, aligned to the path; and a hidden, locked blend +/// in a group `Box`. (Turning the steps along the spine leaves their centers in place, so the +/// orientation comes from the record.) +fn blends_document() -> Document { + let mut doc = Document::new(400.0, 400.0); + let (red, blue, green) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)); + let layer = doc.layers[0].id; + let keys = vec![key_square(&mut doc, 20.0, 20.0, 20.0, red), key_square(&mut doc, 120.0, 20.0, 20.0, blue)]; + let mut fade = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + (fade.name, fade.opacity, fade.blend) = (Some("Fade".into()), 0.5, BlendMode::Multiply); + doc.insert(Some(layer), usize::MAX, fade).unwrap(); + let mut after = (*key_square(&mut doc, 200.0, 20.0, 20.0, green)).clone(); + after.opacity = 0.8; + doc.insert(Some(layer), usize::MAX, after).unwrap(); + let keys = vec![ + key_square(&mut doc, 20.0, 80.0, 20.0, red), + key_square(&mut doc, 120.0, 80.0, 20.0, blue), + key_square(&mut doc, 170.0, 80.0, 20.0, green), + ]; + let spec = BlendSpec { + spacing: BlendSpacing::Distance(25.0), + orientation: BlendOrientation::AlignToPath, + spine: Some(spine_through(&[20.0, 120.0, 170.0], 80.0)), + key_anchors: vec![0, 1, 2], + ..BlendSpec::default() + }; + let mut path = blend_of(&mut doc, keys, spec); + path.name = Some("Path".into()); + doc.insert(Some(layer), usize::MAX, path).unwrap(); + let keys = + vec![key_square(&mut doc, 20.0, 140.0, 20.0, Color::rgb(0.0, 0.0, 0.8)), key_square(&mut doc, 140.0, 140.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let mut smooth = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }); + smooth.name = Some("Smooth".into()); + doc.insert(Some(layer), usize::MAX, smooth).unwrap(); + let keys = vec![key_square(&mut doc, 20.0, 220.0, 20.0, red), key_square(&mut doc, 220.0, 220.0, 20.0, blue)]; + let curve = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((30.0, 230.0).into()), + kurbo::PathEl::CurveTo((80.0, 180.0).into(), (180.0, 180.0).into(), (230.0, 230.0).into()), + ])); + let mut curved = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(4), spine: Some(curve), ..BlendSpec::default() }); + curved.name = Some("Curve".into()); + doc.insert(Some(layer), usize::MAX, curved).unwrap(); + let keys = vec![key_square(&mut doc, 40.0, 260.0, 20.0, red), key_square(&mut doc, 340.0, 260.0, 20.0, blue)]; + let bow = PathData::from_bezpath(&kurbo::BezPath::from_vec(vec![ + kurbo::PathEl::MoveTo((50.0, 270.0).into()), + kurbo::PathEl::CurveTo((50.0, 270.0).into(), (250.0, 200.0).into(), (350.0, 270.0).into()), + ])); + let mut bowed = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(4), spine: Some(bow), ..BlendSpec::default() }); + bowed.name = Some("Bow".into()); + doc.insert(Some(layer), usize::MAX, bowed).unwrap(); + let keys = vec![key_square(&mut doc, 300.0, 20.0, 20.0, red), key_square(&mut doc, 380.0, 100.0, 20.0, blue)]; + let mut diagonal = + blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(2), orientation: BlendOrientation::AlignToPath, ..BlendSpec::default() }); + diagonal.name = Some("Diagonal".into()); + doc.insert(Some(layer), usize::MAX, diagonal).unwrap(); + let keys = vec![key_square(&mut doc, 20.0, 320.0, 20.0, red), key_square(&mut doc, 100.0, 320.0, 20.0, green)]; + let mut shy = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + (shy.visible, shy.locked) = (false, true); + let mut boxed = Node::group(doc.alloc_id(), vec![Arc::new(shy)]); + boxed.name = Some("Box".into()); + doc.insert(Some(layer), usize::MAX, boxed).unwrap(); + doc +} + +/// Every blend of `doc`, in paint order. +fn blends_in(doc: &Document) -> Vec> { + let mut out = vec![]; + fn walk(n: &Arc, out: &mut Vec>) { + if matches!(n.kind, NodeKind::Blend { .. }) { + out.push(n.clone()); + } else { + n.children().into_iter().flatten().for_each(|c| walk(c, out)); + } + } + doc.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// Do the objects `got` lay out as `want` do: as many, each one's bounds within 0.01 pt and its +/// first fill's color within 0.002 a channel, and a group's members the same way? +fn assert_same_objects(got: &[Node], want: &[Node], what: &str) { + assert_eq!(got.len(), want.len(), "{what}: how many"); + for (i, (g, w)) in got.iter().zip(want).enumerate() { + let bounds = |n: &Node| n.geometric_bounds().map(|b| [b.x0, b.y0, b.x1, b.y1]); + match (bounds(g), bounds(w)) { + (Some(a), Some(b)) => assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 0.01), "{what}, object {i}: {a:?} for {b:?}"), + (a, b) => assert_eq!(a, b, "{what}, object {i}"), + } + let fill = |n: &Node| match n.appearance.fill_paint() { + Paint::Solid { color, .. } => Some(color.to_rgb()), + _ => None, + }; + match (fill(g), fill(w)) { + (Some(a), Some(b)) => assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 0.002), "{what}, object {i}: {a:?} for {b:?}"), + (a, b) => assert_eq!(a, b, "{what}, object {i}"), + } + let members = |n: &Node| n.children().map(|c| c.iter().map(|m| (**m).clone()).collect::>()).unwrap_or_default(); + assert_same_objects(&members(g), &members(w), &format!("{what}, object {i}")); + } +} + +/// The blends of `doc` come back live: each with its keys (their points and paint), its spacing +/// and orientation, its name, opacity, blending mode, hidden and locked state, and laying out the +/// same steps (where they sit, how they turn, their colors). A blend with no spine of its own comes +/// back with none, one with a spine edited on the canvas with that spine and its keys' anchors, and +/// one with a replaced spine with a spine anchored at each key (anchors 0 and 1 for two keys). +fn assert_blends_read_back_live(doc: &Document) { + let back = read_back(doc); + let (ours, theirs) = (blends_in(doc), blends_in(&back)); + assert_eq!(theirs.len(), ours.len(), "{:#?}", back.layers[0]); + for (a, b) in ours.iter().zip(&theirs) { + let (NodeKind::Blend { children: ka, spec: sa }, NodeKind::Blend { children: kb, spec: sb }) = (&a.kind, &b.kind) else { panic!() }; + let what = format!("{:?}", a.name); + assert_eq!(kb.len(), ka.len(), "{what}"); + for (x, y) in ka.iter().zip(kb) { + let (g, w) = (art_tree(y), art_tree(x)); + assert!(same_tree(&g, &w), "{what}: {g:#} for {w:#}"); + } + assert_eq!( + (&sb.spacing, sb.orientation, &sb.ease, sb.color_shift, &sb.starts), + (&sa.spacing, sa.orientation, &sa.ease, sa.color_shift, &sa.starts), + "{what}" + ); + match (&sa.spine, sa.key_anchors.is_empty()) { + (None, _) => assert_eq!((&sb.spine, sb.key_anchors.len()), (&None, 0), "{what}: no spine of its own"), + (Some(_), false) => assert!(same_blend_spec(sb, sa), "{what}: {sb:#?} for {sa:#?}"), + (Some(_), true) => { + assert!(sb.spine.is_some(), "{what}"); + assert_eq!(sb.key_anchors, (0..ka.len() as u32).collect::>(), "{what}: an anchor at each key"); + } + } + assert_eq!((&b.name, b.opacity, b.blend, b.visible, b.locked), (&a.name, a.opacity, a.blend, a.visible, a.locked)); + let steps = |k: &[Arc], s: &BlendSpec| vectorcraft_doc::blend::blend_expand(k, s); + assert_same_objects(&steps(kb, sb), &steps(ka, sa), &what); + } +} + +/// Are two blends' settings the same, the spines' points within the written precision? +fn same_blend_spec(got: &BlendSpec, want: &BlendSpec) -> bool { + let points = |s: &Option| { + s.as_ref().map(|p| { + let a: Vec<[f64; 6]> = + p.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| [a.h_in.x, a.h_in.y, a.p.x, a.p.y, a.h_out.x, a.h_out.y])).collect(); + serde_json::json!(a) + }) + }; + let spines = match (points(&got.spine), points(&want.spine)) { + (Some(a), Some(b)) => same_tree(&a, &b), + (None, None) => true, + _ => false, + }; + spines + && (&got.spacing, got.orientation, &got.key_anchors, &got.ease, got.color_shift, &got.starts) + == (&want.spacing, want.orientation, &want.key_anchors, &want.ease, want.color_shift, &want.starts) +} + +/// Each blend comes back live ([`assert_blends_read_back_live`]): no spine of its own, a spine +/// edited on the canvas, replaced curved spines; Specified Steps, Specified Distance, Smooth Color; +/// aligned to the page or the path; named, at half opacity, hidden and locked. The path after the +/// first blend keeps its own opacity. +#[test] +fn blends_are_read_back_live() { + let doc = blends_document(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS || w == writer::LIVE), "{:?}", out.warnings); + let text = program(&doc); + assert_eq!(text.matches("(Adobe Path Blends) 1 0 ").count(), 7); // brand-ok: the plugin name the files use + assert_blends_read_back_live(&doc); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + assert_eq!((art[1].opacity, matches!(art[1].kind, NodeKind::Path { .. })), (0.8, true), "the path after the blend keeps its own opacity"); +} + +/// The record names the keys in their order with the anchors they sit on and the steps before each, +/// the spacing and distance, and the orientation (8 and the spine's starting angle for Align to +/// Path); a key's dictionary names it a key and its id, the spine's names it the spine, and a blend +/// with no spine of its own has no spine part; the blend's name follows its record, before its +/// transparency. +#[test] +fn blends_are_written_in_their_form() { + let doc = blends_document(); + let text = program(&doc); + let words = |at: usize| -> Vec { + let head = text.match_indices("(Adobe Path Blends) 1 0 ").nth(at).unwrap().0; // brand-ok: the plugin name the files use + let hex: String = text[head..].lines().skip(1).take_while(|l| l.starts_with('%') && !l.starts_with("%_")).map(|l| &l[1..]).collect(); + let bytes: Vec = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap()).collect(); + bytes.chunks(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() + }; + let fade = words(0); + let magic = u32::from_le_bytes(*b"DCBA"); + let f = |x: f32| x.to_bits(); + let ff = u32::MAX; + assert_eq!(fade, [magic, 1, f(25.0), 0, 3, 0, 'C' as u32, 0, 0, 1, 2, 'A' as u32, 0, f(0.0), ff, ff, 0, 'B' as u32, 0, f(1.0), ff, ff, 3]); + let path = words(1); + assert_eq!(path.len(), 11 + 3 * 6); + assert_eq!(&path[..7], [magic, 2, f(25.0), 0, 3, f(8.0), 'D' as u32]); + assert_eq!((path[23], path[25], path[28]), ('C' as u32, f(2.0), 1)); + assert_eq!(words(2)[..3], [magic, 0, f(4.0)]); + // Diagonal runs down to the right on the canvas: 45 degrees below level in art space, whose y + // runs up, so its spine starts at 7π/4. + assert_eq!(words(5)[5], f((8.0 + 7.0 * std::f64::consts::FRAC_PI_4) as f32), "Diagonal's orientation"); + let fade_art = &text[..text.find("(Adobe Path Blends) 1 0 ").unwrap()]; // brand-ok: the plugin name the files use + assert!(fade_art.contains("%_(K) /String (ShapeBlendPathType) ,\n%_(A) /String (ShapeBlendPathID) ,"), "{fade_art}"); + assert!(!fade_art.contains("(S) /String (ShapeBlendPathType)"), "no spine part for a blend with no spine of its own"); + assert!(!fade_art.contains("(Fade)"), "the name follows the record"); + let after = &text[text.find("(Adobe Path Blends) 1 0 ").unwrap()..]; // brand-ok: the plugin name the files use + let state = after.find("\n0 0 Xd\n6 () XW").unwrap(); + assert!( + after[..state].contains("%_/ArtDictionary :\n%_/XMLUID : (Fade) ; (AI10_ArtUID) ,"), + "the name before the state block: {}", + &after[..state] + ); + assert_eq!(text.matches("%_(S) /String (ShapeBlendPathType) ,").count(), 3, "the edited spine and the two replaced ones"); +} + +/// Blends of compound paths, of groups, and of 62 keys (the most the ids name; the record's next +/// free id is then 0) come back live, laying out the same steps. +#[test] +fn blends_of_compound_paths_groups_and_62_keys_are_read_back_live() { + let mut doc = Document::new(400.0, 300.0); + let layer = doc.layers[0].id; + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + // The members carry the compound path's paint, as the reader gives them. + let ring = |doc: &mut Document, x: f64, c: Color| { + let paint = || Appearance::basic(solid(c), Paint::None, 0.0); + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, 20.0, x + 20.0, 40.0)), paint()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x + 5.0, 25.0, x + 15.0, 35.0)), paint()); + let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }); + ring.appearance = paint().into(); + Arc::new(ring) + }; + let keys = vec![ring(&mut doc, 20.0, red), ring(&mut doc, 120.0, blue)]; + let mut rings = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + rings.name = Some("Rings".into()); + doc.insert(Some(layer), usize::MAX, rings).unwrap(); + let pair = |doc: &mut Document, x: f64, c: Color| { + let members = vec![key_square(doc, x, 80.0, 10.0, c), key_square(doc, x + 15.0, 80.0, 10.0, Color::gray(0.5))]; + Arc::new(Node::group(doc.alloc_id(), members)) + }; + let keys = vec![pair(&mut doc, 20.0, red), pair(&mut doc, 120.0, blue)]; + let mut pairs = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(2), ..BlendSpec::default() }); + pairs.name = Some("Pairs".into()); + doc.insert(Some(layer), usize::MAX, pairs).unwrap(); + let keys = (0..62).map(|i| key_square(&mut doc, f64::from(i) * 6.0, 150.0, 2.0, Color::gray(f32::from(i as u8) / 62.0))).collect(); + let mut many = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + many.name = Some("Many".into()); + doc.insert(Some(layer), usize::MAX, many).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let text = program(&doc); + let last = text.match_indices("(Adobe Path Blends) 1 0 ").nth(2).unwrap().0; // brand-ok: the plugin name the files use + let hex: String = text[last..].lines().skip(1).take_while(|l| l.starts_with('%') && !l.starts_with("%_")).map(|l| &l[1..]).collect(); + assert_eq!(&hex[6 * 8..7 * 8], "00000000", "the next free id after the 62nd"); + assert_blends_read_back_live(&doc); +} + +/// After a path at half opacity, a blend's steps set their own transparency and lock and hidden +/// state on plain lines: readers of the printed form skip the blend's keys on `%_` lines. +#[test] +fn a_blends_steps_set_their_own_state() { + let mut doc = Document::new(300.0, 100.0); + let layer = doc.layers[0].id; + let mut faint = (*key_square(&mut doc, 250.0, 20.0, 20.0, Color::gray(0.5))).clone(); + faint.opacity = 0.5; + doc.insert(Some(layer), usize::MAX, faint).unwrap(); + let keys = + vec![key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(&mut doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let text = program(&doc); + let hidden_end = text.find("%_U\n%_9 () XW\n").unwrap(); + let steps = &text[hidden_end..text.find("(Adobe Path Blends) 1 0 ").unwrap()]; // brand-ok: the plugin name the files use + for line in ["\n0 A\n", "\n0 Xw\n", "\n0 1 0 0 0 Xy\n"] { + assert!(steps.contains(line), "{line:?} in {steps}"); + } +} + +/// The lines of the layers, `%AI5_BeginLayer` to the end. +fn layer_lines(program: &str) -> Vec<&str> { + program.lines().skip_while(|l| !l.starts_with("%AI5_BeginLayer")).collect() +} + +/// A document with blends is written as the same bytes again, and what the reader reads back is +/// written with the same layers. +#[test] +fn blends_write_the_same_bytes_again() { + let doc = blends_document(); + let first = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program); + let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap(); + let first = String::from_utf8(first.program).unwrap(); + let (again, first) = (layer_lines(&again), layer_lines(&first)); + let differ = again.iter().zip(&first).enumerate().find(|(_, (a, b))| a != b); + assert_eq!(differ, None, "the first line that differs"); + assert_eq!(again.len(), first.len()); +} + +/// Blends the reader wouldn't read back as they are are written as their steps with a warning, as +/// many as the PDF part draws, each where it draws it. Each is changed from a blend that comes back +/// live by one thing: easing, a color shift, start points, an opacity mask, an effect or a fill of +/// its own; more objects than the reader lays out for one blend (5,006); a key that is type; a key +/// with a width profile, two fills, a hidden stroke or a gradient stroke, a drop shadow, a Lab +/// color, an opacity mask, a fill at half opacity or in Multiply, or a stroke under its fill (which +/// the editing copy writes otherwise); a key with Offset Path or Roughen, a group key with a fill of its own, or a +/// compound shape key (which baking changes); a group key holding an empty path, path keys of two +/// subpaths, a compound path key with a member of two subpaths (which the editing copy writes +/// otherwise); a clipping group +/// key; a hidden key; a key holding a +/// blend; keys with gradient fills (whose steps the reader can't compare); more than 62 keys; a +/// spine of two parts; and step counts on the edge of rounding (Smooth Color of one color with +/// edges four and a half key widths apart, Specified Distance of two and a half steps, and 0.03 pt +/// past them on a spine of 200 segments). Smooth Color of one color with edges five key widths +/// apart comes back live, and so does that Specified Distance blend on a spine of two segments. +#[test] +fn blends_the_reader_cant_read_are_written_as_their_steps() { + let live = |doc: &mut Document| { + let keys = vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) + }; + let with_spec = |change: fn(&mut BlendSpec)| { + move |doc: &mut Document| { + let mut n = live(doc); + if let NodeKind::Blend { spec, .. } = &mut n.kind { + change(spec); + } + n + } + }; + let with_keys = |make: fn(&mut Document) -> Vec>| { + move |doc: &mut Document| { + let keys = make(doc); + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }) + } + }; + type Make = Box Node>; + let cases: Vec<(&str, Make)> = vec![ + ("live", Box::new(live)), + ("easing", Box::new(with_spec(|s| s.ease = BlendEase { kind: BlendEaseType::InOut, ramp: 0.5 }))), + ("color shift", Box::new(with_spec(|s| s.color_shift = 30.0))), + ("start points", Box::new(with_spec(|s| s.starts = vec![Some(1), None]))), + ( + "opacity mask", + Box::new(move |doc: &mut Document| { + let mut n = live(doc); + let art = (*key_square(doc, 0.0, 0.0, 200.0, Color::gray(1.0))).clone(); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })); + n + }), + ), + ( + "type key", + Box::new(with_keys(|doc| { + let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(150.0, 40.0), "A", vectorcraft_doc::CharStyle::default()); + let text = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t))); + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(text)] + })), + ), + ( + "more than 5,000 objects", + Box::new(move |doc: &mut Document| { + let keys = (0..6).map(|i| key_square(doc, f64::from(i) * 60.0, 20.0, 10.0, Color::gray(f32::from(i as u8) / 6.0))).collect(); + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1000), ..BlendSpec::default() }) + }), + ), + ( + "key with a width profile", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let mut st = StrokeLayer::new(solid(Color::BLACK), 4.0); + st.profile = Some(vectorcraft_doc::WidthProfile { points: vec![(0.0, 1.0, 0.5), (1.0, 0.0, 1.0)] }); + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(st)); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with two fills", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + a.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0))))); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with a hidden stroke", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let st = StrokeLayer { visible: false, ..StrokeLayer::new(solid(Color::BLACK), 2.0) }; + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(st)); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "key with a gradient stroke", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))]; + let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(grad, 2.0))); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "hidden key", + Box::new(with_keys(|doc| { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + a.visible = false; + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "nested blend", + Box::new(with_keys(|doc| { + let inner = + vec![key_square(doc, 20.0, 20.0, 10.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 40.0, 20.0, 10.0, Color::rgb(0.0, 1.0, 0.0))]; + let inner = blend_of(doc, inner, BlendSpec { spacing: BlendSpacing::Steps(1), ..BlendSpec::default() }); + vec![Arc::new(inner), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "gradient keys", + Box::new(with_keys(|doc| { + let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]; + let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::gray(0.0))).clone(); + a.appearance = Appearance::basic(grad, Paint::None, 0.0).into(); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "63 keys", + Box::new(with_keys(|doc| { + (0..63).map(|i| key_square(doc, f64::from(i) * 6.0, 20.0, 2.0, Color::gray(f32::from(i as u8) / 63.0))).collect() + })), + ), + ("an effect of its own", Box::new(move |doc: &mut Document| with_own(live(doc), |n| n.appearance.effects.push(drop_shadow())))), + ( + "a fill of its own", + Box::new(move |doc: &mut Document| { + with_own(live(doc), |n| n.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))))) + }), + ), + ( + "key with Offset Path", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(fx("path.offsetPath", serde_json::json!({"offset": 3})))))), + ), + ( + "key with Roughen", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(fx("distort.roughen", serde_json::json!({})))))), + ), + ("key with a drop shadow", Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance.effects.push(drop_shadow()))))), + ( + "key in a Lab color", + Box::new(with_keys(|doc| { + changed_key(doc, |a| a.appearance = Appearance::basic(solid(Color::Lab { l: 50.0, a: 60.0, b: -40.0 }), Paint::None, 0.0).into()) + })), + ), + ( + // The other key's stroke of no paint is left out, so the steps' strokes would blend from + // none. + "stroked key against a key with a stroke left out", + Box::new(with_keys(|doc| { + changed_key(doc, |a| a.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), solid(Color::BLACK), 10.0).into()) + })), + ), + ( + // The reader reads at most 64 dash lengths; with more the stroke opens solid. + "key with a dash of 65 lengths", + Box::new(with_keys(|doc| { + let stroked = |dash: Option| { + move |a: &mut Node| { + let mut look = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), solid(Color::BLACK), 2.0); + if let Some(AppearanceItem::Stroke(s)) = look.items.get_mut(1) { + s.dash = dash; + } + a.appearance = look.into(); + } + }; + let mut keys = changed_key(doc, stroked(Some(Dash { pattern: vec![2.0; 65], offset: 0.0, align_corners: false }))); + let mut b = (*keys[1]).clone(); + stroked(None)(&mut b); + keys[1] = Arc::new(b); + keys + })), + ), + ( + "key with a fill of no paint against a filled key", + Box::new(with_keys(|doc| changed_key(doc, |a| a.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into()))), + ), + ( + "key with an opacity mask", + Box::new(with_keys(|doc| { + let art = (*key_square(doc, 0.0, 0.0, 200.0, Color::gray(1.0))).clone(); + changed_key(doc, move |a| { + a.extras_mut().mask = + Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })) + }) + })), + ), + ( + "key fill at half opacity", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + if let Some(AppearanceItem::Fill(f)) = a.appearance.items.first_mut() { + f.opacity = 0.5; + } + }) + })), + ), + ( + "key fill in Multiply", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + if let Some(AppearanceItem::Fill(f)) = a.appearance.items.first_mut() { + f.blend = BlendMode::Multiply; + } + }) + })), + ), + ( + "key stroke under its fill", + Box::new(with_keys(|doc| { + changed_key(doc, |a| { + a.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_))); + a.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(solid(Color::BLACK), 2.0))); + }) + })), + ), + ( + "group key with a fill of its own", + Box::new(with_keys(|doc| { + let mut g = Node::group(doc.alloc_id(), vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]); + g.appearance.items.push(AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0))))); + let h = Node::group(doc.alloc_id(), vec![key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]); + vec![Arc::new(g), Arc::new(h)] + })), + ), + ( + "compound shape key", + Box::new(with_keys(|doc| { + let members = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 30.0, 30.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + let mut g = Node::group(doc.alloc_id(), members); + g.extras_mut().compound_shape = true; + vec![Arc::new(g), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "group key holding an empty path", + Box::new(with_keys(|doc| { + let empty = Node::path(doc.alloc_id(), PathData::default(), Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + let g = Node::group(doc.alloc_id(), vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), Arc::new(empty)]); + let h = Node::group( + doc.alloc_id(), + vec![ + key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0)), + key_square(doc, 150.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0)), + ], + ); + vec![Arc::new(g), Arc::new(h)] + })), + ), + ( + "path key of two subpaths", + Box::new(with_keys(|doc| { + let mut ring = shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(25.0, 25.0, 35.0, 35.0)).subpaths); + let a = Node::path(doc.alloc_id(), ring, Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0)); + let mut ring = shapes::rectangle(Rect::new(120.0, 20.0, 140.0, 40.0)); + ring.subpaths.extend(shapes::rectangle(Rect::new(125.0, 25.0, 135.0, 35.0)).subpaths); + let b = Node::path(doc.alloc_id(), ring, Appearance::basic(solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0)); + vec![Arc::new(a), Arc::new(b)] + })), + ), + ( + "compound path key with a member of two subpaths", + Box::new(with_keys(|doc| { + let mut two = shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)); + two.subpaths.extend(shapes::rectangle(Rect::new(25.0, 25.0, 35.0, 35.0)).subpaths); + let paint = || Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let a = Node::path(doc.alloc_id(), two, paint()); + let b = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(45.0, 20.0, 50.0, 25.0)), paint()); + let mut c = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(a), Arc::new(b)], rule: FillRule::EvenOdd }); + c.appearance = paint().into(); + vec![Arc::new(c), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "clipping group key", + Box::new(with_keys(|doc| { + let clip = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default()); + let inside = key_square(doc, 15.0, 15.0, 30.0, Color::rgb(1.0, 0.0, 0.0)); + let g = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), inside], clip: true }); + vec![Arc::new(g), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] + })), + ), + ( + "a spine of two parts", + Box::new(move |doc: &mut Document| { + let mut n = live(doc); + if let NodeKind::Blend { spec, .. } = &mut n.kind { + let mut spine = spine_through(&[20.0, 120.0], 20.0); + let (p, q) = (vectorcraft_geom::Point::new(0.0, 100.0), vectorcraft_geom::Point::new(50.0, 150.0)); + spine.subpaths.push(vectorcraft_geom::SubPath::polyline(&[p, q], false)); + (spec.spine, spec.key_anchors) = (Some(spine), vec![0, 1]); + } + n + }), + ), + ( + "Smooth Color of one color, four and a half key widths apart", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 110.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }) + }), + ), + ( + "live", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::SmoothColor, ..BlendSpec::default() }) + }), + ), + ( + "Specified Distance of two and a half steps", + Box::new(move |doc: &mut Document| { + let keys = + vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Distance(40.0), ..BlendSpec::default() }) + }), + ), + ( + "Specified Distance 0.03 pt past two and a half steps on a spine of 200 segments", + Box::new(move |doc: &mut Document| distance_on_segments(doc, 200)), + ), + ("live", Box::new(move |doc: &mut Document| distance_on_segments(doc, 2))), + ]; + /// Red to blue squares whose centers are 100.03 pt apart, on a straight spine of `segments` + /// equal segments between them, in Specified Distance of 40 pt. + fn distance_on_segments(doc: &mut Document, segments: u32) -> Node { + let keys = vec![key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, 120.03, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let points: Vec = + (0..=segments).map(|i| vectorcraft_geom::Point::new(30.0 + 100.03 * f64::from(i) / f64::from(segments), 30.0)).collect(); + let spine = PathData::single(vectorcraft_geom::SubPath::polyline(&points, false)); + let spec = BlendSpec { spacing: BlendSpacing::Distance(40.0), spine: Some(spine), key_anchors: vec![0, segments], ..BlendSpec::default() }; + blend_of(doc, keys, spec) + } + // Every case runs, and the cases that fail are listed together. + let failed: Vec<&str> = cases + .into_iter() + .filter(|(what, make)| std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| written_as_steps(what, make))).is_err()) + .map(|(what, _)| what) + .collect(); + assert!(failed.is_empty(), "failed: {failed:?}"); +} + +/// The blend `make` makes, alone on a layer: written live when `what` is "live", else written as its +/// steps with a warning, as many as the PDF part draws, each where it draws it. +fn written_as_steps(what: &str, make: &dyn Fn(&mut Document) -> Node) { + let mut doc = Document::new(400.0, 200.0); + let n = make(&mut doc); + let id = n.id; + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + let first = read_back(&doc).layers[0].children().unwrap()[0].clone(); + if what == "live" { + assert!(!out.warnings.iter().any(|w| w == writer::BLENDS), "{what}: {:?}", out.warnings); + assert!(matches!(first.kind, NodeKind::Blend { .. }), "{what}: {:?}", first.kind); + return; + } + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{what}: {:?}", out.warnings); + assert!(matches!(first.kind, NodeKind::Group { .. }), "{what}: its steps, as a group: {:?}", first.kind); + assert!(!program(&doc).contains("ShapeBlendPathType"), "{what}"); + // The steps the PDF part draws: the blend as baking left it, laid out. + let baked = vectorcraft_effects::bake_document(&doc).unwrap_or_else(|| doc.clone()); + let blend = baked.layers[0].children().unwrap()[0].clone(); + assert_eq!(blend.id, id, "{what}"); + let steps = vectorcraft_effects::expand_live_deep(Some(&baked), &blend); + let want: Vec = steps.children().unwrap().iter().map(|s| (**s).clone()).collect(); + let got: Vec = first.children().unwrap().iter().map(|s| (**s).clone()).collect(); + // As many, each where the PDF part draws it (strokes written as outlines may move a step's + // bounds by up to half their width). + assert_eq!(got.len(), want.len(), "{what}: how many steps"); + let center = |n: &Node| n.geometric_bounds().map(|b| b.center()).unwrap(); + for (i, (g, w)) in got.iter().zip(&want).enumerate() { + assert!((center(g) - center(w)).hypot() <= 2.5, "{what}, step {i}: {:?} for {:?}", center(g), center(w)); + } +} + +/// `n` changed by `change`. +fn with_own(mut n: Node, change: impl FnOnce(&mut Node)) -> Node { + change(&mut n); + n +} + +/// Two keys, red and blue squares, the red one changed by `change`. +fn changed_key(doc: &mut Document, change: impl FnOnce(&mut Node)) -> Vec> { + let mut a = (*key_square(doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0))).clone(); + change(&mut a); + vec![Arc::new(a), key_square(doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))] +} + +/// A document with `blend` (two squares, three steps) in a context the reader doesn't read a blend +/// in, or one the writer writes as hidden lines. +fn blend_in_context(context: &str) -> Document { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let blend = |doc: &mut Document, x: f64| { + let keys = vec![key_square(doc, x, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(doc, x + 100.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + blend_of(doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }) + }; + let square_with = |doc: &mut Document, fill: Paint| { + Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)), Appearance::basic(fill, Paint::None, 0.0)) + }; + let n = match context { + "pattern tile" => { + let b = blend(&mut doc, 0.0); + doc.patterns.push(vectorcraft_doc::PatternDef { + tile: Rect::new(0.0, 0.0, 150.0, 60.0), + ..vectorcraft_doc::PatternDef::new("Fades", vec![Arc::new(b)]) + }); + square_with(&mut doc, Paint::Pattern { pattern: "Fades".into(), xf: Affine::IDENTITY }) + } + "opacity mask" => { + let b = blend(&mut doc, 20.0); + let mut n = square_with(&mut doc, solid(Color::BLACK)); + n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(b), clip: false, invert: false, disabled: false, linked: true })); + n + } + "symbol" => { + let b = blend(&mut doc, 0.0); + doc.symbols.push(Symbol { dynamic: false, name: "Fade".into(), art: Arc::new(b) }); + instance(&mut doc, "Fade", Affine::translate((20.0, 20.0))) + } + "art cut to a clipping object" => { + let clipper = Node::group(doc.alloc_id(), vec![Arc::new(square_with(&mut doc, Paint::None))]); + let b = blend(&mut doc, 20.0); + Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clipper), Arc::new(b)], clip: true }) + } + // Eight symbols' art inside each other, each instance written as its art (isolated): the + // blend is written eight levels down. + "eight levels down" => { + let b = blend(&mut doc, 0.0); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(b) }); + for i in 1..8 { + let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY); + inner.isolate = true; + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) }); + } + let mut top = instance(&mut doc, "S7", Affine::translate((20.0, 20.0))); + top.isolate = true; + top + } + _ => panic!("{context}"), + }; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + doc +} + +/// Blends in pattern tiles, opacity masks and symbols (written as hidden lines or in a symbol's +/// definition), in art cut to a clipping object and eight levels down in art written in place of +/// symbol instances are written as their steps, with a warning. +#[test] +fn blends_in_other_art_are_written_as_their_steps() { + let live = |context: &str| { + let doc = blend_in_context(context); + let out = export_ai_editing(&doc, &opts()).unwrap(); + !out.warnings.iter().any(|w| w == writer::BLENDS) || program(&doc).contains("ShapeBlendPathType") + }; + let contexts = ["pattern tile", "opacity mask", "symbol", "art cut to a clipping object", "eight levels down"]; + let failed: Vec<&str> = contexts.into_iter().filter(|c| live(c)).collect(); + assert!(failed.is_empty(), "written live: {failed:?}"); +} + +/// Blends past what the reader lays out in one file (50,000 objects, each blend counted twice) are +/// written as their steps, with a warning; the blends before them are written live. +#[test] +fn blends_past_the_readers_budget_are_written_as_their_steps() { + let mut doc = Document::new(400.0, 400.0); + let layer = doc.layers[0].id; + // Three keys and 2,003 objects each: twelve take 48,072 and the thirteenth would pass 50,000. + for i in 0..13 { + let y = f64::from(i) * 25.0; + let keys = vec![ + key_square(&mut doc, 20.0, y, 10.0, Color::rgb(1.0, 0.0, 0.0)), + key_square(&mut doc, 120.0, y, 10.0, Color::rgb(0.0, 0.0, 1.0)), + key_square(&mut doc, 220.0, y, 10.0, Color::rgb(0.0, 1.0, 0.0)), + ]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(1000), ..BlendSpec::default() }); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + let back = read_back(&doc); + let art = back.layers[0].children().unwrap(); + let live: Vec = art.iter().map(|n| matches!(n.kind, NodeKind::Blend { .. })).collect(); + assert_eq!(live, [vec![true; 12], vec![false]].concat()); +} + +/// On a large canvas every blend is written as its steps, with a warning. +#[test] +fn a_large_canvas_writes_blends_as_their_steps() { + let mut doc = Document::new(20000.0, 100.0); + let keys = + vec![key_square(&mut doc, 20.0, 20.0, 20.0, Color::rgb(1.0, 0.0, 0.0)), key_square(&mut doc, 120.0, 20.0, 20.0, Color::rgb(0.0, 0.0, 1.0))]; + let n = blend_of(&mut doc, keys, BlendSpec { spacing: BlendSpacing::Steps(3), ..BlendSpec::default() }); + let layer = doc.layers[0].id; + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BLENDS), "{:?}", out.warnings); + assert!(matches!(read_back(&doc).layers[0].children().unwrap()[0].kind, NodeKind::Group { .. })); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index bea247262b..6836d13e44 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -15,6 +15,7 @@ use vectorcraft_pathops::BoolOp; use crate::ai_ops::{self, unit}; use crate::ps; +mod blends; mod brushes; mod envelopes; mod images; @@ -24,6 +25,9 @@ mod symbols; mod texts; mod variables; +#[cfg(test)] +pub(super) use blends::BLENDS; +pub(super) use blends::unbaked_blends; #[cfg(test)] pub(super) use brushes::BRUSHES; #[cfg(test)] @@ -56,7 +60,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +pub(super) const LIVE: &str = "meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = @@ -326,6 +330,14 @@ pub(super) struct Writer<'a> { series_tag: Option, /// Where the `Go` lines of the graph being written start in [`Self::body`]. graph_tags: Vec, + /// Blends may be written live; false on a large canvas, where they are written as their steps. + pub(super) blends_live: bool, + /// How many more objects the reader's blends may lay out ([`crate::import::BLEND_BUDGET`]). + blend_budget: usize, + /// The entries naming a blend's key object in its dictionary, and the key's id. + blend_role: Option<(NodeId, String)>, + /// The blends baking left as they are ([`blends::unbaked_blends`]); only these are written live. + pub(super) unbaked_blends: HashSet, } impl<'a> Writer<'a> { @@ -408,6 +420,10 @@ impl<'a> Writer<'a> { in_graph: false, series_tag: None, graph_tags: vec![], + blends_live: true, + blend_budget: crate::import::BLEND_BUDGET, + blend_role: None, + unbaked_blends: HashSet::new(), } } @@ -838,7 +854,9 @@ impl<'a> Writer<'a> { } NodeKind::Envelope { .. } if self.envelope(n, xy) => {} NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true), - NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { + NodeKind::Blend { .. } if self.blend(n, xy) => {} + NodeKind::Blend { .. } => self.drawn_art(n, xy, Some(blends::BLENDS), true), + NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => { self.drawn_art(n, xy, Some(LIVE), true); } // Ruler guides are kept in the document's native copy only. @@ -953,9 +971,10 @@ impl<'a> Writer<'a> { /// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]), /// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an /// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask - /// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see - /// [`Self::define_symbol`]). False when `n` has an opacity mask that is left out: nested too - /// deep, or its art doesn't fit. + /// (`AI9_Mask`, see [`Self::mask`]), is a symbol's art (its symbol's entries first, see + /// [`Self::define_symbol`]), or is a blend's key object (its part and id after the name, see + /// [`blends`]). False when `n` has an opacity mask that is left out: nested too deep, or its art + /// doesn't fit. fn dictionary(&mut self, n: &Node) -> bool { let name = n.name.as_deref().filter(|s| !s.is_empty()); let moved = std::mem::take(&mut self.wrap_moved); @@ -975,7 +994,11 @@ impl<'a> Writer<'a> { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, }; - if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() { + let role = match &self.blend_role { + Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e), + _ => None, + }; + if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() && role.is_none() { return mask_written; } let start = self.body.len(); @@ -996,6 +1019,10 @@ impl<'a> Writer<'a> { self.bound.push((n.id, id, bound)); } } + let has_role = role.is_some(); + if let Some(r) = role { + self.body.push_str(&r); + } if let Some(w) = wrap { self.text_wrap(w); } @@ -1003,7 +1030,7 @@ impl<'a> Writer<'a> { if let Some(m) = mask && !self.mask(m) { - if !has_id && !has_entries && wrap.is_none() { + if !has_id && !has_entries && wrap.is_none() && !has_role { self.body.truncate(start); return false; } diff --git a/crates/eps/src/ai_editing/writer/blends.rs b/crates/eps/src/ai_editing/writer/blends.rs new file mode 100644 index 0000000000..8d3eb20ac9 --- /dev/null +++ b/crates/eps/src/ai_editing/writer/blends.rs @@ -0,0 +1,354 @@ +//! Blends: a live blend as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader, `blend.rs` +//! and `read/containers.rs`' `end_blend`). +//! +//! The blend's own art on `%_` lines: `0 Ae`, a group of its key objects, each with an +//! `/ArtDictionary` naming it a key (`ShapeBlendPathType` `K`) and its id (`ShapeBlendPathID`, a +//! letter or digit), and its spine as an unpainted path named the spine (`S`), written only when the +//! blend has a spine of its own; then its steps drawn, a group on plain lines; then `0 Ae`, +//! `(Adobe Path Blends) 1 0 n XP` and the blend's record, `n` bytes as hex on `%` lines; then the +//! blend's name in an `/ArtDictionary` and its transparency, as a group's after its end. The record +//! is `DCBA` and little-endian 32-bit words: 1, the spacing (0 Smooth Color, 1 Specified Steps, 2 +//! Specified Distance); 2, the distance as a float (Specified Steps: the spine's length shared out +//! between the steps; Smooth Color: 4); 4, the steps between the first two keys; 5, the orientation +//! (0 Align to Page, a float of 8 and the spine's starting angle in radians for Align to Path); 6, +//! the next free id (0 after the 62nd); 9, 1; 10, the number of keys; then six words a key: its id, +//! 0, the anchor of the spine it sits on as a float, two words of all ones, and the steps between +//! it and the key before it. The reader reads words 1, 2 (for Specified Distance), 5 (0, or 8 or +//! more), 10 and the keys' ids; the others are written as the record's form has them. +//! +//! Each blend is checked with the reader's own reading ([`crate::import::blend_reads`]) before it is +//! written: one the reader would read with other settings is written as its steps. + +use std::collections::HashSet; +use std::fmt::Write; +use std::sync::Arc; + +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::blend::{blend_spine, blend_steps, blend_steps_settled, pin_spine}; +use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_geom::{FillRule, PathData}; + +use super::{MAX_NEST, Writer, Xy, hide}; +use crate::import::{BLEND_PLUGIN, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, blend_reads}; + +pub(in crate::ai_editing) const BLENDS: &str = "blends with easing, a color shift or start points of their own, blends with effects, an appearance or an opacity mask of their own, blends of objects other than paths, compound paths and groups, of clipping groups, of more than 62 key objects, of hidden key objects, of key objects that hold a blend, of key objects with geometry or Pathfinder effects or a group's own fills and strokes, or of key objects the editing copy would change (empty paths or subpaths, paths and compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with transparency or effects of their own, effects or opacity masks), blends where one key object has a fill or stroke of no paint or a stroke of no width and another has one that draws, blends inside objects with geometry or Pathfinder effects or a group's own fills and strokes, blends whose spine has more than one part, blends whose step count is close to where rounding changes it, blends that would open with other settings or not as they are drawn, blends in opacity masks, pattern tiles, symbols and art cut to a clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live objects, brushed strokes), blends whose art would pass the most objects the reader reads, and every blend on a large canvas are written as their steps in the editing data for other apps"; + +/// How far (pt) the lengths a blend counts its steps from may move when written (coordinates are +/// written to 4 decimals and read back through art space) without changing a count. +const SETTLE_LENGTH: f64 = 0.01; +/// How far (pt) each segment of a spine may add to [`SETTLE_LENGTH`]: rounding moves each of its +/// points by up to 0.00005 √2 pt, which moves the segment's length by up to six times that. +const SETTLE_SEGMENT: f64 = 5e-4; +/// How far a key's color (each channel, 0 to 1) may move when written without changing a Smooth +/// Color count. +const SETTLE_COLOR: f64 = 0.001; + +/// The most dash lengths the reader reads; a stroke with more opens solid. +const MAX_DASH_LENGTHS: usize = 64; + +/// The ids the keys take, in their order (letters and digits, as the reader reads them). +const IDS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +/// Hex digits on one `%` line of a record. +const HEX_LINE: usize = 60; + +/// A blend to write live. +pub(super) struct LiveBlend { + keys: Vec>, + ids: Vec, + /// Its spine part; `None`: the blend has no spine of its own. + spine: Option, + record: Vec, + steps: Vec>, +} + +impl Writer<'_> { + /// Blend `n` as the reader reads it live, or `None` when it would read other settings or none + /// (the blend is then written as its steps). + pub(super) fn live_blend(&mut self, n: &Node) -> Option { + let NodeKind::Blend { children: keys, spec } = &n.kind else { return None }; + // Hidden lines (pattern tiles, opacity masks), symbols' definitions and art cut to a + // clipping object aren't read as live blends. (No blend is drawn in a look: styled objects + // hold only paths, compound paths and groups of them.) + if !self.blends_live || self.hidden > 0 || self.in_symbol || self.clip.is_some() || self.nest >= MAX_NEST { + return None; + } + // Baking changes its keys, or the art it sits in ([`unbaked_blends`]). + if !self.unbaked_blends.contains(&n.id) { + return None; + } + if !spec.ease.is_default() || spec.color_shift != 0.0 || !spec.starts.is_empty() { + return None; + } + let own = &n.appearance; + if !own.items.is_empty() || !own.effects.is_empty() || n.extras().mask.is_some() { + return None; + } + // The reader shows every key object it reads. + if keys.len() < 2 || keys.len() > IDS.len().min(MAX_BLEND_KEYS) || !keys.iter().all(|k| k.visible && plain_key(k)) { + return None; + } + // A fill or stroke the editing copy leaves out is read back as none at all, and the steps + // blend from it to another key's otherwise. + if left_out_against_drawn(keys) { + return None; + } + // The spine written: a replaced spine (no key anchors) with an anchor where each key sits, a + // spine edited on the canvas with its keys' anchors moved onto them. + let spec: &BlendSpec = spec; + // The blend lays out along the spine's first subpath, and only that part is written: a + // spine of more parts would open without the others. + if spec.spine.as_ref().is_some_and(|s| s.subpaths.len() > 1) { + return None; + } + let written = match &spec.spine { + None => BlendSpec { key_anchors: vec![], ..spec.clone() }, + Some(_) if spec.key_anchors.is_empty() => { + let (path, anchors) = pin_spine(keys, spec)?; + let anchors = anchors.into_iter().map(u32::try_from).collect::, _>>().ok()?; + BlendSpec { spine: Some(path), key_anchors: anchors, ..spec.clone() } + } + Some(_) => BlendSpec { spine: Some(blend_spine(keys, spec)?.0), ..spec.clone() }, + }; + // As many objects as the reader lays out for one blend, twice within what its budget has left, + // counted before the steps are drawn. + let objects = blend_steps(keys, &written).into_iter().fold(keys.len(), usize::saturating_add); + if objects > MAX_BLEND_OBJECTS || objects.saturating_mul(2) > self.blend_budget { + return None; + } + // The reader counts the steps from the keys as written, rounded: a count that rounding can + // change may come back other than drawn. Specified Distance counts from the spine's length, + // and every segment of the spine adds to how far that may move. + let segments = written.spine.as_ref().and_then(|s| s.subpaths.first()).map_or(0, |s| s.segment_count()); + let settle = match written.spacing { + BlendSpacing::Distance(_) => SETTLE_LENGTH + segments as f64 * SETTLE_SEGMENT, + _ => SETTLE_LENGTH, + }; + if !blend_steps_settled(keys, &written, settle, SETTLE_COLOR) { + return None; + } + let ids: Vec = IDS.iter().take(keys.len()).map(|c| char::from(*c).to_string()).collect(); + let record = self.record(keys, &written)?; + let steps: Vec> = vectorcraft_effects::expand_live_deep(Some(self.doc), n).children().cloned().unwrap_or_default(); + let drawn: Vec = steps.iter().map(|s| (**s).clone()).collect(); + // The spine part as written: the first subpath of the spine laid out. + let part = written.spine.as_ref().and_then(|s| s.subpaths.first()).map(|sp| PathData::single(sp.clone())); + let mut budget = self.blend_budget; + let read = blend_reads(keys, &ids, part.as_ref(), &record, &drawn, &mut budget)?; + if read != written { + return None; + } + self.blend_budget = budget; + Some(LiveBlend { keys: keys.clone(), ids, spine: part, record, steps }) + } + + /// The record of a blend of `keys` with the settings `spec` (its spine as written). + fn record(&self, keys: &[Arc], spec: &BlendSpec) -> Option> { + let (spine, anchors) = blend_spine(keys, spec)?; + let steps = blend_steps(keys, spec); + let first = u32::try_from(*steps.first()?).ok()?; + let (spacing, value) = match spec.spacing { + BlendSpacing::SmoothColor => (0, 4.0), + BlendSpacing::Steps(n) => (1, spine.length() / (f64::from(n) + 1.0)), + BlendSpacing::Distance(d) => (2, d), + }; + let orientation = match spec.orientation { + BlendOrientation::AlignToPage => 0.0, + BlendOrientation::AlignToPath => 8.0 + self.starting_angle(&spine)?, + }; + let count = u32::try_from(keys.len()).ok()?; + let next = IDS.get(keys.len()).copied().map_or(0, u32::from); + let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), spacing, (value as f32).to_bits(), 0, first, (orientation as f32).to_bits()]; + words.extend([next, 0, 0, 1, count]); + for (i, id) in IDS.iter().take(keys.len()).enumerate() { + let anchor = anchors.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(i); + let before = i.checked_sub(1).and_then(|j| steps.get(j)).copied().unwrap_or(0); + words.extend([u32::from(*id), 0, (anchor as f32).to_bits(), u32::MAX, u32::MAX, u32::try_from(before).ok()?]); + } + Some(words.iter().flat_map(|w| w.to_le_bytes()).collect()) + } + + /// The angle in art space (radians, from 0 to 2π) at which `spine` starts. + fn starting_angle(&self, spine: &PathData) -> Option { + let sp = spine.subpaths.first()?; + let first = sp.anchors.first()?; + let towards = if (first.h_out - first.p).hypot() > 1e-9 { first.h_out } else { sp.anchors.get(1)?.p }; + let (a, b) = (self.to_art * first.p, self.to_art * towards); + let angle = (b.y - a.y).atan2(b.x - a.x); + Some(if angle < 0.0 { angle + std::f64::consts::TAU } else { angle }) + } + + /// Blend `n`, of transparency `xy`, written live ([`Self::live_blend`]): its own art on `%_` + /// lines, its steps and its record, then the state block of its transparency, before which the + /// object's dictionary (its name, text wrap options and variables) goes. False, writing + /// nothing, when it is written as its steps: the reader would read it otherwise, or art in it + /// would be left out at the object limit ([`Self::take_objects`]). + pub(super) fn blend(&mut self, n: &Node, xy: Xy) -> bool { + let budget = self.blend_budget; + let Some(b) = self.live_blend(n) else { return false }; + let start = self.body.len(); + let (state, gs, charges, bound, warnings) = (self.state, self.gs, self.charges(), self.bound.len(), self.warnings.len()); + let outer = std::mem::take(&mut self.body); + self.hidden += 1; + self.line("0 Ae"); + let opened = self.open_group("u"); + if opened { + for (k, id) in b.keys.iter().zip(&b.ids) { + self.blend_role = Some((k.id, format!("%_(K) /String (ShapeBlendPathType) ,\n%_({id}) /String (ShapeBlendPathID) ,\n"))); + self.node(k); + self.blend_role = None; + } + if let Some(spine) = &b.spine { + self.plain_object(spine, FillRule::NonZero, None, None, Xy::OPAQUE); + self.body.push_str("%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n%_\n"); + } + self.line("U"); + self.line("9 () XW"); + } + self.hidden -= 1; + let part = std::mem::replace(&mut self.body, outer); + hide(&part, &mut self.body); + // Readers of the printed form skip the hidden lines: the steps set their own state. + (self.state, self.gs) = (None, None); + self.state(n.locked, !n.visible); + let steps = self.open_group("u"); + if steps { + self.nest += 1; + for s in &b.steps { + self.node(s); + } + self.nest -= 1; + self.state(n.locked, !n.visible); + self.line("U"); + self.line("9 () XW"); + } + if !opened || !steps || self.left_out_since(charges) { + let lines = self.body.split_off(start); + self.give_back(charges, &lines); + self.bound.truncate(bound); + // The warnings of art written as its steps again are those steps'. + if !self.left_out_since(charges) { + self.warnings.truncate(warnings); + } + (self.state, self.gs, self.block_end, self.blend_budget) = (state, gs, usize::MAX, budget); + return false; + } + self.line("0 Ae"); + let hex: String = b.record.iter().map(|x| format!("{x:02X}")).collect(); + let _ = writeln!(self.body, "({BLEND_PLUGIN}) 1 0 {} XP", b.record.len()); + for chunk in hex.as_bytes().chunks(HEX_LINE) { + self.body.push('%'); + self.body.push_str(&String::from_utf8_lossy(chunk)); + self.body.push('\n'); + } + // The blend's dictionary goes after the record and before this block ([`Self::node`]). + self.state_block(xy); + true + } +} + +/// The blends on `doc`'s layers that baking leaves as they are: blends with nothing in them that +/// [`vectorcraft_effects::needs_bake`] evaluates (geometry and Pathfinder effects, a group's own +/// fills and strokes), inside no object that has such things of its own. Baking changes the keys +/// of the others, so they are written as their steps. +pub(in crate::ai_editing) fn unbaked_blends(doc: &Document) -> HashSet { + fn walk(nodes: &[Arc], out: &mut HashSet) { + for n in nodes { + if matches!(n.kind, NodeKind::Blend { .. }) { + if !vectorcraft_effects::needs_bake(n) { + out.insert(n.id); + } + continue; + } + let Some(children) = n.children() else { continue }; + let mut own = (**n).clone(); + if let Some(c) = own.children_mut() { + c.clear(); + } + if !vectorcraft_effects::needs_bake(&own) { + walk(children, out); + } + } + } + let mut out = HashSet::new(); + walk(&doc.layers, &mut out); + out +} + +/// Does the reader read stroke `s`'s dashes back as they are (`read/ops.rs`' `d`): at most 64 +/// lengths, each finite and not negative, and a finite offset? It reads other dashes as a solid +/// line. +fn dash_read_back(s: &StrokeLayer) -> bool { + s.dash + .as_ref() + .is_none_or(|d| d.pattern.len() <= MAX_DASH_LENGTHS && d.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && d.offset.is_finite()) +} + +/// Do the keys hold a fill or stroke that the editing copy leaves out (a fill of no paint; a stroke +/// of no paint or of no width, as `visible_items` leaves them out) where another holds one of the +/// same kind that it writes? The steps blend the width, paint and settings of the one left out, and +/// the keys read back blend from no fill or stroke, so the steps would open otherwise. +fn left_out_against_drawn(keys: &[Arc]) -> bool { + // [fill, stroke]: is one left out somewhere, is one written somewhere. + let mut left_out = [false; 2]; + let mut drawn = [false; 2]; + for k in keys { + k.walk(&mut |n| { + for i in &n.appearance.items { + let (kind, out) = match i { + AppearanceItem::Fill(f) => (0, f.paint.is_none()), + AppearanceItem::Stroke(s) => (1, s.paint.is_none() || !(s.width > 0.0 && s.width.is_finite())), + }; + if out { + left_out[kind] = true; + } else { + drawn[kind] = true; + } + } + }); + } + (left_out[0] && drawn[0]) || (left_out[1] && drawn[1]) +} + +/// Can `k` be a key object written live, as the reader reads it back: paths, compound paths and +/// groups other than clipping groups (holding no blend), without effects or opacity masks, each with +/// at most one fill and one plain stroke over it (a line the data draws as it is), each fill and +/// stroke shown, in a color other than Lab or none, opaque in the normal blending mode? (A group's own fills and +/// strokes are baked into art of their own, and such blends aren't [`unbaked_blends`].) +fn plain_key(k: &Node) -> bool { + let mut plain = true; + k.walk(&mut |n| { + // A clipping group may be written as its art cut to the clipping object. + let kind = match &n.kind { + // The writer leaves out a path with nothing to draw and subpaths without anchors, and + // writes a path of several subpaths as a compound path. + NodeKind::Path { path, guide: false, .. } => matches!(path.subpaths.as_slice(), [one] if !one.anchors.is_empty()), + // A compound path is written as one path, and read back with a member for each + // subpath. + NodeKind::Compound { children, .. } => { + !children.is_empty() + && children.iter().all(|c| matches!(&c.kind, NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1)) + } + NodeKind::Group { clip: false, .. } => true, + _ => false, + }; + let items = &n.appearance.items; + let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count(); + let strokes = items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + let order = !matches!(items.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]); + let quiet = items.iter().all(|i| { + i.visible() + && matches!(i.paint(), Paint::Solid { .. } | Paint::None) + // A color that names no global or spot swatch is written in RGB, so a Lab color + // would come back as another. + && !matches!(i.paint(), Paint::Solid { color: Color::Lab { .. }, .. }) + && i.effects().is_empty() + && i.opacity() >= 1.0 + && i.blend() == BlendMode::Normal + && !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s)) + }); + plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none(); + }); + plain +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 259be45eac..fb43590b45 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -90,9 +90,10 @@ pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; pub(crate) use ai::{ - BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, - MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, - read_style_list, style_moves_with, symbol_art_member, warp_number, + BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, blend_reads, + brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object, read_style_list, style_moves_with, + symbol_art_member, warp_number, }; #[cfg(test)] pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 1a73f64a50..a228228d0c 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -34,6 +34,7 @@ use std::io::Read as _; use super::lex::find; use crate::ps; +pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as BLEND_PLUGIN, blend_reads}; pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object}; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use envelope::MAX_CHECKED; @@ -50,14 +51,14 @@ pub(crate) use read::objects_read; pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; +pub(crate) use read::{ + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, + slot_of, style_moves_with, symbol_art_member, +}; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; -pub(crate) use read::{ - MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, slot_of, - style_moves_with, symbol_art_member, -}; pub(crate) use read::is_look_slot; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index 530be2647d..d317164d3a 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -34,16 +34,16 @@ use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind}; use vectorcraft_geom::{ParamCurve, PathData, Point, SubPath}; /// The plugin that writes blends. -pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use +pub(crate) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use /// The most bytes of a blend's record read. pub(super) const MAX_RECORD: usize = 4096; /// The most keys read from one blend. -const MAX_KEYS: usize = 64; +pub(crate) const MAX_KEYS: usize = 64; /// The most steps between two keys (Blend Options' limit). const MAX_STEPS: usize = 1000; /// The most objects (keys and steps) one blend may lay out to be read live; more keep their /// drawn steps. -pub(super) const MAX_BLEND_OBJECTS: usize = 5_000; +pub(crate) const MAX_BLEND_OBJECTS: usize = 5_000; /// How far (pt) a step laid out here may be from where the file draws it. const PLACE_TOLERANCE: f64 = 0.5; /// How far a step's colour (each channel, 0 to 1) may be from the drawn one. @@ -227,6 +227,38 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Rol .map(|(_, spec, _)| NodeKind::Blend { children: keys, spec: Box::new(spec.clone()) }) } +/// What the reader makes of a blend written as the key objects `keys`, named by `ids` in their +/// order, the spine `spine` (`None`: no spine part), the record `bytes` and the drawn steps `drawn`: +/// the live blend's settings, or `None` where it keeps the drawn steps. Takes from `budget` as +/// [`live_blend`] does. +pub(crate) fn blend_reads( + keys: &[Arc], + ids: &[String], + spine: Option<&PathData>, + bytes: &[u8], + drawn: &[Node], + budget: &mut usize, +) -> Option { + let record = record(bytes)?; + let mut roles = Roles::new(); + let mut parts: Vec> = Vec::with_capacity(keys.len() + 1); + for (k, id) in keys.iter().zip(ids) { + roles.insert(k.id, ("K".to_string(), Some(id.clone()))); + parts.push(k.clone()); + } + if let Some(s) = spine { + let id = NodeId(u64::MAX); + roles.insert(id, ("S".to_string(), None)); + parts.push(Arc::new(Node::path(id, s.clone(), Default::default()))); + } + let edit = Node::new(NodeId(u64::MAX - 1), NodeKind::Group { children: parts, clip: false }); + let drawn = Node::new(NodeId(u64::MAX - 2), NodeKind::Group { children: drawn.iter().cloned().map(Arc::new).collect(), clip: false }); + match live_blend(&edit, &drawn, &record, &roles, budget)? { + NodeKind::Blend { spec, .. } => Some(*spec), + _ => None, + } +} + /// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a /// different one. fn on_spine(keys: &[Arc], spine: &PathData) -> Option> { diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 67928785ad..b045dd128f 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -156,9 +156,10 @@ use graph::Graph; pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; #[cfg(test)] pub(crate) use raster::with_image_limits; +pub(crate) use types::BLEND_BUDGET; pub(crate) use types::MAX_NODES; pub use types::PlacedPage; -use types::{BLEND_BUDGET, BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; #[cfg(test)] pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; pub(super) use types::{blend_mode, blend_name}; diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index b6e908c2e1..02d4a3354a 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -16,7 +16,7 @@ pub(crate) const MAX_NODES: usize = 4_000_000; /// The most objects all the blends of one import may lay out to be checked (each twice) and made /// live; past it, blends keep their drawn steps. -pub(super) const BLEND_BUDGET: usize = 50_000; +pub(crate) const BLEND_BUDGET: usize = 50_000; /// Most points in one path. pub(super) const MAX_POINTS: usize = 4_000_000; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9c46a01f77..2ef731ba4a 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -127,7 +127,22 @@ private editing data. VectorCraft: on its stroke; other brushed strokes are written as their brush's art. A document that uses a new document's brushes writes none until a path keeps one on its stroke; then the brushes are written, and the file opens without the new document's Pattern and Bristle - brushes. + brushes. Blends are written live: their key objects, their spine when they have one of their own, their steps + drawn, and their spacing (Smooth Color, Specified Steps, Specified Distance) and orientation (Align to Page, Align to + Path); a replaced spine is written with an anchor where each key object sits, so it opens with those anchors and + lays out the same steps. Blends with easing, a color shift or start points, with effects, an appearance or an + opacity mask of their own, of objects other than paths, compound paths and groups, of clipping groups, of more than + 62 key objects, with a hidden key object, holding another blend, of key objects with geometry or Pathfinder effects + or a group's own fills and strokes, of key objects the editing copy would change (empty paths or subpaths, paths and + compound path members of several subpaths, several fills or strokes, strokes a plain line can't draw, dashes of more than 64 lengths, hidden fills or strokes, fills or strokes other than a color, in a Lab color or with + transparency or effects of their own, effects, opacity masks), where one key object has a fill or stroke of no paint + or a stroke of no width and another has one that draws, whose spine has more than one part, whose step count + is close to where rounding changes it, or that VectorCraft's reader wouldn't open with their settings or as they + are drawn, are written as their steps with a warning, as are blends inside objects with geometry or Pathfinder + effects or a group's own fills and strokes, blends in opacity masks, pattern tiles, symbols and art cut to a + clipping object or nested eight levels deep in art written in place of other objects (symbol instances, live + objects, brushed strokes), blends whose art would pass the most objects VectorCraft's reader reads, and every blend + on a large canvas. Point type, area type (with its rows, columns, gutters and first baseline, threaded frames included) and type on a path are written as text: a text object for each, naming its story in the text document, with the characters, fonts, sizes, leading, tracking, baseline shift,