.ai save: the editing copy keeps live effects

The editing copy of a PDF-compatible .ai wrote an object's live effects
as their result (geometry effects) or left them out (the others).
Objects with effects the .ai reader reads are now written as art styles:

- An object is written as its drawn look (a group of its vector art as
  its geometry effects leave it, without shadows, glows or feathers,
  with the object's transparency after it), then the object itself on
  %_ lines (its points painted with nothing, or with its gradient fill
  placed on the outline it draws; a group with its members), its name
  and opacity mask, and
  1 (style) XW naming its style.
- Styles are written in a non-printing block after the symbols, in
  %AI9_BeginArtStyles: a chain of the stack of fills and strokes (with
  the contents where the appearance puts them), the effects and the
  object's transparency. Objects of the same appearance share a style.
- The effects written are the ones the reader reads on objects, with
  their settings in the units it reads them in: Drop Shadow, Inner Glow,
  Outer Glow, Feather, Round Corners, Scribble, Convert to Shape, Offset
  Path, Outline Object, Outline Stroke and Pathfinder > Add.
- Each style is read back before it is written, by a new reader
  function, read_art_style, which runs the reader's style parser and its
  reading of a graphic style with the object's own gradient. An object
  whose style reads back differently (several fills or strokes, fills
  or strokes with transparency or effects of their own, pattern fills,
  other effects), a filled object that fills by the even-odd rule (a
  style's fill fills by the non-zero rule), a group whose effects change
  its members' outlines while a member is written on another outline
  (strokes as filled outlines, pattern fills as tiles, gradients that
  fit their object), or one in a container whose own
  effects change its members, is written as its drawn look with the
  warning, and a style that is not written leaves no gradient
  definition behind. Graphic styles and links to them are left out with
  a warning. No art style is written on a large canvas.

Appearance attributes:
https://helpx.adobe.com/illustrator/using/appearance-attributes.html

Tests: the round trip of objects with each effect, a gradient fill, a
group with transparency and a mask, Pathfinder > Add and a hidden
effect; the same bytes on a second write; the forms written; the
objects the reader would not read; a large canvas; the warning for
graphic styles; filled even-odd objects; a gradient placed on the
outline Offset Path draws; a style that is not written; effects in a
pattern a drawn look uses; the reader's check of a style; fuzz cases
for damaged written styles.

Docs: docs/file-format-parity.md.
This commit is contained in:
dotCooCoo
2026-11-07 10:17:51 -08:00
parent f8e0639d14
commit 6c285d3042
13 changed files with 2112 additions and 22 deletions
@@ -488,7 +488,7 @@ fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs(
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [id]})).unwrap();
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
let bytes = b64(&r);
+85
View File
@@ -3691,6 +3691,91 @@ proptest! {
survive("mutated .ai symbols", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
survive("mutated .ai symbols, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
}
/// A `.ai` whose art styles, as the writer writes them, are damaged: the styles, the style
/// list, a styled object's drawn look, the object on `%_` lines and its `1 (style) XW`, cut
/// short or edited.
#[test]
fn ai_written_styles_never_panic(cut in 0usize..STYLES_FUZZ_CHARS, edits in prop::collection::vec((0usize..STYLES_FUZZ_CHARS, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U', 'X', 'W'])), 0..12)) {
let text = mutate_text(styles_text(), cut, &edits);
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
survive("mutated .ai art styles", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
survive("mutated .ai art styles, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?;
}
}
/// The range of [`ai_written_styles_never_panic`]'s cuts and edits: past the end of [`styles_text`].
const STYLES_FUZZ_CHARS: usize = 64_000;
/// The editing data VectorCraft writes for a document with a drop shadow on a path, a gradient fill
/// and a width profile on others, a stroked even-odd path with an opacity mask and Pathfinder › Add
/// on a group.
fn styles_text() -> &'static str {
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
TEXT.get_or_init(|| {
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Node, NodeKind, OpacityMask, StrokeLayer, WidthProfile};
use vectorcraft_geom::{FillRule, Rect, shapes};
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let fx = |id: &str| vectorcraft_render::effects::new_effect(id, &json!({})).unwrap();
let mut ap = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 2.0);
ap.effects = vec![fx("stylize.dropShadow")];
let shaded = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap.clone());
doc.insert(Some(layer), usize::MAX, shaded).unwrap();
let ramp = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, Color::BLACK)]);
let mut graded = Appearance::basic(Paint::Gradient(Box::new(GradientPaint::new(ramp))), Paint::None, 0.0);
graded.effects = vec![fx("stylize.outerGlow")];
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 50.0, 50.0, 90.0)), graded);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let mut tapered = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
tapered.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.5), (1.0, 0.0, 1.0)] });
let profiled = Appearance { items: vec![AppearanceItem::Stroke(tapered)], effects: vec![fx("stylize.roundCorners")], contents_index: None };
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 150.0, 40.0)), profiled);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let mut stroked = Appearance::basic(Paint::None, Paint::solid(Color::WHITE), 2.0);
stroked.effects = vec![fx("stylize.dropShadow")];
let mut odd = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 90.0)), stroked);
if let NodeKind::Path { rule, .. } = &mut odd.kind {
*rule = FillRule::EvenOdd;
}
let mask_art = Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(100.0, 50.0, 150.0, 70.0)),
Appearance::basic(Paint::solid(Color::gray(0.0)), Paint::None, 0.0),
);
odd.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
doc.insert(Some(layer), usize::MAX, odd).unwrap();
let square = |doc: &mut Document, x: f64| {
Node::path(
doc.alloc_id(),
shapes::rectangle(Rect::new(x, 50.0, x + 30.0, 80.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
)
};
let (a, b) = (square(&mut doc, 60.0), square(&mut doc, 80.0));
let mut merged = Node::group(doc.alloc_id(), vec![std::sync::Arc::new(a), std::sync::Arc::new(b)]);
merged.appearance = Appearance { effects: vec![fx("pathfinder.add")], ..Appearance::default() }.into();
doc.insert(Some(layer), usize::MAX, merged).unwrap();
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
String::from_utf8(out.program).unwrap()
})
}
/// The data [`ai_written_styles_never_panic`] damages, as it is, opens with its styles live, and the
/// property's cuts and edits reach all of it.
#[test]
fn the_written_styles_fuzz_data_opens_live() {
let text = styles_text();
assert!(text.chars().count() < STYLES_FUZZ_CHARS, "{}", text.chars().count());
for mark in ["%AI9_BeginArtStyles", "%AI5_BeginLayer", "\n6 () XW", "\n1 (Anon", "(BSLeftWidthsArray)", "0 /Bool (UseEvenOdd)", "Bb"] {
assert!(text.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(200.0, 100.0), vec![], false, true, 1.0);
assert!(layered, "{warnings:?}");
let art = d.layers[0].children().unwrap();
assert_eq!(art.iter().map(|n| n.appearance.effects.len()).collect::<Vec<_>>(), [1, 1, 1, 1, 1]);
}
/// Editing data with symbols (S2's art holds an instance of S1, F's holds non-native art), the
+29 -3
View File
@@ -100,6 +100,17 @@
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
//! group with live effects is written as its drawn look (`u`, its vector art as its geometry
//! effects leave it, without shadows, glows or feathers, `U`, its transparency, `0 0 Xd`,
//! `6 () XW`), then the object itself on `%_` lines (its points painted
//! with nothing, or with its gradient fill; a group with its members) with its name and opacity
//! mask, then `1 (style) XW`. The styles are written in a non-printing block after the symbols
//! (`%AI9_BeginArtStyles`, each `/KnownStyle :` with its name and a filter tree: a chain of the
//! stack of fills and strokes with the contents among them, the effects and the blend filter). A
//! fill filter fills by the non-zero rule (`0 /Bool (UseEvenOdd)`), so a filled object that fills by
//! the even-odd rule is written as its drawn look. A style is written only when the reader reads it
//! back as the object's appearance.
//!
//! 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
@@ -133,7 +144,9 @@
//! 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
//! tiles and the placement of pattern swatches that move, turn or scale their pattern, the opacity and blending modes of single fills and strokes, opacity masks on
//! layers and opacity masks nested too deep, and live effects other than geometry effects left out.
//! layers and opacity masks nested too deep, and, on objects written without an art style, live
//! effects other than geometry effects left out; graphic styles, links to them and every art style
//! on a large canvas are left out.
//!
//! The data streams hold the program compressed with Zstandard after `%AI24_ZStandard_Data`, with
//! the version numbers of the newest files users sent ([`private_data`]).
@@ -210,11 +223,15 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
if !(board.is_finite() && board.width() > 0.0 && board.height() > 0.0) {
return Err("the document has no artboard".into());
}
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
let scale = canvas_scale(doc);
// The objects that may keep their effects in an art style, as they are before baking (not on
// a large canvas, whose scale the styles' strokes and effects would need).
let styled = writer::styled_objects(doc);
let graphic_styles = writer::has_graphic_styles(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);
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
let scale = canvas_scale(doc);
let reduced = (scale != 1.0).then(|| {
let mut d = doc.clone();
crate::import::scale_document(&mut d, 1.0 / scale, true);
@@ -243,6 +260,14 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
w.symbols_live = scale == 1.0;
w.symbol_doc = symbol_doc;
w.reserve_swatch_gradients();
if scale == 1.0 {
w.styled = styled;
} else if !styled.is_empty() {
w.warnings.push(writer::LARGE_CANVAS_STYLES.to_string());
}
if graphic_styles {
w.warnings.push(writer::GRAPHIC_STYLES.to_string());
}
for layer in &doc.layers {
w.layer(layer);
}
@@ -266,6 +291,7 @@ pub fn export_ai_editing(doc: &Document, o: &AiEditingOptions) -> Result<AiEditi
s.push_str("%%BeginProlog\n%%EndProlog\n%%BeginSetup\n");
w.definitions(&mut s);
w.symbol_definitions(&mut s);
w.art_styles(&mut s);
s.push_str(&palette);
w.symbol_list(&mut s);
artboards(&mut s, doc, to_art, origin);
File diff suppressed because it is too large Load Diff
+30
View File
@@ -17,9 +17,14 @@ use crate::ps;
mod images;
mod paints;
mod styles;
mod symbols;
mod texts;
#[cfg(test)]
pub(super) use styles::same_appearance;
pub(super) use styles::{GRAPHIC_STYLES, LARGE_CANVAS_STYLES, has_graphic_styles, styled_objects};
pub(super) use images::PAYLOAD;
#[cfg(test)]
pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED};
@@ -208,6 +213,14 @@ pub(super) struct Writer<'a> {
symbol_scales: HashMap<String, f64>,
/// The entries a symbol's dictionary adds to its art's dictionary, and the art's id.
root_entries: Option<(vectorcraft_doc::NodeId, String)>,
/// The objects that may be written with an art style, as they were before baking, by id
/// ([`styles::styled_objects`]).
pub(super) styled: HashMap<NodeId, Arc<Node>>,
/// The art styles written ([`styles`]).
styles: styles::Styles,
/// An object's drawn look is being written: no object in it is written with a style, and its
/// effects are the style's.
in_look: bool,
}
impl<'a> Writer<'a> {
@@ -257,6 +270,9 @@ impl<'a> Writer<'a> {
inner_scale: 1.0,
symbol_scales: HashMap::new(),
root_entries: None,
styled: HashMap::new(),
styles: styles::Styles::default(),
in_look: false,
}
}
@@ -445,6 +461,9 @@ impl<'a> Writer<'a> {
/// Warn when `n` has effects the data leaves out.
fn effects(&mut self, n: &Node) {
if self.in_look {
return;
}
let items = n.appearance.items.iter().filter(|i| i.visible()).flat_map(|i| i.effects());
if n.appearance.effects.iter().chain(items).any(|e| e.visible) {
self.warn(EFFECTS);
@@ -459,6 +478,17 @@ impl<'a> Writer<'a> {
if self.in_symbol {
self.wrote_fixed |= symbols::redrawn(n);
}
// On the layers, outside art cut to a clipping object: with its art style, when it has one.
if !self.in_look
&& self.hidden == 0
&& self.nest == 0
&& self.clip.is_none()
&& !self.in_symbol
&& let Some(orig) = self.styled.get(&n.id).cloned()
&& let Some(name) = self.object_style(n, &orig)
{
return self.styled_object(n, &orig, &name);
}
self.effects(n);
self.state(n.locked, !n.visible);
let xy = Xy::of(n);
+42 -14
View File
@@ -103,6 +103,22 @@ impl Writer<'_> {
name
}
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
/// art uses, and the next name's number.
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
}
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
let (len, used, next) = mark;
self.gradients.truncate(len);
for (d, u) in self.gradients.iter_mut().zip(used) {
d.used = u;
}
self.next_gradient = next;
}
/// `p` as the paint of a fill or stroke whose gradient is placed on `bounds`: a gradient is
/// placed there (it then no longer depends on the shape it paints, which may be cut); one the
/// data can't hold is its average color, with a warning.
@@ -222,24 +238,11 @@ impl Writer<'_> {
/// last stop; a radial one's `… Bm` (the unit circle onto its extent ellipse).
fn instance(&mut self, g: &GradientPaint, stroke: bool, clip: bool, path: &BezPath) {
let Some(geom) = g.geom else { return };
let name = self.define_gradient(&g.gradient, g.swatch.as_deref());
self.line(if stroke { "1 Bb" } else { "Bb" });
self.instance_head(g, clip, path);
let m = self.grad_space;
let u = geom.end - geom.start;
let radial = g.gradient.kind == GradientKind::Radial;
let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas);
if radial {
let c = m * geom.start;
let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c);
let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) };
let off = if fraction > 0.0 { off } else { Vec2::ZERO };
ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]);
self.line("Bh");
}
let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes()));
ps::push_nums(&mut self.body, &place.bg);
ps::push_nums(&mut self.body, &place.transform.as_coeffs());
self.line("1 Bg");
// The unit vector along the gradient, and across it as long.
let frame = |from: f64, to: f64| {
let p = geom.start + u * from;
@@ -267,6 +270,28 @@ impl Writer<'_> {
matrix(frame(last, last + CAP / len), "Bc");
}
/// A gradient instance's focal point (`Bh`, radial gradients only) and its `Bg` line, as
/// [`Self::instance`] writes them; also what a fill's art style holds after its `Bb`.
pub(super) fn instance_head(&mut self, g: &GradientPaint, clip: bool, path: &BezPath) {
let Some(geom) = g.geom else { return };
let name = self.define_gradient(&g.gradient, g.swatch.as_deref());
let m = self.grad_space;
let radial = g.gradient.kind == GradientKind::Radial;
let place = placement(&geom, radial, &(self.canvas * path.clone()), self.canvas);
if radial {
let c = m * geom.start;
let off = geom.focal.map_or(Vec2::ZERO, |f| m * f - c);
let (angle, fraction) = if off.hypot() > 1e-9 { place.focal } else { (0.0, 0.0) };
let off = if fraction > 0.0 { off } else { Vec2::ZERO };
ps::push_nums(&mut self.body, &[off.x, off.y, angle, fraction]);
self.line("Bh");
}
let _ = write!(self.body, "{} {} ", u8::from(!clip), ps::bytes(name.as_bytes()));
ps::push_nums(&mut self.body, &place.bg);
ps::push_nums(&mut self.body, &place.transform.as_coeffs());
self.line("1 Bg");
}
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd` (type 0 linear,
/// 1 radial), `[`, each stop on a `%_` line (`color style opacity 6 midpoint rampPoint Bs`), a
/// linear gradient's from the last to the first and a radial one's from the first to the last,
@@ -390,9 +415,12 @@ impl Writer<'_> {
self.line("n\n%_/ArtDictionary :\n%_1 /Bool (AIPattern_Editor_Backing_Tile_Rect) ,\n%_;\n%_");
self.nest += 1;
self.hidden += 1;
// The tile's effects are its own, not those of a drawn look that first uses it.
let in_look = std::mem::take(&mut self.in_look);
for a in &def.art {
self.node(a);
}
self.in_look = in_look;
self.hidden -= 1;
self.nest -= 1;
let art;
+685
View File
@@ -0,0 +1,685 @@
//! Art styles: objects with live effects a plain path can't hold, written as their drawn look, the
//! object itself on `%_` lines and `1 (style) XW`, and the styles they name in
//! `%AI9_BeginArtStyles` (see [`crate::ai_editing`] for the form). Each style is read back before it
//! is written ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of
//! a graphic style, with the object's own gradient): one that reads back differently is not
//! written, and the object is written as its drawn look alone.
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
use serde_json::Value;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Knockout, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{BezPath, FillRule, Rect, Shape};
use super::{Writer, Xy, blend_code, compound_path, hide};
use crate::ai_ops;
use crate::ps;
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str =
"on a large canvas, objects with live effects are written as their drawn look in the editing data for other apps";
pub(in crate::ai_editing) const GRAPHIC_STYLES: &str = "graphic styles and links to them are left out of the editing data for other apps";
/// Does `doc` have graphic styles other than a new document's, or an object in its layers, opacity
/// masks or symbols linked to a graphic style?
pub(in crate::ai_editing) fn has_graphic_styles(doc: &Document) -> bool {
fn linked(n: &Node) -> bool {
n.extras().graphic_style.is_some()
|| n.extras().mask.as_ref().is_some_and(|m| linked(&m.art))
|| n.children().is_some_and(|c| c.iter().any(|m| linked(m)))
}
doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles || doc.layers.iter().any(|l| linked(l)) || doc.symbols.iter().any(|s| linked(&s.art))
}
/// The objects of `doc`'s layers that may be written with an art style ([`Writer::styled_object`]),
/// by id: paths and compound paths with points and groups, with live effects, without Opacity &
/// Mask Define Knockout Shape (the reader takes an object's transparency from its look, which
/// doesn't carry it). A group's members are paths, compound paths or such groups, none with effects
/// or anything baking changes.
pub(in crate::ai_editing) fn styled_objects(doc: &Document) -> HashMap<NodeId, Arc<Node>> {
fn walk(nodes: &[Arc<Node>], out: &mut HashMap<NodeId, Arc<Node>>) {
for n in nodes {
if candidate(n) {
out.insert(n.id, n.clone());
continue;
}
// Baking a container with effects of its own changes its members, which keep their ids:
// they are written as baking left them.
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &n.kind
&& !bakes_members(n)
{
walk(children, out);
}
}
}
let mut out = HashMap::new();
walk(&doc.layers, &mut out);
out
}
/// Does container `n` need baking for what it has itself, whatever its members hold?
fn bakes_members(n: &Node) -> bool {
let mut own = n.clone();
if let Some(children) = own.children_mut() {
children.clear();
}
vectorcraft_effects::needs_bake(&own)
}
/// Whether `n` may be written with an art style ([`styled_objects`]).
fn candidate(n: &Node) -> bool {
if n.appearance.effects.is_empty() || n.knockout_shape {
return false;
}
match &n.kind {
NodeKind::Path { path, guide: false, clipping: false, .. } => has_points(path),
NodeKind::Compound { .. } => has_points(&compound_path(n)),
NodeKind::Group { children, clip: false } => !n.is_compound_shape() && children.iter().all(|c| plain_member(c)),
_ => false,
}
}
/// Does `path` write anything ([`Writer::plain_object`] skips subpaths without points)?
fn has_points(path: &vectorcraft_geom::PathData) -> bool {
path.subpaths.iter().any(|sp| !sp.anchors.is_empty())
}
/// A member of a group written with an art style: written as it is, and read back as it is.
fn plain_member(n: &Node) -> bool {
let quiet = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| i.effects().is_empty()) && !vectorcraft_effects::needs_bake(n);
quiet
&& match &n.kind {
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => true,
NodeKind::Group { children, .. } => children.iter().all(|c| plain_member(c)),
_ => false,
}
}
/// The art styles objects name, each with its text after its name (`/ActiveStyle :` to `/Def ;`).
#[derive(Default)]
pub(in crate::ai_editing) struct Styles {
/// Every style, in the order written: its name and text.
known: Vec<(String, String)>,
/// The name of each style by its text.
by_text: HashMap<String, String>,
next_anon: u64,
}
impl Styles {
/// The name of an object style of `text`: a style with the same text already written, else a
/// new one named `Anon` and a number.
fn object_style(&mut self, text: String) -> String {
if let Some(name) = self.by_text.get(&text) {
return name.clone();
}
self.next_anon += 1;
let name = format!("Anon {}", self.next_anon);
self.by_text.insert(text.clone(), name.clone());
self.known.push((name.clone(), text));
name
}
}
/// One style as the reader's section holds it: `/KnownStyle :`, `(name) /Name ,`, its text.
fn known_style(name: &str, text: &str) -> String {
format!("/KnownStyle :\n{} /Name ,\n{text}", ps::bytes(name.as_bytes()))
}
/// The number transparency's `Xy` gives the blending mode a live effect's `mode` names (any case,
/// spaces and dashes ignored).
fn mode_code(mode: &str) -> Option<u8> {
let key: String = mode.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
BlendMode::ALL.iter().find(|m| format!("{m:?}").to_ascii_lowercase() == key).map(|m| blend_code(*m))
}
/// A filter's `Xy` line: `mode opacity isolate knockout shape Xy`.
fn xy_line(s: &mut String, xy: Xy) {
let knockout = match xy.knockout {
Knockout::Off => 0,
Knockout::On => 1,
Knockout::Neutral => 2,
};
let _ = write!(s, "{} ", blend_code(xy.blend));
ps::push_num(s, f64::from(xy.opacity));
let _ = writeln!(s, " {} {knockout} {} Xy", u8::from(xy.isolate), u8::from(xy.shape));
}
/// The line style of a paint style that isn't a stroke's.
const NO_LINE: &str = "0 J 0 j 1 w 10 M []0 d\n";
/// A basic filter's start: its name and kind numbers (`1 0` for an effect, `0 0` for the
/// style's own filters), `/Visible` and the dictionary's start.
fn basic(s: &mut String, name: &str, effect: bool, visible: bool) {
let _ = write!(s, "/BasicFilter :\n{} {} 0 /Filter ,\n{} /Visible ,\n", ps::bytes(name.as_bytes()), u8::from(effect), u8::from(visible));
}
/// The filter that stands for the object's contents in its stack.
const CONDUIT: &str = "/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n";
/// A basic filter's end.
const END_BASIC: &str = "; /Dict ;\n /Part ,\n";
/// The blend filter of transparency `xy`.
fn blend_filter(s: &mut String, xy: Xy) {
basic(s, "Blend Style Filter", false, true);
s.push_str("/Dictionary : /NotRecorded ,\n/BlendStyle : ");
xy_line(s, xy);
s.push_str(NO_LINE);
s.push_str("0 XR\n/Def ; \n (BlendStyle) ,\n");
s.push_str(END_BASIC);
}
/// A live effect's dictionary entries.
#[derive(Default)]
struct Entries(String);
impl Entries {
fn real(&mut self, key: &str, v: f64) {
ps::push_num(&mut self.0, v);
let _ = writeln!(self.0, " /Real {} ,", ps::bytes(key.as_bytes()));
}
fn int(&mut self, key: &str, v: i64) {
let _ = writeln!(self.0, "{v} /Int {} ,", ps::bytes(key.as_bytes()));
}
fn bool(&mut self, key: &str, v: bool) {
let _ = writeln!(self.0, "{} /Bool {} ,", u8::from(v), ps::bytes(key.as_bytes()));
}
}
/// `p`'s entry `key` as a number.
fn num(p: &Value, key: &str) -> Option<f64> {
p.get(key)?.as_f64().filter(|v| v.is_finite())
}
/// `p`'s entry `key` as text, for comparing: lower case, letters and digits only.
fn word(p: &Value, key: &str) -> Option<String> {
Some(p.get(key)?.as_str()?.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase())
}
/// `p`'s entry `key` as a switch.
fn flag(p: &Value, key: &str) -> Option<bool> {
p.get(key)?.as_bool()
}
impl Writer<'_> {
/// What `paint` writes with [`Self::color`] (a color, a spot or global color), as a string.
fn color_ops(&mut self, paint: &Paint, stroke: bool) -> String {
let saved = std::mem::take(&mut self.body);
self.color(paint, stroke);
std::mem::replace(&mut self.body, saved)
}
/// A fill style holding a color, as an effect's entry `key` or a fill's own.
fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) {
let ops = self.color_ops(&Paint::solid(color), false);
let _ = write!(s, "/FillStyle : 0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Def ; \n {} ,\n", ps::bytes(key.as_bytes()));
}
/// A fill's basic filter: a color, or a gradient placed on the object's outline (`on`: the
/// object's own outline and rule), filling by the non-zero rule. `None` for other paint.
fn fill_filter(&mut self, s: &mut String, f: &FillLayer, visible: bool, on: Option<(&BezPath, FillRule)>) -> Option<()> {
if f.overprint {
return None;
}
// A color comes before the paint state, a gradient's instance after it.
let (color, gradient) = match &f.paint {
Paint::Solid { .. } => (self.color_ops(&f.paint, false), String::new()),
Paint::Gradient(_) => {
let (path, _) = on?;
let Paint::Gradient(placed) = self.placed(&f.paint, path.bounding_box()) else { return None };
(String::new(), format!("Bb\n{}0 BB\n", self.gradient_bg(&placed, path)?))
}
Paint::Pattern { .. } | Paint::None => return None,
};
basic(s, "Fill Style Filter", false, visible);
let _ = write!(
s,
"/Dictionary : /NotRecorded ,\n0 /Bool (UseEvenOdd) ,\n/FillStyle : 0 O\n{color}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n{gradient}"
);
s.push_str("/Def ; \n (FillStyle) ,\n");
s.push_str(END_BASIC);
Some(())
}
/// A stroke's basic filter: a color, its line style, and its width profile as the arrays
/// `BSVariableWidthTValuesArray`, `BSLeftWidthsArray` and `BSRightWidthsArray`. `None` for
/// other paint.
fn stroke_filter(&mut self, s: &mut String, st: &StrokeLayer, visible: bool) -> Option<()> {
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
return None;
}
let ops = self.color_ops(&st.paint, true);
basic(s, "Stroke Style Filter", false, visible);
s.push_str("2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n");
s.push_str(&ops);
s.push_str("0 1 0 0 0 Xy\n");
ai_ops::line_style(s, st);
s.push_str("0 XR\n1 0 Xd\n/Def ; \n (StrokeStyle) ,\n");
if let Some(p) = &st.profile {
let array = |s: &mut String, key: &str, values: &mut dyn Iterator<Item = f64>| {
s.push_str("/Array :");
for v in values {
s.push(' ');
ps::push_num(s, v);
s.push_str(" /Real ,");
}
let _ = writeln!(s, " ; {} ,", ps::bytes(key.as_bytes()));
};
array(s, "BSVariableWidthTValuesArray", &mut p.points.iter().map(|q| q.0));
array(s, "BSLeftWidthsArray", &mut p.points.iter().map(|q| q.1));
array(s, "BSRightWidthsArray", &mut p.points.iter().map(|q| q.2));
}
s.push_str(END_BASIC);
Some(())
}
/// A gradient instance's focal point (`Bh`, radial gradients only) and its `flag (name) x y
/// angle length a b c d tx ty 1 Bg` line for placed gradient `g` on `path`, as a fill's style
/// holds them ([`Self::instance_head`]).
fn gradient_bg(&mut self, g: &vectorcraft_color::GradientPaint, path: &BezPath) -> Option<String> {
let saved = std::mem::take(&mut self.body);
self.instance_head(g, false, path);
let line = std::mem::replace(&mut self.body, saved);
(!line.is_empty()).then_some(line)
}
/// An appearance item's basic filter. `None` for an item with transparency or effects of its
/// own, which the reader doesn't read on an object.
fn item_filter(&mut self, s: &mut String, item: &AppearanceItem, on: Option<(&BezPath, FillRule)>) -> Option<()> {
if item.opacity() < 1.0 || item.blend() != BlendMode::Normal || !item.effects().is_empty() {
return None;
}
match item {
AppearanceItem::Fill(f) => self.fill_filter(s, f, item.visible(), on),
AppearanceItem::Stroke(st) => self.stroke_filter(s, st, item.visible()),
}
}
/// The text of a style of appearance `ap` and transparency `xy` (after its name): the chain
/// of its stack (the fills and strokes that paint, the top one first, the contents among them
/// where the appearance puts them), its effects and its blend filter. A gradient fill is
/// placed on the outline of `on`, and a fill fills by its rule (`None`: the non-zero rule, on no
/// object). `None` when a fill, stroke or effect isn't one written here.
pub(super) fn style_text(&mut self, ap: &Appearance, xy: Xy, on: Option<(&BezPath, FillRule)>) -> Option<String> {
let mut s = String::from(
"/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n",
);
let ci = ap.contents_index.unwrap_or(0).min(ap.items.len());
let painting: Vec<(usize, &AppearanceItem)> = ap.items.iter().enumerate().filter(|(_, i)| !i.paint().is_none()).collect();
let below = painting.iter().filter(|(at, _)| *at < ci).count();
// Listed top first: the contents go above the `below` fills and strokes under them.
for (written, (_, item)) in painting.iter().rev().enumerate() {
if painting.len() - written == below {
s.push_str(CONDUIT);
}
self.item_filter(&mut s, item, on)?;
}
if below == 0 {
s.push_str(CONDUIT);
}
s.push_str(";\n /Part ,\n");
for e in &ap.effects {
s.push_str(&self.effect_filter(e)?);
}
blend_filter(&mut s, xy);
s.push_str(";\n\n/Execution ;\n /Def ;\n");
Some(s)
}
/// A live effect's basic filter, with the settings the reader reads
/// ([`crate::import`]'s `.ai` reader, `style.rs`), in the units it reads them in. `None` for an
/// effect, or a setting, that isn't written here.
fn effect_filter(&mut self, e: &Effect) -> Option<String> {
let p = vectorcraft_effects::merged_params(&e.id, &e.params);
let mut d = Entries::default();
let id = e.id.as_str();
let name = if id.starts_with("stylize.") { self.stylize_entries(id, &p, &mut d)? } else { Self::path_entries(id, &p, &mut d)? };
let mut s = String::new();
basic(&mut s, name, true, e.visible);
s.push_str("/Dictionary : /NotRecorded ,\n");
s.push_str(&d.0);
s.push_str(END_BASIC);
Some(s)
}
/// A Stylize effect's entries ([`Self::effect_filter`]) and its filter's name.
fn stylize_entries(&mut self, id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> {
Some(match id {
"stylize.dropShadow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
let darkness = word(p, "shade").as_deref() == Some("darkness");
if darkness {
d.real("dark", num(p, "darkness")?);
}
d.real("vert", num(p, "y")?);
d.real("horz", num(p, "x")?);
d.real("blur", num(p, "blur")? / 2.0);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK);
self.fill_style(&mut d.0, color, "sclr");
d.int("csrc", i64::from(darkness));
"Adobe Drop Shadow" // brand-ok: the filter's name in the files
}
"stylize.innerGlow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
d.real("blur", num(p, "blur")?);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::WHITE);
self.fill_style(&mut d.0, color, "gclr");
d.int("gtyp", i64::from(word(p, "source").as_deref() == Some("edge")));
"Adobe Inner Glow" // brand-ok: the filter's name in the files
}
"stylize.outerGlow" => {
d.int("blnd", i64::from(mode_code(p.get("mode")?.as_str()?)?));
d.real("opac", num(p, "opacity")? / 100.0);
d.real("blur", num(p, "blur")? / 2.0);
let color = vectorcraft_effects::color_param(p, vectorcraft_color::Color::BLACK);
self.fill_style(&mut d.0, color, "sclr");
"Adobe Outer Glow" // brand-ok: the filter's name in the files
}
"stylize.feather" => {
d.real("Radius", num(p, "radius")?);
"Adobe Fuzzy Mask" // brand-ok: the filter's name in the files
}
"stylize.roundCorners" => {
d.real("radius", num(p, "radius")?);
"Adobe Round Corners" // brand-ok: the filter's name in the files
}
"stylize.scribble" => {
d.real("Angle", num(p, "angle")?);
d.real("EdgeOverlap", num(p, "overlap")?);
d.real("EdgeOverlapVariation", num(p, "overlapVariation")?);
d.real("StrokeWidth", num(p, "strokeWidth")?);
d.real("Scribbliness", num(p, "curviness")? / 100.0);
d.real("ScribbleVariation", num(p, "curvinessVariation")? / 100.0);
d.real("Spacing", num(p, "spacing")?);
d.real("SpacingVariation", num(p, "spacingVariation")?);
"Adobe Scribble Fill" // brand-ok: the filter's name in the files
}
_ => return None,
})
}
/// Convert to Shape's, a Path effect's or Pathfinder › Add's entries ([`Self::effect_filter`])
/// and its filter's name.
fn path_entries(id: &str, p: &Value, d: &mut Entries) -> Option<&'static str> {
Some(match id {
"convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" => {
let shape = match id {
"convertToShape.rectangle" => 0,
"convertToShape.roundedRectangle" => 1,
_ => 2,
};
let relative = flag(p, "relative")?;
d.int("Shape", shape);
d.real("Absolute", if relative { 0.0 } else { 1.0 });
d.real("AbsWidth", num(p, "width")?);
d.real("AbsHeight", num(p, "height")?);
d.real("RelWidth", num(p, "extraW")? / 2.0);
d.real("RelHeight", num(p, "extraH")? / 2.0);
if shape == 1 {
d.real("CornerRadius", num(p, "radius")?);
}
"Adobe Shape Effects" // brand-ok: the filter's name in the files
}
"path.offsetPath" => {
d.real("ofst", num(p, "offset")?);
let joins = match word(p, "joins")?.as_str() {
"round" => 0,
"bevel" => 1,
"miter" => 2,
_ => return None,
};
d.int("jntp", joins);
d.real("mlim", num(p, "miterLimit")?);
"Adobe Offset Path" // brand-ok: the filter's name in the files
}
"path.outlineObject" => "Adobe Outline Type", // brand-ok: the filter's name in the files
"path.outlineStroke" => "Adobe Outline Stroke", // brand-ok: the filter's name in the files
"pathfinder.add" => {
d.int("Command", 0);
d.bool("ConvertCustom", true);
d.bool("ExtractUnpainted", true);
d.real("Mix", 0.5);
d.real("Precision", 10.0);
d.bool("RemovePoints", false);
d.real("TrapAspect", 1.0);
d.bool("TrapConvertCustom", false);
d.real("TrapMaxTint", 1.0);
d.bool("TrapReverse", false);
d.real("TrapThickness", 0.25);
d.real("TrapTint", 0.4);
d.real("TrapTintTolerance", 0.05);
"Adobe Pathfinder" // brand-ok: the filter's name in the files
}
_ => return None,
})
}
/// The style object `orig` (`n` before baking) is written with; `None` when the reader wouldn't
/// read the object as it is with it. A gradient fill is placed on `n`'s outline, as the object
/// draws it. A style that isn't written leaves no gradient definition or warning behind.
pub(super) fn object_style(&mut self, n: &Node, orig: &Node) -> Option<String> {
if let NodeKind::Group { children, .. } = &orig.kind
&& bakes_members(orig)
&& !children.iter().all(|c| self.member_keeps_outline(c))
{
return None;
}
let graded = orig.appearance.items.iter().any(|i| matches!(i.paint(), Paint::Gradient(_)));
let saved = (graded.then(|| self.gradient_mark()), self.warnings.len());
let path = drawn_outline(n, orig);
let rule = object_rule(orig);
let text = self.style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))).filter(|t| object_reads(orig, t));
let Some(text) = text else {
if let Some(mark) = saved.0 {
self.gradient_rollback(mark);
}
self.warnings.truncate(saved.1);
return None;
};
Some(self.styles.object_style(text))
}
/// Is member `m` of a styled group whose effects change its members' outlines (and each of its
/// own members) written on the outline those effects draw on: every fill and stroke as the
/// object paints it ([`Self::direct`], [`Self::direct_stroke`]), not as filled outlines, brush
/// art or pattern tiles, and no gradient that fits its object, which the effects would fit to
/// the new outline?
fn member_keeps_outline(&self, m: &Node) -> bool {
let items_keep = m.appearance.items.iter().all(|i| match i {
AppearanceItem::Fill(f) => f.paint.is_none() || self.direct(&f.paint),
AppearanceItem::Stroke(s) => s.paint.is_none() || self.direct_stroke(s),
});
items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c)))
}
/// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and
/// hidden state; its drawn look (a group of its vector art as baking left it, without shadows,
/// glows or feathers, the object's transparency
/// after the group's end, `0 0 Xd`, `6 () XW`); the object itself on `%_` lines (a path's or
/// compound path's points painted with nothing, or with its gradient fill when its style has
/// one; a group with its members), its name and opacity mask; then `1 (name) XW`.
pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) {
self.state(orig.locked, !orig.visible);
let xy = Xy::of(orig);
let was = self.in_look;
self.in_look = true;
self.line("u");
let mut look = n.clone();
(look.name, look.opacity, look.blend, look.isolate, look.knockout, look.knockout_shape) =
(None, 1.0, BlendMode::Normal, false, Knockout::Neutral, false);
if look.extras().mask.is_some() {
look.extras_mut().mask = None;
}
match &look.kind {
NodeKind::Group { children, clip: false } => {
for c in children.clone() {
self.node(&c);
}
}
_ => self.node(&look),
}
self.line("U");
self.write_xy(xy);
self.line("0 0 Xd\n6 () XW");
self.in_look = was;
// The object, on `%_` lines, in its own state (the look's members may have changed it).
self.state(orig.locked, !orig.visible);
let saved = std::mem::take(&mut self.body);
self.hidden += 1;
let fit = drawn_outline(n, orig).map(|p| p.bounding_box());
match &orig.kind {
NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy),
NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy),
NodeKind::Group { children, .. } => {
self.line("u");
for c in children {
self.node(c);
}
self.line("U");
}
_ => {}
}
self.dictionary(orig);
self.hidden -= 1;
let part = std::mem::replace(&mut self.body, saved);
hide(&part, &mut self.body);
self.block_end = usize::MAX;
let _ = writeln!(self.body, "1 {} XW", ps::bytes(name.as_bytes()));
}
/// A styled path's or compound path's points: painted with nothing, or with its gradient fill
/// (which its style's gradient fill is), placed on `fit` (the outline's bounds when `None`).
fn styled_outline(&mut self, orig: &Node, path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule, fit: Option<Rect>, xy: Xy) {
let bounds = fit.unwrap_or_else(|| path.to_bezpath().bounding_box());
let gradient = orig.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) if matches!(f.paint, Paint::Gradient(_)) => Some(f),
_ => None,
});
match gradient {
Some(f) => {
let fill = FillLayer { paint: self.placed(&f.paint, bounds), ..f.clone() };
self.plain_object(path, rule, Some(&fill), None, xy.object());
}
None => self.plain_object(path, rule, None, None, xy.object()),
}
}
/// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style,
/// `%AI9_EndArtStyles`.
pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) {
if self.styles.known.is_empty() {
return;
}
s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n");
for (name, text) in &self.styles.known {
s.push_str(&known_style(name, text));
}
s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n");
}
}
/// The outline a path's or compound path's style places a gradient fill on.
fn object_outline(n: &Node) -> Option<BezPath> {
match &n.kind {
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
NodeKind::Compound { .. } => Some(compound_path(n).to_bezpath()),
_ => None,
}
}
/// The outline a styled path or compound path draws: `n`'s, as baking left it, when it is still a
/// path or compound path, else `orig`'s.
fn drawn_outline(n: &Node, orig: &Node) -> Option<BezPath> {
object_outline(orig)?;
object_outline(n).or_else(|| object_outline(orig))
}
/// The fill rule of a path or compound path (a group's is the default).
fn object_rule(n: &Node) -> FillRule {
match &n.kind {
NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule,
_ => FillRule::NonZero,
}
}
/// Does the reader read object `n` written with style text `text` as it is: a path or compound
/// path with a style it reads on any object, filled by the non-zero rule when the style fills it,
/// or a group with no fills or strokes of its own?
fn object_reads(n: &Node, text: &str) -> bool {
let section = known_style("x", text);
let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_)));
let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false };
let group = matches!(n.kind, NodeKind::Group { .. });
if !read.simple || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) {
return false;
}
if !group {
let filled = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && !i.paint().is_none());
if filled && object_rule(n) == FillRule::EvenOdd {
return false;
}
// A path's contents are nothing: the reader keeps the object's own.
read.appearance.contents_index = n.appearance.contents_index;
}
same_appearance(&read.appearance, &n.appearance)
}
/// Do appearances `a` and `b` draw the same, as the reader reads one written from the other: the
/// fills and strokes that paint, within the written numbers' precision, and the effects with
/// their settings filled in from their defaults (blending modes in any case, colors as colors).
pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) -> bool {
let norm = |ap: &Appearance| -> Value {
let mut ap = ap.clone();
let ci = ap.contents_index.unwrap_or(0).min(ap.items.len());
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
ap.items.retain(|i| !i.paint().is_none());
ap.contents_index = (below > 0).then_some(below);
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
e.params = normalized_params(e);
}
serde_json::to_value(&ap).unwrap_or(Value::Null)
};
near(&norm(a), &norm(b))
}
/// Effect `e`'s settings with its defaults filled in, its blending mode in lower case and its color as
/// `#rrggbb`.
fn normalized_params(e: &Effect) -> Value {
let mut p = vectorcraft_effects::merged_params(&e.id, &e.params);
if let Some(m) = word(&p, "mode") {
p["mode"] = Value::String(m);
}
if p.get("color").is_some() {
p["color"] = Value::String(vectorcraft_effects::color_param(&p, vectorcraft_color::Color::BLACK).to_hex());
}
for key in ["shade", "source", "joins", "points", "orientation"] {
if let Some(w) = word(&p, key) {
p[key] = Value::String(w);
}
}
p
}
/// How far apart two numbers may read in [`near`]: a number written to 4 decimals, then converted
/// from a fraction to a percentage (`5e-3`) or from radians to degrees (`3e-3`).
const NEAR: f64 = 6e-3;
/// JSON values equal but for numbers within the written numbers' precision.
fn near(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
(Some(x), Some(y)) => (x - y).abs() <= NEAR,
_ => x == y,
},
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| near(x, y)),
(Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, v)| y.get(k).is_some_and(|w| near(v, w))),
_ => a == b,
}
}
+1 -1
View File
@@ -70,7 +70,7 @@ use graphics::{GState, Out};
use interp::{Fault, Interp};
use obj::PsError;
pub(crate) use ai::{MAX_GRADIENT_STOPS, MAX_SYMBOLS, symbol_art_member};
pub(crate) use ai::{MAX_GRADIENT_STOPS, MAX_SYMBOLS, read_art_style, symbol_art_member};
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from};
pub(crate) use native::{MAX_TEXT, scale_document};
+1 -1
View File
@@ -41,7 +41,7 @@ pub use read::{
BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, graphic_styles, palette, read, read_beside,
variables,
};
pub(crate) use read::{MAX_SYMBOLS, join_and, slot_frame, slot_of, symbol_art_member};
pub(crate) use read::{MAX_SYMBOLS, join_and, read_art_style, slot_frame, slot_of, symbol_art_member};
pub(crate) use read::is_look_slot;
+1
View File
@@ -136,6 +136,7 @@ pub(crate) use art::join_and;
use art::preview_png;
pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, graphic_styles, palette, variables};
pub(crate) use document::{slot_frame, slot_of};
pub(crate) use ops::read_art_style;
pub use types::IMAGE_TOO_LARGE;
use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster, SymbolHead};
#[cfg(test)]
+31
View File
@@ -1121,6 +1121,37 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle)
Some(Appearance { items, effects: st.effects.clone(), contents_index: st.contents_index })
}
/// What the reader makes of art style `name` in `section` (the text between `%AI9_BeginArtStyles`
/// and its end), for writers that check a style before they write it.
#[derive(Clone, Debug)]
pub(crate) struct StyleRead {
/// The style's appearance: a gradient fill is the object's own gradient.
pub appearance: Appearance,
/// An object other than type is read with it ([`crate::import::ai::style::ArtStyle::simple`]).
pub simple: bool,
/// It has Effect › Pathfinder effects, which only a group with no fills or strokes is read with.
pub pathfinder: bool,
}
/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`],
/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads
/// it on objects other than type. `None` when the section doesn't define it, the reader doesn't read
/// it, or it paints with a pattern, a brush or a gradient that isn't the object's own.
pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option<StyleRead> {
use crate::import::ai::style::StyleItem;
let mut st = crate::import::ai::style::art_styles(section).remove(name)?;
if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 {
let own = own_gradient?;
for item in &mut st.items {
if matches!(item, StyleItem::Gradient { .. }) {
*item = StyleItem::Fill(own.clone());
}
}
}
let appearance = appearance_from_art_style(&st)?;
Some(StyleRead { appearance, simple: st.simple, pathfinder: st.pathfinder })
}
/// A style's stroke as an appearance item (`None` for a fill).
fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option<AppearanceItem> {
let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, brush } = item else { return None };
+29
View File
@@ -1186,3 +1186,32 @@ fn convert_to_shape_settings_that_arent_read_keep_the_drawn_look() {
format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", &[compound("Stack Style Filter", &[item])]));
assert!(!art_styles(data.as_bytes())["Odd"].plain);
}
/// A style as a writer checks it: the reader's appearance, with a gradient fill as the object's own,
/// and nothing for styles it doesn't read.
#[test]
fn a_style_is_read_as_a_writer_checks_it() {
let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own);
let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids));
let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB");
let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient));
let data = style(&[stack, blend(1, 0.5)]);
let own = Paint::solid(vectorcraft_color::Color::WHITE);
let got = read(&data, Some(&own)).unwrap();
assert_eq!(got.appearance.items.len(), 1);
assert_eq!(got.appearance.items[0].paint(), &own);
assert!(got.simple && !got.pathfinder);
// A gradient that isn't the object's own, a pattern, another name, two gradients: nothing.
assert!(read(&data, None).is_none());
let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]);
assert!(read(&pattern, None).is_none());
assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none());
assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none());
// Damaged text: every cut of the style, and stray bytes, without a panic.
for cut in 0..data.len() {
let _ = read(data.get(..cut).unwrap_or_default(), Some(&own));
}
for junk in ["(", ")", ";", "/KnownStyle :\n(Odd) /Name ,\n;;;;", "/KnownStyle :\n(Odd) /Name ,\n/Array : 1 /Real , ; (x) ,"] {
let _ = read(junk, Some(&own));
}
}
+11 -2
View File
@@ -85,7 +85,15 @@ private editing data. VectorCraft:
instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art, pattern fills in a
symbol's art are written as their tiles cut to the shape, symbols past 4,096 are written only as their
instances' art, and symbols' 9-slice guides, export types and dynamic type are left out, each with a
warning.
warning. Paths, compound paths and groups with live effects keep them as art styles: the drawn look, the object
itself and the style it names, for a fill and a stroke at most in solid colors or the object's gradient (a stroke
with its variable-width profile), filled by the non-zero rule, with Drop Shadow, Inner Glow, Outer Glow, Feather,
Round Corners, Scribble, Convert to Shape, Offset Path, Outline Object or Outline Stroke, and groups with Pathfinder ›
Add. Groups keep them when their members are paths, compound paths or such groups, without effects of their own; when the
group's effects change its members' outlines, a member's strokes are plain lines, and its fills are not pattern
fills written as tiles or gradients that fit their object. The look holds the object's vector art, without the shadow, glow or feather. Other objects are
written as their drawn look with a warning. Graphic styles and links to them are left out with a warning. No art style is written 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,
@@ -100,7 +108,8 @@ private editing data. VectorCraft:
color, each with a warning. Gradients that dither or mix their colors perceptually are written as classic
gradients, and gradient stops linked to global process colors as their colors, each with a warning. The opacity
and blending mode of single fills and strokes, opacity masks on layers, the placement of pattern swatches that
move, turn or scale their pattern, and effects other than geometry effects are left out.
move, turn or scale their pattern, and the effects of objects written without an art style, other than geometry
effects, are left out.
- **Writes** a legacy `.ai` of version 7 (Save As › `ai` › Version: Legacy (version 7), `aiVersion: "7"`): the
PostScript form, from the published *Adobe Illustrator File Format Specification* version 7.0
([PRONOM fmt/423](https://www.nationalarchives.gov.uk/PRONOM/fmt/423)), which apps reading `.ai` open with its