Merge main into feat/stylus-wheel

This commit is contained in:
dotCooCoo
2026-11-13 08:11:32 -08:00
150 changed files with 10189 additions and 1008 deletions
+445 -1
View File
@@ -1038,7 +1038,7 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() {
/// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound
/// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks,
/// gradients, pattern definitions and tiles, images, type, symbol definitions and instances,
/// objects with art styles and objects bound to variables.
/// objects with art styles, objects bound to variables and live envelopes.
fn counted() -> Vec<(&'static str, Document)> {
vec![
("sample", sample()),
@@ -1053,6 +1053,7 @@ fn counted() -> Vec<(&'static str, Document)> {
("painted clips", painted_clips()),
("blend", blend_doc()),
("brushes", brushes_document()),
("envelopes", envelopes_document()),
]
}
@@ -9068,3 +9069,446 @@ fn spread_gradients_past_the_stops_the_reader_reads_stay_gradients() {
let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") };
assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&swatch.gradient.stops.len()), "{} stops", swatch.gradient.stops.len());
}
/// An envelope named `Bent` of `kind` around a red rectangle (40, 20)-(100, 80) and a blue one
/// (100, 20)-(160, 80), with Fidelity `fidelity`, Edit Contents `editing` and `options`.
fn envelope_node(
doc: &mut Document,
kind: vectorcraft_doc::live::EnvelopeKind,
fidelity: f64,
editing: bool,
options: vectorcraft_doc::live::EnvelopeOptions,
) -> Node {
let content = vec![
Arc::new(square(doc, Rect::new(40.0, 20.0, 100.0, 80.0), Color::rgb(1.0, 0.0, 0.0))),
Arc::new(square(doc, Rect::new(100.0, 20.0, 160.0, 80.0), Color::rgb(0.0, 0.0, 1.0))),
];
let kind = NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() };
named(Node::new(doc.alloc_id(), kind), "Bent")
}
/// A 200 × 100 document of envelope `kind` ([`envelope_node`]) alone.
fn envelope_doc(
kind: vectorcraft_doc::live::EnvelopeKind,
fidelity: f64,
editing: bool,
options: vectorcraft_doc::live::EnvelopeOptions,
) -> Document {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let envelope = envelope_node(&mut doc, kind, fidelity, editing, options);
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
doc
}
/// A grid of `rows`×`cols` patches over (30, 10)-(170, 90), row by row from the top left, with its
/// sixth point moved.
fn envelope_points(rows: u32, cols: u32) -> Vec<kurbo::Point> {
let mut points: Vec<kurbo::Point> = (0..=rows)
.flat_map(|r| {
(0..=cols).map(move |c| kurbo::Point::new(30.0 + 140.0 * f64::from(c) / f64::from(cols), 10.0 + 80.0 * f64::from(r) / f64::from(rows)))
})
.collect();
points[5] += kurbo::Vec2::new(5.0, -8.0);
points
}
/// The envelopes written live: warps (vertical, with distortions, and twisted), meshes (with
/// handles of their own, one handle uneven, and with the smooth ones), top objects (a curved top
/// side, and two segments to the top and bottom sides), with Edit Contents off and on.
fn live_envelope_kinds() -> Vec<(&'static str, vectorcraft_doc::live::EnvelopeKind)> {
use vectorcraft_doc::live::{EnvelopeKind, H_RIGHT, WARP_NET, smooth_handles};
let warp = |style: &str, bend: f64, h: f64, v: f64, horizontal: bool| EnvelopeKind::Warp {
style: style.into(),
bend,
h,
v,
horizontal,
version: WARP_NET,
};
let points = envelope_points(2, 3);
let mut handles = smooth_handles(2, 3, &points);
handles[5][H_RIGHT] += kurbo::Vec2::new(4.0, 6.0);
let mut curved = kurbo::BezPath::new();
curved.move_to((30.0, 10.0));
curved.curve_to((70.0, -5.0), (130.0, -5.0), (170.0, 10.0));
curved.line_to((170.0, 90.0));
curved.line_to((30.0, 90.0));
curved.close_path();
let mut six = kurbo::BezPath::new();
six.move_to((30.0, 10.0));
for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (100.0, 95.0), (30.0, 90.0)] {
six.line_to(p);
}
six.close_path();
vec![
("arc", warp("arc", 50.0, -20.0, 30.0, false)),
("twist", warp("twist", -35.0, 0.0, 0.0, true)),
("mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles }),
("smooth mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points, handles: vec![] }),
("curved top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&curved), corners: None }),
("six-anchor top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&six), corners: None }),
]
}
/// `doc` written and read back from its editing data: the top object on its first layer, the
/// writer's warnings and the reader's notes.
fn envelope_back(doc: &Document) -> (Node, Vec<String>, Vec<String>) {
let (p, warnings) = private_data(doc, &opts()).unwrap();
let (back, notes) = crate::ai_alone(&p.data).unwrap();
let a = back.layers[0].children().unwrap();
assert_eq!(a.len(), 1, "{a:#?}");
((*a[0]).clone(), warnings, notes)
}
/// Does reopened envelope kind `got` have the shape of `want`: a warp's style, bend, distortions
/// and orientation; a mesh's grid and the handles that draw (those inside the grid); the patch a top
/// object's outline makes?
fn same_envelope_kind(want: &vectorcraft_doc::live::EnvelopeKind, got: &vectorcraft_doc::live::EnvelopeKind) -> bool {
use vectorcraft_doc::live::{Coons, EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, smooth_handles};
let near = |a: kurbo::Point, b: kurbo::Point| a.distance(b) < 1e-3;
match (want, got) {
(
EnvelopeKind::Warp { style, bend, h, v, horizontal, version },
EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal: hz, version: ver },
) => style == s && horizontal == hz && version == ver && [(bend, b), (h, dh), (v, dv)].iter().all(|(x, y)| (*x - *y).abs() < 1e-9),
(EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { rows: r, cols: c, points: p, handles: hs }) => {
let own = if handles.is_empty() { smooth_handles(*rows, *cols, points) } else { handles.clone() };
let inside = |i: usize, slot: usize| {
let (row, col) = (i / (*cols as usize + 1), i % (*cols as usize + 1));
match slot {
s if s == H_LEFT => col > 0,
s if s == H_RIGHT => col < *cols as usize,
s if s == H_UP => row > 0,
s if s == H_DOWN => row < *rows as usize,
_ => false,
}
};
(rows, cols) == (r, c)
&& points.len() == p.len()
&& points.iter().zip(p).all(|(a, b)| near(*a, *b))
&& own.iter().zip(hs).enumerate().all(|(i, (a, b))| (0..4).all(|s| !inside(i, s) || near(a[s].to_point(), b[s].to_point())))
}
(EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) => {
let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false };
(0..=8).all(|j| {
(0..=8).all(|i| a.eval(f64::from(i) / 8.0, f64::from(j) / 8.0).distance(b.eval(f64::from(i) / 8.0, f64::from(j) / 8.0)) < 1e-2)
})
}
_ => false,
}
}
/// A PDF-compatible `.ai`'s editing data keeps a warp, a mesh and a top object envelope live, with
/// Edit Contents off and on: VectorCraft's reader opens each as the same envelope, its contents,
/// Fidelity, Edit Contents, Envelope Options and shape as saved, and its name, the drawn art saved
/// with it drawing as the envelope does.
#[test]
fn envelopes_are_read_back_live() {
use vectorcraft_doc::live::EnvelopeOptions;
for (name, kind) in live_envelope_kinds() {
for editing in [false, true] {
let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW);
let (back, warnings, notes) = envelope_back(&doc);
let what = format!("{name}, editing {editing}");
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}");
let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") };
assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}");
assert!(same_envelope_kind(&kind, got), "{what}: {got:?}");
assert_eq!(back.name.as_deref(), Some("Bent"), "{what}");
let colors: Vec<Option<Color>> = content.iter().map(|c| c.appearance.fill_paint().color()).collect();
assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}");
// Saved again as it opened (a top object now with the corners the file gives it), it
// opens as the same envelope again.
let mut again = Document::new(200.0, 100.0);
let layer = again.layers[0].id;
again.insert(Some(layer), usize::MAX, back.clone()).unwrap();
let (twice, warnings, notes) = envelope_back(&again);
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}");
let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") };
assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}");
}
}
}
/// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol
/// opens with it as a live envelope.
#[test]
fn an_envelope_in_a_symbol_is_read_back_live() {
use vectorcraft_doc::live::EnvelopeOptions;
let kinds = live_envelope_kinds();
for (name, kind) in kinds {
let mut doc = Document::new(200.0, 100.0);
let art = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW);
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) });
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, instance).unwrap();
let (p, warnings) = private_data(&doc, &opts()).unwrap();
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{name}: {warnings:?}");
let (back, notes) = crate::ai_alone(&p.data).unwrap();
let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols));
let mut envelopes = vec![];
symbol.art.walk(&mut |n| {
if let NodeKind::Envelope { kind, .. } = &n.kind {
envelopes.push((**kind).clone());
}
});
assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}");
}
}
/// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows
/// the envelope's dictionary rather than its mask's art.
#[test]
fn an_envelope_with_an_opacity_mask_is_read_back_live() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
let mut doc = Document::new(200.0, 100.0);
let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW);
let gray = square(&mut doc, Rect::new(40.0, 20.0, 160.0, 80.0), Color::gray(0.5));
let art = group(&mut doc, vec![gray], false);
envelope.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
let text = program(&doc);
let (xp, mask) = (text.find(") 1 0 0 XP").unwrap_or(0), text.find("(AI9_Mask)").unwrap_or(usize::MAX));
assert!(mask < xp, "{text}");
let (back, warnings, notes) = envelope_back(&doc);
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
assert!(same_envelope_kind(&kind, got), "{got:?}");
assert!(back.extras().mask.is_some(), "{back:#?}");
}
/// As many envelopes are written live as the reader checks in one file, and the ones after them
/// as their art, with a warning.
#[test]
fn envelopes_past_the_readers_checks_are_written_as_their_art() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let limit = crate::import::ENVELOPE_CHECKS;
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
for _ in 0..=limit {
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
}
let (p, warnings) = private_data(&doc, &opts()).unwrap();
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
let (back, notes) = crate::ai_alone(&p.data).unwrap();
let a = back.layers[0].children().unwrap();
let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count();
assert_eq!((a.len(), live), (limit + 1, limit), "{notes:?}");
assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
}
/// Every Envelope Options switch and the ends of Fidelity come back as saved.
#[test]
fn envelope_options_and_fidelity_are_read_back() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
let new = EnvelopeOptions::NEW;
let all = [
(new, 50.0),
(EnvelopeOptions { anti_alias: false, ..new }, 0.0),
(EnvelopeOptions { preserve_shape: PreserveShape::Transparency, ..new }, 100.0),
(EnvelopeOptions { distort_linear_gradients: true, distort_pattern_fills: true, ..new }, 30.0),
(EnvelopeOptions { distort_appearance: false, ..new }, 50.0),
];
for (options, fidelity) in all {
let (back, _, notes) = envelope_back(&envelope_doc(kind.clone(), fidelity, false, options));
let NodeKind::Envelope { options: o, fidelity: f, .. } = &back.kind else { panic!("{options:?}: {back:#?} {notes:?}") };
assert_eq!((*o, *f), (options, fidelity));
}
}
/// With Distort Appearance, an envelope whose contents map from their bounds with their strokes
/// saves that box's size, and opens mapping from the same box.
#[test]
fn an_envelope_mapping_from_its_contents_strokes_is_read_back() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin};
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let mut envelope = envelope_node(
&mut doc,
EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] },
50.0,
false,
EnvelopeOptions::NEW,
);
let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() };
for c in content.iter_mut() {
let fill = Arc::make_mut(c).appearance.fill_paint();
Arc::make_mut(c).appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into();
}
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap();
options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap();
let margin = options.bounds_margin;
assert!(margin.iter().all(|m| *m > 0.0), "{margin:?}");
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
let (back, warnings, notes) = envelope_back(&doc);
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin);
}
/// A test's stand-in for a node that must be an envelope.
fn unreachable_envelope() -> ! {
panic!("not an envelope")
}
/// The record is written in the order the reader reads it: on `%_` lines the group holding the
/// grid, its dictionary with the options, the contents' block and the kind, then the distorted art
/// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and
/// the dictionary the grid.
#[test]
fn an_envelope_is_written_in_the_order_the_reader_reads_it() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
for editing in [false, true] {
let text = program(&envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW));
let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("{s} missing: {text}"));
let (group, mesh, dictionary, block, key, style, xp) = (
at("%_u\n"),
at("%_/Mesh X!"),
at("%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n"),
at("%_X=\n"),
at("%_ (AIDeformArtKey) ,\n"),
at("%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\n"),
at("(Adobe Deform Plugin) 1 0 0 XP\n"),
);
assert!(group < dictionary && dictionary < block && block < key && key < style && style < xp, "{text}");
assert_eq!(block < mesh, editing, "{text}");
assert!(text.contains(&format!("%_{} /Bool (AIDeformEditModeKey) ,\n", u8::from(editing))), "{text}");
// The distorted art is one group on plain lines, named as the envelope, right before the `XP`.
let drawn = &text[style..xp];
assert!(drawn.contains("\nu\n") && drawn.contains("(Bent) ; (AI10_ArtUID) ,"), "{drawn}");
// The contents are on `%_` lines only: drawn once on plain lines, as the distorted art.
assert_eq!(text.matches("(Adobe Deform Plugin)").count(), 1, "{text}");
}
}
/// Envelopes the reader would open in another shape, or not at all, are written as their distorted
/// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn
/// without its style's net, a mesh the reader would lay out the other way round, a top object
/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with
/// Distort Appearance off. Other live objects keep their own warning.
#[test]
fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let base =
|| envelope_doc(EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, 50.0, false, EnvelopeOptions::NEW);
let change = |f: &dyn Fn(&mut NodeKind)| {
let mut doc = base();
let id = doc.layers[0].children().unwrap()[0].id;
f(&mut doc.node_mut(id).unwrap().kind);
doc
};
let typed = change(&|k| {
if let NodeKind::Envelope { content, .. } = k {
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(50.0, 50.0), "Type", vectorcraft_doc::CharStyle::default());
content.push(Arc::new(Node::new(vectorcraft_doc::NodeId(9_000), NodeKind::Text(Box::new(t)))));
}
});
let turned = change(&|k| {
if let NodeKind::Envelope { frame, .. } = k {
**frame = Affine::rotate(0.3);
}
});
let old_warp = change(&|k| {
if let NodeKind::Envelope { kind, .. } = k {
**kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
}
});
// Columns down the page and rows across: the reader turns the grid round.
let sideways = change(&|k| {
if let NodeKind::Envelope { kind, .. } = k {
let points =
(0..=3).flat_map(|r| (0..=2).map(move |c| kurbo::Point::new(30.0 + 70.0 * f64::from(c), 10.0 + 80.0 * f64::from(r) / 3.0))).collect();
**kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] };
}
});
let mut uneven = kurbo::BezPath::new();
uneven.move_to((30.0, 10.0));
for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] {
uneven.line_to(p);
}
uneven.close_path();
let lopsided = change(&|k| {
if let NodeKind::Envelope { kind, .. } = k {
**kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None };
}
});
let fractional = change(&|k| {
if let NodeKind::Envelope { fidelity, .. } = k {
*fidelity = 50.5;
}
});
let margin_kept = change(&|k| {
if let NodeKind::Envelope { options, .. } = k {
options.distort_appearance = false;
options.bounds_margin = [0.5; 4];
}
});
let cases = [
("type", typed),
("turned", turned),
("old warp", old_warp),
("sideways mesh", sideways),
("lopsided top object", lopsided),
("fractional fidelity", fractional),
("margin kept", margin_kept),
];
for (what, doc) in cases {
let text = program(&doc);
assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}");
let (back, warnings, _) = envelope_back(&doc);
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
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);
}
/// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`.
fn transpose(points: Vec<kurbo::Point>, rows: usize, cols: usize) -> Vec<kurbo::Point> {
(0..=cols).flat_map(|c| (0..=rows).map(move |r| (r, c))).map(|(r, c)| points[r * (cols + 1) + c]).collect()
}
/// An envelope with its contents in an opacity mask's art is written as its art there, and an
/// envelope in a group stays live.
#[test]
fn envelopes_in_masks_are_written_as_their_art_and_in_groups_stay_live() {
let doc = envelopes_document();
let (p, warnings) = private_data(&doc, &opts()).unwrap();
let (back, notes) = crate::ai_alone(&p.data).unwrap();
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
let mut live = 0;
back.walk(|n| live += usize::from(matches!(n.kind, NodeKind::Envelope { .. })));
assert_eq!(live, 3, "{notes:?}");
}
/// A warp, a mesh envelope with its contents edited, a top object in a group, and an envelope in an
/// opacity mask's art.
fn envelopes_document() -> Document {
use vectorcraft_doc::live::EnvelopeOptions;
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let kinds = live_envelope_kinds();
let kind = |name: &str| kinds.iter().find(|(n, _)| *n == name).map(|(_, k)| k.clone()).unwrap();
let warp = envelope_node(&mut doc, kind("arc"), 50.0, false, EnvelopeOptions::NEW);
let mesh = envelope_node(&mut doc, kind("mesh"), 50.0, true, EnvelopeOptions::NEW);
let top = envelope_node(&mut doc, kind("six-anchor top object"), 50.0, false, EnvelopeOptions::NEW);
let top = group(&mut doc, vec![top], false);
let mut masked = square(&mut doc, Rect::new(0.0, 0.0, 200.0, 100.0), Color::gray(0.5));
let mask_art = envelope_node(&mut doc, kind("twist"), 50.0, false, EnvelopeOptions::NEW);
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
for n in [warp, mesh, top, masked] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
doc
}
+41 -21
View File
@@ -16,6 +16,7 @@ use crate::ai_ops::{self, unit};
use crate::ps;
mod brushes;
mod envelopes;
mod images;
mod paints;
mod styles;
@@ -25,6 +26,8 @@ mod variables;
#[cfg(test)]
pub(super) use brushes::BRUSHES;
#[cfg(test)]
pub(super) use envelopes::ENVELOPES;
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects};
#[cfg(test)]
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance};
@@ -52,8 +55,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, envelopes, meshes, repeats, placed documents and intertwines are written as their art 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 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 =
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
@@ -262,6 +264,12 @@ pub(super) struct Writer<'a> {
brush_set: brushes::Brushes,
/// Brushes may be written; false on a large canvas, where they are left out.
pub(super) brushes_live: bool,
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
/// ([`Self::envelope`]).
deform: bool,
/// How many more envelopes may be written live: as many as the reader checks in one file
/// ([`crate::import::ENVELOPE_CHECKS`]).
envelopes_left: usize,
}
impl<'a> Writer<'a> {
@@ -319,6 +327,8 @@ impl<'a> Writer<'a> {
in_look: false,
brush_set: brushes::Brushes::default(),
brushes_live: true,
deform: false,
envelopes_left: crate::import::ENVELOPE_CHECKS,
objects: 0,
left_out: 0,
definition_objects: 0,
@@ -694,29 +704,16 @@ impl<'a> Writer<'a> {
}
self.end_group("U", xy);
}
NodeKind::Blend { .. }
| NodeKind::Envelope { .. }
| NodeKind::Mesh(_)
| NodeKind::Repeat(_)
| NodeKind::PlacedDocument(_)
| NodeKind::Intertwine { .. } => {
if !self.open_group("u") {
return;
}
self.warn(LIVE);
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
self.nest += 1;
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
self.node(c);
}
self.nest -= 1;
}
self.end_group("U", xy);
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)),
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
self.drawn_art(n, xy, Some(LIVE));
}
// Ruler guides are kept in the document's native copy only.
NodeKind::RulerGuide { .. } => {}
}
// Taken before the dictionary, whose opacity mask art may hold envelopes of its own.
let deform = std::mem::take(&mut self.deform);
if self.body.len() > start {
// A group's dictionary goes between its end and its state block.
let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start));
@@ -726,6 +723,29 @@ impl<'a> Writer<'a> {
self.body.push_str(&b);
}
}
// An envelope's plugin `XP` follows its distorted art, after the art's state block.
if deform {
self.line(&envelopes::plugin_line());
}
}
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) {
if !self.open_group("u") {
return;
}
if let Some(w) = warning {
self.warn(w);
}
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
self.nest += 1;
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
self.node(c);
}
self.nest -= 1;
}
self.end_group("U", xy);
}
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
@@ -0,0 +1,395 @@
//! Envelopes (see [`crate::ai_editing`] for the form), written in the form VectorCraft's `.ai`
//! reader opens as live envelopes again: on `%_` lines a group holding the grid that shapes the
//! envelope (while its contents are edited, the contents), then that group's `/ArtDictionary` with
//! Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity (`AIDeformFidelityKey`), Edit
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another
//! shape is written as its distorted art.
use std::fmt::Write;
use std::sync::Arc;
use kurbo::{Point, Vec2};
use vectorcraft_doc::live::{
Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes,
envelope_grid, envelope_stroke_margin, warp_grid,
};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_geom::{Affine, PathData};
use super::{MAX_NEST, Writer, Xy, hide};
use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number};
use crate::ps;
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the
/// reader's).
const MAX_GRID: usize = 50;
/// How far, as a share of the diagonal of a top object's patch, the patch on the outline written for
/// it may lie from its own at any of the places checked.
const TOP_OBJECT_TOLERANCE: f64 = 1e-6;
/// How far apart two bounds margins may be and still count as the same.
const MARGIN_SLACK: f32 = 1e-5;
/// What an envelope's dictionary holds besides its contents: the entries before the contents' block,
/// each on a line of its own, the kind (`AIDeformStyle`) and the grid that shapes it (`rows`, `cols`
/// and its points with their handles, row by row from the top left, in the document), when it has
/// one.
struct Record {
keys: String,
style: u8,
grid: Option<(usize, usize, Vec<GridPoint>)>,
}
/// The `XP` that ends an envelope, after its distorted art.
pub(super) fn plugin_line() -> String {
format!("{} 1 0 0 XP", ps::bytes(DEFORM_PLUGIN.as_bytes()))
}
/// Does `n`, or anything in it, hold type?
fn holds_type(n: &Node) -> bool {
matches!(n.kind, NodeKind::Text(_)) || n.children().is_some_and(|c| c.iter().any(|k| holds_type(k)))
}
/// The record of envelope `n` (its parts given), or `None` where the reader would open it in
/// another shape than it has, or not as an envelope.
fn record(
n: &Node,
content: &[Arc<Node>],
kind: &EnvelopeKind,
fidelity: f64,
editing: bool,
options: &EnvelopeOptions,
frame: Affine,
) -> Option<Record> {
// The reader reads Fidelity as a whole number from 0 to 100, and bounds margins only with
// Distort Appearance on.
let whole = (0.0..=100.0).contains(&fidelity) && fidelity.fract() == 0.0;
let margin_kept = !options.distort_appearance && options.bounds_margin != [0.0; 4];
if content.is_empty() || frame != Affine::IDENTITY || !whole || margin_kept || content.iter().any(|c| holds_type(c)) {
return None;
}
let mut keys = String::new();
let bit = |on: bool, at: u32| i64::from(on) << at;
let word = bit(options.distort_appearance, 0)
| bit(options.distort_pattern_fills, 1)
| bit(options.distort_linear_gradients, 2)
| bit(!options.anti_alias, 16)
| bit(options.preserve_shape == PreserveShape::ClippingMask, 17);
let _ = writeln!(keys, "{word} /Int (AIDeformOptionsKey) ,");
let _ = writeln!(keys, "{} /Int (AIDeformFidelityKey) ,", fidelity as i64);
let _ = writeln!(keys, "{} /Bool (AIDeformEditModeKey) ,", u8::from(editing));
let real = |keys: &mut String, v: f64, key: &str| {
ps::push_num_places(keys, v, 9);
let _ = writeln!(keys, " /Real ({key}) ,");
};
let (style, grid) = match kind {
EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => {
let fraction = |p: f64| (p.is_finite() && (-100.0..=100.0).contains(&p)).then_some(p / 100.0);
let (number, bend, h, v) = (warp_number(style)?, fraction(*bend)?, fraction(*h)?, fraction(*v)?);
if *version != WARP_NET {
return None;
}
let _ = writeln!(keys, "{number} /Int (DeformStyle) ,");
real(&mut keys, h, "DeformHoriz");
real(&mut keys, bend, "DeformValue");
real(&mut keys, v, "DeformVert");
let _ = writeln!(keys, "{} /Bool (Rotate) ,", u8::from(!*horizontal));
// The grid of the warp's shape, for apps that read it.
(1, warp_grid(n).and_then(|m| as_read(&m)).and_then(|(rows, cols, pts)| sized(rows, cols).map(|(r, c)| (r, c, pts))))
}
EnvelopeKind::Mesh { rows, cols, points, handles } => {
let (r, c) = sized(*rows, *cols)?;
let mesh = envelope_grid(*rows, *cols, points, handles)?;
let pts = as_read(&mesh)?.2;
// The reader lays the grid out with its first row at the top and its first column at the
// left: a grid it would lay out another way round would map the contents another way.
if !reads_as_written(r, c, &pts) {
return None;
}
(2, Some((r, c, pts)))
}
EnvelopeKind::TopObject { path, corners } => (3, Some(top_object_grid(path, *corners)?)),
};
if options.distort_appearance {
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?;
let margin = options.bounds_margin;
let same = |m: [f32; 4]| m.iter().zip(margin).all(|(a, b)| (a - b).abs() <= MARGIN_SLACK);
// The reader maps from the size written when it matches the contents' bounds with their
// strokes, and from their geometric bounds otherwise.
let size = if margin == [0.0; 4] {
plain
} else if stroked != plain && envelope_stroke_margin(stroked, plain).is_some_and(same) {
stroked
} else {
return None;
};
real(&mut keys, size.height(), "AIDeformArtHeightKey");
real(&mut keys, size.width(), "AIDeformArtWidthKey");
}
Some(Record { keys, style, grid })
}
/// `rows` and `cols` as sizes, when the reader reads a grid of them.
fn sized(rows: u32, cols: u32) -> Option<(usize, usize)> {
let (r, c) = (usize::try_from(rows).ok()?, usize::try_from(cols).ok()?);
((1..=MAX_GRID).contains(&r) && (1..=MAX_GRID).contains(&c)).then_some((r, c))
}
/// The points of grid `m` with their handles as the reader reads them back: the handles that point
/// out of the grid, which nothing draws with, are left at the point. `None` for a grid of points
/// or handles that aren't finite.
fn as_read(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
let (rows, cols) = (m.rows as usize, m.cols as usize);
let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite();
let mut pts = Vec::with_capacity(m.points.len());
for (i, q) in m.points.iter().enumerate() {
if !finite(q.p.to_vec2()) || !q.handles.iter().all(|h| finite(*h)) {
return None;
}
let (r, c) = (i / (cols + 1), i % (cols + 1));
let mut h = q.handles;
for (slot, out) in [(H_LEFT, c == 0), (H_RIGHT, c == cols), (H_UP, r == 0), (H_DOWN, r == rows)] {
if out && let Some(h) = h.get_mut(slot) {
*h = Vec2::ZERO;
}
}
pts.push((q.p, h));
}
Some((m.rows, m.cols, pts))
}
/// Does the reader lay out grid `pts` (`rows`×`cols` patches) as it is written?
fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool {
let points =
pts.iter().map(|(p, handles)| MeshPoint { p: *p, color: vectorcraft_color::Color::BLACK, opacity: 1.0, handles: *handles }).collect();
let mesh = GradientMesh { rows: rows as u32, cols: cols as u32, points };
envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts)
}
/// The grid a top object with outline `path` and corners `corners` is written with: its edge runs
/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so
/// the top and bottom sides need as many segments as each other, as do the left and right sides;
/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's
/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked.
fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec<GridPoint>)> {
let coons = Coons::from_top_object(path, corners)?;
// The outline, as the patch takes it: the largest subpath.
let mut sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?.clone();
let count = sp.anchors.len();
let empty = |i: usize| {
let c = sp.segment(i);
[c.p1, c.p2, c.p3].iter().all(|p| p.distance(c.p0) <= 1e-9)
};
if !sp.closed || count < 4 || (0..count).any(empty) {
return None;
}
let fits = |c: &[usize; 4]| {
c.iter().all(|i| *i < count) && {
let gaps = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count);
gaps.clone().all(|g| g > 0) && gaps.sum::<usize>() == count
}
};
// Stored corners that fit keep the outline as drawn; otherwise it runs clockwise, and the
// corners are the anchors the patch's corners lie on.
let at = match corners.map(|c| c.map(|i| i as usize)).filter(fits) {
Some(c) => c,
None => {
if sp.signed_area() < 0.0 {
sp.reverse();
}
let find = |q: Point| sp.anchors.iter().position(|a| a.p.distance(q) <= 1e-9);
let [tl, tr, br, bl] = coons.corners();
let c = [find(tl)?, find(tr)?, find(br)?, find(bl)?];
if !fits(&c) {
return None;
}
c
}
};
let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count;
let (cols, rows) = (gap(0), gap(1));
if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID {
return None;
}
let width = cols + 1;
let mut pts: Vec<GridPoint> = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width];
// Where the `k`th anchor from the top left corner goes, and the slots of the handles of the
// segment from it to the next anchor: its own, and the next anchor's back.
let place = |k: usize| -> (usize, usize, usize, usize) {
if k < cols {
(0, k, H_RIGHT, H_LEFT)
} else if k < cols + rows {
(k - cols, cols, H_DOWN, H_UP)
} else if k < 2 * cols + rows {
(rows, cols - (k - cols - rows), H_LEFT, H_RIGHT)
} else {
(rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN)
}
};
for k in 0..count {
let i = (at[0] + k) % count;
let seg = sp.segment(i);
// A straight segment's patch spreads evenly along it, as a cubic's with its handles a third
// of the way does.
let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) };
let (r, c, out, into) = place(k);
let (nr, nc, _, _) = place((k + 1) % count);
if let Some(q) = pts.get_mut(r * width + c) {
q.0 = seg.p0;
q.1[out] = p1 - seg.p0;
}
if let Some(q) = pts.get_mut(nr * width + nc) {
q.1[into] = p2 - seg.p3;
}
}
// The points inside, blended from the sides.
let edge = |r: usize, c: usize| pts.get(r * width + c).map_or(Point::ZERO, |q| q.0).to_vec2();
let mut inside = vec![];
for r in 1..rows {
for c in 1..cols {
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
let p = (1.0 - v) * edge(0, c) + v * edge(rows, c) + (1.0 - u) * edge(r, 0) + u * edge(r, cols)
- ((1.0 - u) * (1.0 - v) * edge(0, 0) + u * (1.0 - v) * edge(0, cols) + (1.0 - u) * v * edge(rows, 0) + u * v * edge(rows, cols));
inside.push((r * width + c, p.to_point()));
}
}
for (i, p) in inside {
if let Some(q) = pts.get_mut(i) {
q.0 = p;
}
}
if !pts.iter().all(|(p, h)| p.is_finite() && h.iter().all(|h| h.is_finite())) || !reads_as_written(rows, cols, &pts) {
return None;
}
// The top object the reader makes of the grid: its edge, with the corners of the grid.
let outline = envelope_outline(rows as u32, cols as u32, &pts)?;
let corners = [0, cols, cols + rows, 2 * cols + rows].map(|c| c as u32);
let read = Coons::from_top_object(&outline, Some(corners))?;
let [tl, tr, br, bl] = coons.corners();
let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE;
const STEPS: usize = 8;
let at = |i: usize| i as f64 / STEPS as f64;
let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach));
same.then_some((rows, cols, pts))
}
impl Writer<'_> {
/// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity
/// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. False,
/// writing nothing, where it is written as its art instead: where the reader would open it in
/// another shape, or some of it is left out for the object limit ([`Self::take_objects`]).
pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool {
let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false };
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 {
return false;
}
let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false };
let start = self.body.len();
let (state, gs, charges, bound) = (self.state, self.gs, self.charges(), self.bound.len());
self.nest += 1;
self.hidden += 1;
// The group before the dictionary: the grid, or the contents while they are edited.
let outer = std::mem::take(&mut self.body);
let opened = self.open_group("u");
if opened {
if *editing {
self.contents(content);
} else {
self.grid(record.grid.as_ref());
}
self.line("U");
}
let before = std::mem::replace(&mut self.body, outer);
hide(&before, &mut self.body);
self.body.push_str("%_/ArtDictionary :\n");
hide(&record.keys, &mut self.body);
self.body.push_str("%_X=\n");
// The dictionary's art starts unlocked, shown and opaque, as an opacity mask's does.
let outer = std::mem::take(&mut self.body);
let at_block = self.state;
(self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE));
if *editing {
self.grid(record.grid.as_ref());
} else if self.open_group("u") {
self.contents(content);
self.end_group("U", Xy::PLAIN);
}
let block = std::mem::replace(&mut self.body, outer);
hide(&block, &mut self.body);
(self.state, self.gs, self.block_end) = (at_block, None, usize::MAX);
let _ = writeln!(self.body, "%_X+\n%_ (AIDeformArtKey) ,\n%_{} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW", record.style);
self.hidden -= 1;
self.nest -= 1;
// The distorted art, which takes the envelope's lock, visibility, transparency, name and
// opacity mask.
self.state(n.locked, !n.visible);
self.drawn_art(n, xy, None);
if !opened || self.left_out_since(charges) {
let lines = self.body.split_off(start);
self.give_back(charges, &lines);
self.bound.truncate(bound);
(self.state, self.gs, self.block_end) = (state, gs, usize::MAX);
return false;
}
self.deform = true;
self.envelopes_left -= 1;
true
}
/// An envelope's contents.
fn contents(&mut self, content: &[Arc<Node>]) {
for c in content {
self.node(c);
}
}
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
/// towards the previous one and a weight, in art space), from its top left one down, across and
/// up, and `/E`. One object.
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
let Some((rows, cols, pts)) = grid else { return };
if !self.take_objects(1) {
return;
}
let (rows, cols, width) = (*rows, *cols, cols + 1);
let to_art = self.to_art;
let s = &mut self.body;
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
let num = |s: &mut String, v: f64| {
s.push(' ');
ps::push_num(s, v);
};
for c in 0..cols {
for r in 0..rows {
let _ = writeln!(s, "[{c} {r}] /P X#");
// Each corner with the slots of its handles towards the next corner and the previous one.
let corners = [((r, c), H_DOWN, H_RIGHT), ((r + 1, c), H_RIGHT, H_UP), ((r + 1, c + 1), H_UP, H_LEFT), ((r, c + 1), H_LEFT, H_DOWN)];
for ((pr, pc), next, prev) in corners {
let (p, h) = pts.get(pr * width + pc).copied().unwrap_or((Point::ZERO, [Vec2::ZERO; 4]));
let at = |v: Vec2| to_art * (p + v);
s.push_str("[0 1");
for q in [at(Vec2::ZERO), at(h[next])] {
num(s, q.x);
num(s, q.y);
}
s.push_str(" 1");
let q = at(h[prev]);
num(s, q.x);
num(s, q.y);
s.push_str(" 1] /N X#\n");
}
s.push_str("/E X#\n");
}
}
s.push_str("/End X!\n");
}
}
+5 -2
View File
@@ -82,12 +82,15 @@ use graphics::{GState, Out};
use interp::{Fault, Interp};
use obj::PsError;
#[cfg(test)]
pub(crate) use ai::ENVELOPE_DRAWN;
pub use ai::NameEncoding;
#[cfg(test)]
pub(crate) use ai::objects_read;
pub(crate) use ai::{
BRUSH_MANAGER, BrushesRead, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept,
read_art_style, read_brush_object, read_style_list, style_moves_with, symbol_art_member, warp_number,
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,
};
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
+1 -1
View File
@@ -36,9 +36,9 @@ use crate::ps;
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;
#[cfg(test)]
pub(crate) use envelope::MAX_CHECKED;
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright};
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
pub(crate) use frames::text_frames;
pub use obj::{NameEncoding, Names};
+4 -4
View File
@@ -41,7 +41,7 @@ use super::obj::Obj;
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black};
/// The plugin that writes envelopes.
pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
pub(crate) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
/// The note for an envelope that keeps its drawn art.
pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art";
/// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the
@@ -366,12 +366,12 @@ fn only_mesh(n: &Node) -> Option<&GradientMesh> {
}
/// A grid point and its handles.
type GridPoint = (Point, [Vec2; 4]);
pub(crate) type GridPoint = (Point, [Vec2; 4]);
/// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first
/// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range
/// or with points that aren't finite.
fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
pub(crate) fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
let (mut rows, mut cols) = (m.rows, m.cols);
if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID {
return None;
@@ -451,7 +451,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
}
/// The outline of an upright grid: its edge, clockwise from the top left corner.
fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option<PathData> {
pub(crate) fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option<PathData> {
let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied();
// Each edge: from a point by one of its handles to the next point by one of its handles.
type Edge = ((u32, u32), usize, (u32, u32), usize);
+49
View File
@@ -7730,6 +7730,55 @@ fn a_top_object_envelope_opens_live_with_its_outline() {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
/// A top object whose saved grid has three patches across, its top edge one curve split into
/// thirds, maps its contents along that one curve. In this synthetic file the drawn art is drawn by
/// VectorCraft's own map of the unsplit curve, so the envelope opens live only when the split side
/// maps the same way, and the contents' first quarter ends a quarter of the way along the curve.
#[test]
fn a_top_object_whose_top_is_one_curve_split_in_thirds_opens_live() {
use kurbo::{CubicBez, ParamCurve};
use vectorcraft_doc::live::EnvelopeKind;
// In the document: the top runs from (40, 20) to (160, 20), its parameter fast at the start.
let top = CubicBez::new((40.0, 20.0), (112.0, -16.0), (154.0, 2.0), (160.0, 20.0));
let thirds = [top.subsegment(0.0..1.0 / 3.0), top.subsegment(1.0 / 3.0..2.0 / 3.0), top.subsegment(2.0 / 3.0..1.0)];
// Art space has y up: row 1 is the top. The bottom row and the columns are straight.
let up = |p: Point| (p.x, 100.0 - p.y);
let at = move |(i, j): (usize, usize)| {
if j == 1 { up(if i == 0 { top.p0 } else { thirds[i - 1].p3 }) } else { (40.0 + 40.0 * i as f64, 20.0) }
};
let handle = move |p: (usize, usize), q: (usize, usize)| match (p, q) {
((i, 1), (k, 1)) if k == i + 1 => up(thirds[i].p1),
((i, 1), (k, 1)) if k + 1 == i => up(thirds[k].p2),
_ => {
let ((x, y), (u, v)) = (at(p), at(q));
(x + (u - x) / 3.0, y + (v - y) / 3.0)
}
};
let shape = mesh_text(3, 1, &at, &handle, None);
// The contents: two red bars at the box's left and right ends, drawn by the unsplit curve.
let mut bp = kurbo::BezPath::new();
bp.move_to(top.p0);
bp.curve_to(top.p1, top.p2, top.p3);
bp.line_to((160.0, 80.0));
bp.line_to((40.0, 80.0));
bp.close_path();
let one_curve = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: Some([0, 1, 2, 3]) };
let src = Rect::new(40.0, 20.0, 160.0, 80.0);
let bars = [Rect::new(40.0, 20.0, 70.0, 80.0), Rect::new(130.0, 20.0, 160.0, 80.0)];
let content: String = bars.iter().map(|b| format!("{RED}{}f\n", rect_path(b.x0, b.y0, b.x1, b.y1))).collect();
let drawn: String = bars.iter().map(|b| drawn_box(&one_curve, src, *b)).collect();
let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &content, 3, &drawn)));
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let (_, kind, ..) = live_envelope(&a[0]);
let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") };
assert_eq!(path.anchor_count(), 8, "{path:?}");
let map = vectorcraft_doc::live::envelope_mapper(kind, src);
let (p, want) = (map(Point::new(70.0, 20.0)), top.eval(0.25));
assert!((p - want).hypot() < 0.02, "{p:?}, want {want:?}");
}
/// Envelope Options come from the options word, Fidelity from its own key.
#[test]
fn an_envelope_reads_its_options_and_fidelity() {
+228 -49
View File
@@ -55,8 +55,99 @@ const MAX_DEVICE_N: usize = 32;
const MISSING_PATTERN: &str = "missing patterns are written as mid-grey";
const TOO_LARGE: &str = "the artwork is too large for EPS: what follows 256 MB of PostScript was left out";
/// The most PostScript the page body may grow to: symbols and patterns that hold one another
/// expand into every instance, so nesting depth alone doesn't bound the output.
/// expand into every instance, so nesting depth alone doesn't bound the output. An image placed
/// more than once counts its data once.
const MAX_BODY: usize = 256 << 20;
/// Most compressed bytes in one string of an image's samples at Level 2 (under PostScript's
/// 65,535-byte string limit).
const IMAGE_CHUNK: usize = 48 << 10;
/// The start of the procedure that reads an image's data from the lines after it.
const INLINE_SOURCE: &str = "{ /VCsrc currentfile /ASCII85Decode filter def\n";
/// An image as written: what sets up its color, its image dictionary and its compressed samples.
/// Placed once, it is written where it is drawn, its data following the operators that read it.
/// Placed more than once, its samples are written once in the setup as `VCim<i>` (a reusable
/// stream at Level 3, an array of strings at Level 2) and each placement reads them from there.
struct ImageCode {
/// The color space or ink operators, each line ending in a line break.
prelude: String,
/// `<< /ImageType … /ImageMatrix […]` with its mask colors: the dictionary up to its data source.
dict: String,
/// The decoding filter of the samples: `/FlateDecode` or `/RunLengthDecode`.
filter: &'static str,
/// `image` or `imagemask`.
op: &'static str,
/// The compressed samples in ASCII85, as lines with the end marker.
ascii: String,
/// The compressed samples, kept at Level 2, where a reused image's samples are written as
/// strings of at most [`IMAGE_CHUNK`] bytes.
data: Vec<u8>,
/// How many placements in the page draw it.
uses: usize,
/// The length of [`ImageCode::push_inline`]'s text.
inline_len: usize,
/// The length of [`ImageCode::reference`]'s text.
ref_len: usize,
}
impl ImageCode {
/// The operators and data that draw the image where it is placed.
fn push_inline(&self, s: &mut String) {
s.push_str(&self.prelude);
s.push_str(INLINE_SOURCE);
s.push_str(&self.dict);
s.push_str(&self.inline_read());
s.push_str(&self.ascii);
}
/// The end of the procedure [`ImageCode::push_inline`] writes. The procedure is read whole
/// before it runs: the image data follows it, and flushing the ASCII85 filter afterwards reads
/// past its end marker.
fn inline_read(&self) -> String {
format!("\n/DataSource VCsrc {} filter >> {}\nVCsrc flushfile }} exec\n", self.filter, self.op)
}
/// The operators that draw the image `VCim<i>` holds, for an image placed more than once.
fn reference(&self, i: usize, level: Level) -> String {
match level {
// The stream is read again from its start.
Level::Three => {
format!("{}VCim{i} resetfile\n{}\n/DataSource VCim{i} {} filter >> {}\n", self.prelude, self.dict, self.filter, self.op)
}
// A procedure gives the strings in turn, then an empty string: the end of the data.
Level::Two => format!(
"{}/VCi 0 def\n{}\n/DataSource {{VCi VCim{i} length lt {{VCim{i} VCi get /VCi VCi 1 add def}} {{()}} ifelse}} {} filter >> {}\n",
self.prelude, self.dict, self.filter, self.op
),
}
}
/// The setup's definition of `VCim<i>`: the image's compressed samples, once.
fn resource(&self, i: usize, level: Level) -> String {
let mut s = String::with_capacity(self.ascii.len() + 200);
match level {
Level::Three => {
// The stream reads all of its data when it is made, so the data follows the
// procedure that makes it.
let intent = if self.op == "imagemask" { 1 } else { 0 };
let _ = writeln!(
s,
"{{ /VCsrc currentfile /ASCII85Decode filter def\n/VCim{i} VCsrc << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\nVCsrc flushfile }} exec"
);
s.push_str(&self.ascii);
}
Level::Two => {
let _ = writeln!(s, "/VCim{i} [");
for chunk in self.data.chunks(IMAGE_CHUNK) {
s.push_str("<~");
s.push_str(&ps::ascii85(chunk));
}
s.push_str("] def\n");
}
}
s
}
}
/// What the walk wrote: definitions for the setup, the page, the spot colours it uses (name and
/// CMYK equivalent) and the warnings.
@@ -157,10 +248,18 @@ pub(crate) struct Scene<'a> {
device_n: Vec<String>,
warnings: Vec<String>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
/// Image keys → what draws them (`None`: left out).
images: HashMap<String, Option<Arc<String>>>,
/// Image keys → the index in `codes` of what draws them (`None`: left out).
images: HashMap<String, Option<usize>>,
/// The source key and solid paint together identify a colorized encoding.
colorized_images: HashMap<(String, String), Option<Arc<String>>>,
colorized_images: HashMap<(String, String), Option<usize>>,
/// The encoded images.
codes: Vec<ImageCode>,
/// Where in `body` each placement of an encoded image goes (in order) and the index of its code.
placements: Vec<(usize, usize)>,
/// What the placements in `placements` add to `body`'s length when the page is finished.
pending: usize,
/// The most the page body may grow to ([`MAX_BODY`]).
max_body: usize,
/// Symbols and brush art being written inside one another.
nest: u32,
}
@@ -181,10 +280,21 @@ impl<'a> Scene<'a> {
brushes: None,
images: HashMap::new(),
colorized_images: HashMap::new(),
codes: vec![],
placements: vec![],
pending: 0,
max_body: MAX_BODY,
nest: 0,
}
}
/// This scene with a page body of at most `max` bytes.
#[cfg(test)]
pub fn with_max_body(mut self, max: usize) -> Self {
self.max_body = max;
self
}
pub fn run(mut self) -> Page {
let doc = self.doc;
for l in &doc.layers {
@@ -199,7 +309,27 @@ impl<'a> Scene<'a> {
self.page()
}
fn page(self) -> Page {
fn page(mut self) -> Page {
if !self.placements.is_empty() {
let level = self.o.level;
let mut body = String::with_capacity(self.body.len().saturating_add(self.pending));
let mut at = 0;
for &(offset, i) in &self.placements {
body.push_str(self.body.get(at..offset).unwrap_or_default());
at = offset;
let Some(code) = self.codes.get(i) else { continue };
if code.uses > 1 {
body.push_str(&code.reference(i, level));
} else {
code.push_inline(&mut body);
}
}
body.push_str(self.body.get(at..).unwrap_or_default());
self.body = body;
for (i, code) in self.codes.iter().enumerate().filter(|(_, c)| c.uses > 1) {
self.setup.push_str(&code.resource(i, level));
}
}
let custom = self
.spots
.iter()
@@ -337,7 +467,7 @@ impl<'a> Scene<'a> {
if let NodeKind::Layer { template: true, .. } = n.kind {
return;
}
if self.body.len() >= MAX_BODY {
if self.size() >= self.max_body {
self.warn(TOO_LARGE);
return;
}
@@ -347,7 +477,7 @@ impl<'a> Scene<'a> {
_ => {}
}
self.note_losses(n);
let was = self.body.len();
let (was, placed) = (self.body.len(), self.placements.len());
match &n.kind {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
children.iter().for_each(|c| self.node(c, false));
@@ -402,12 +532,29 @@ impl<'a> Scene<'a> {
// Ruler guides draw on screen only.
NodeKind::RulerGuide { .. } => {}
}
if self.body.len() > MAX_BODY {
if self.size() > self.max_body {
self.body.truncate(was);
self.unplace(placed);
self.warn(TOO_LARGE);
}
}
/// How long the page body will be: what is written and what its image placements add.
fn size(&self) -> usize {
self.body.len().saturating_add(self.pending)
}
/// Take back the image placements after the first `n`, last first.
fn unplace(&mut self, n: usize) {
while self.placements.len() > n {
let Some((_, i)) = self.placements.pop() else { break };
let Some(code) = self.codes.get_mut(i) else { continue };
code.uses = code.uses.saturating_sub(1);
let cost = if code.uses == 0 { code.inline_len } else { code.ref_len };
self.pending = self.pending.saturating_sub(cost);
}
}
/// A clipping group: the art inside its first child's outline. The clipping path's fills
/// paint behind the art (clipped) and its strokes over it (not clipped).
fn clip_group(&mut self, children: &[Arc<Node>]) {
@@ -1229,7 +1376,7 @@ impl<'a> Scene<'a> {
};
let place = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width(), area.height());
if let Some(image) = image {
self.place_image(&image, place);
self.place_inline(&image, place);
}
}
@@ -1241,18 +1388,29 @@ impl<'a> Scene<'a> {
return;
}
let encoded = match self.images.get(key) {
Some(e) => e.clone(),
Some(e) => *e,
None => {
let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(Arc::new);
self.images.insert(key.to_string(), e.clone());
let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(|c| self.add_code(c));
self.images.insert(key.to_string(), e);
e
}
};
if let Some(e) = encoded {
self.place_image(&e, place);
if let Some(i) = encoded {
self.place_image(i, place);
}
}
/// Keep `code` for the placements that draw it: its index in `codes`.
fn add_code(&mut self, mut code: ImageCode) -> usize {
let i = self.codes.len();
if self.o.level == Level::Three {
code.data = vec![];
}
code.ref_len = code.reference(i, self.o.level).len();
self.codes.push(code);
i
}
/// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil;
/// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2.
fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) {
@@ -1262,19 +1420,19 @@ impl<'a> Scene<'a> {
}
let cache = (key.to_string(), format!("{paint:?}"));
let encoded = match self.colorized_images.get(&cache) {
Some(e) => e.clone(),
Some(e) => *e,
None => {
let e = self.encode_colorized(blob, paint).map(Arc::new);
self.colorized_images.insert(cache, e.clone());
let e = self.encode_colorized(blob, paint).map(|c| self.add_code(c));
self.colorized_images.insert(cache, e);
e
}
};
if let Some(e) = encoded {
self.place_image(&e, place);
if let Some(i) = encoded {
self.place_image(i, place);
}
}
fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<String> {
fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<ImageCode> {
let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else {
self.warn(UNDECODED);
return None;
@@ -1355,17 +1513,17 @@ impl<'a> Scene<'a> {
("/RunLengthDecode", rl)
}
};
let mut out = String::new();
let mut prelude = String::new();
if binary {
// imagemask takes its current ink from the graphics state.
out.push_str(&self.ink_code(ink));
prelude.push_str(&self.ink_code(ink));
} else {
match ink {
Ink::Spot { space, .. } => {
let _ = writeln!(out, "VCsp{space} setcolorspace");
let _ = writeln!(prelude, "VCsp{space} setcolorspace");
}
Ink::Process(space, ..) => {
let _ = writeln!(out, "{} setcolorspace", space.name());
let _ = writeln!(prelude, "{} setcolorspace", space.name());
}
}
}
@@ -1374,19 +1532,16 @@ impl<'a> Scene<'a> {
Ink::Process(space, ..) => space.n(),
};
let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() };
let _ = write!(
out,
"{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]",
let mut dict = format!(
"<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]",
if keyed { 4 } else { 1 },
if binary { 1 } else { 8 },
);
if keyed {
let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect();
let _ = write!(out, " /MaskColor [{}]", mask.join(" "));
let _ = write!(dict, " /MaskColor [{}]", mask.join(" "));
}
let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" });
out.push_str(&ps::ascii85(&encoded));
Some(out)
Some(image_code(prelude, dict, filter, if binary { "imagemask" } else { "image" }, encoded))
}
/// Ink-setting operators in the cached stencil body, built with the same path as solid fills.
@@ -1409,18 +1564,40 @@ impl<'a> Scene<'a> {
Some(img.to_rgba8())
}
/// Draw an image of [`Self::encode_image`] on the unit square mapped by `place`.
fn place_image(&mut self, encoded: &str, place: Affine) {
/// Draw the image of `codes[i]` on the unit square mapped by `place`. Its operators go in when
/// the page is finished ([`Self::page`]), once it is known how many placements draw it.
fn place_image(&mut self, i: usize, place: Affine) {
if !invertible(place) {
return;
}
if self.body.len().saturating_add(encoded.len()).saturating_add(64) > MAX_BODY {
let Some(code) = self.codes.get(i) else { return };
let cost = if code.uses == 0 { code.inline_len } else { code.ref_len };
if self.size().saturating_add(cost).saturating_add(64) > self.max_body {
self.warn(TOO_LARGE);
return;
}
self.line("q");
let _ = writeln!(self.body, "{} cm", ps::matrix(place));
self.body.push_str(encoded);
self.placements.push((self.body.len(), i));
self.pending = self.pending.saturating_add(cost);
if let Some(code) = self.codes.get_mut(i) {
code.uses += 1;
}
self.line("Q");
}
/// Draw `code`, an image drawn nowhere else, on the unit square mapped by `place`.
fn place_inline(&mut self, code: &ImageCode, place: Affine) {
if !invertible(place) {
return;
}
if self.size().saturating_add(code.inline_len).saturating_add(64) > self.max_body {
self.warn(TOO_LARGE);
return;
}
self.line("q");
let _ = writeln!(self.body, "{} cm", ps::matrix(place));
code.push_inline(&mut self.body);
self.line("Q");
}
@@ -1428,7 +1605,7 @@ impl<'a> Scene<'a> {
/// them on the unit square: in the process colour space, transparent pixels masked out at
/// Level 3 (a key colour no opaque pixel has), white at Level 2; partly transparent ones over
/// white. `None` for an empty image.
fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option<String> {
fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option<ImageCode> {
let space = if self.cmyk { Space::Cmyk } else { Space::Rgb };
let mut cache: HashMap<[u8; 3], [u8; 4]> = HashMap::new();
let cms = self.cms.clone();
@@ -1447,7 +1624,7 @@ impl<'a> Scene<'a> {
/// Straight CMYK pixels with opacity (five bytes a pixel, `w` × `h`, rows from the top), drawn
/// as [`Self::encode_image`] draws its pixels and keeping their ink amounts: partly
/// transparent pixels lay down that share of each ink.
fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option<String> {
fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option<ImageCode> {
self.encode_samples(cmyka.as_chunks::<5>().0, w, h, Space::Cmyk, |p: &[u8; 5], al| {
[0, 1, 2, 3].map(|i| ((u32::from(p[i]) * al + 127) / 255) as u8)
})
@@ -1463,7 +1640,7 @@ impl<'a> Scene<'a> {
h: u32,
space: Space,
mut sample: impl FnMut(&[u8; N], u32) -> [u8; 4],
) -> Option<String> {
) -> Option<ImageCode> {
if w == 0 || h == 0 {
return None;
}
@@ -1503,27 +1680,29 @@ impl<'a> Scene<'a> {
("/RunLengthDecode", rl)
}
};
let mut out = String::with_capacity(encoded.len() * 5 / 4 + 400);
let _ = writeln!(out, "{} setcolorspace", space.name());
let prelude = format!("{} setcolorspace\n", space.name());
let decode = "0 1 ".repeat(n);
let _ = write!(
out,
"{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]",
let mut dict = format!(
"<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]",
if keyed { 4 } else { 1 },
decode.trim_end()
);
if keyed {
let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect();
let _ = write!(out, " /MaskColor [{}]", mask.join(" "));
let _ = write!(dict, " /MaskColor [{}]", mask.join(" "));
}
// The procedure is read whole before it runs: the image data follows it, and flushing the
// ASCII85 filter afterwards reads past its end marker.
let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> image\nVCsrc flushfile }} exec");
out.push_str(&ps::ascii85(&encoded));
Some(out)
Some(image_code(prelude, dict, filter, "image", encoded))
}
}
/// An image of `prelude`, `dict`, `filter` and `op` (see [`ImageCode`]) with compressed samples
/// `data`, not yet placed.
fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static str, data: Vec<u8>) -> ImageCode {
let mut code = ImageCode { prelude, dict, filter, op, ascii: ps::ascii85(&data), data, uses: 0, inline_len: 0, ref_len: 0 };
code.inline_len = code.prelude.len() + INLINE_SOURCE.len() + code.dict.len() + code.inline_read().len() + code.ascii.len();
code
}
/// `a` to `b` at `t`.
fn mix(a: &[f32], b: &[f32], t: f32) -> Vec<f32> {
a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect()
+232 -3
View File
@@ -82,6 +82,17 @@ fn checked_page(ps: &str) -> String {
}
}
'{' | '[' => stack.push(c),
// An ASCII85 string: its digits are data.
'<' if chars.peek() == Some(&'~') => {
let mut last = ' ';
loop {
let c = chars.next().expect("ASCII85 string closes");
if last == '~' && c == '>' {
break;
}
last = c;
}
}
'<' if chars.peek() == Some(&'<') => {
chars.next();
stack.push('<');
@@ -679,15 +690,20 @@ fn png_doc() -> Document {
for (x, _, p) in img.enumerate_pixels_mut() {
*p = if x < 2 { image::Rgba([0, 200, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) };
}
image_doc(&img, 10.0)
}
/// A 200 × 200 pt document holding `img` as a PNG, its pixels `scale` points wide, at (10, 10).
fn image_doc(img: &image::RgbaImage, scale: f64) -> Document {
let mut png = vec![];
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let mut d = Document::new(200.0, 200.0);
d.images.insert("pic".into(), ImageBlob::new("image/png", png));
let im = ImageObject {
key: "pic".into(),
width: 4,
height: 2,
xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0),
width: img.width(),
height: img.height(),
xf: Affine::translate((10.0, 10.0)) * Affine::scale(scale),
link: None,
placement: Default::default(),
pixels: None,
@@ -988,6 +1004,219 @@ fn uncolorized_image_stays_on_original_eps_path() {
assert_eq!(page_of(&color, &opts(&color)), original);
}
/// A copy of the first layer's object `i`, moved by `xf`, added on top.
fn place_again(d: &mut Document, i: usize, xf: Affine) {
let mut n = (*d.layers[0].children().unwrap()[i]).clone();
n.id = d.alloc_id();
if let NodeKind::Image(im) = &mut n.kind {
im.xf = xf * im.xf;
}
d.insert(d.default_layer(), usize::MAX, n).unwrap();
}
/// Pixels of noise, opaque.
fn noise(w: u32, h: u32) -> image::RgbaImage {
let mut seed = 1u32;
image::RgbaImage::from_fn(w, h, |_, _| {
let mut px = [255u8; 4];
for v in &mut px[..3] {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
*v = (seed >> 16) as u8;
}
image::Rgba(px)
})
}
/// The pixels of each image an EPS file's page draws, read back from the page.
fn imported_images(bytes: &[u8]) -> Vec<Vec<u8>> {
fn walk(n: &Node, d: &Document, out: &mut Vec<Vec<u8>>) {
if let NodeKind::Image(im) = &n.kind {
out.push(image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().into_raw());
}
for c in n.children().into_iter().flatten() {
walk(c, d, out);
}
}
let r = import_with(bytes, false).unwrap();
assert!(!r.preview, "{:?}", r.warnings);
let mut out = vec![];
for l in &r.document.layers {
walk(l, &r.document, &mut out);
}
out
}
/// The samples of an image placed more than once, from the setup that defines them: inflated at
/// Level 3, each string run-length decoded in turn at Level 2.
fn reused_samples(ps: &str, level: Level) -> Vec<u8> {
let setup = &ps[ps.find("%%BeginSetup").unwrap()..ps.find("%%EndSetup").unwrap()];
match level {
Level::Three => ps::inflate(&image_data(setup), 1 << 28).unwrap(),
Level::Two => {
let mut data = vec![];
for s in setup.split("<~").skip(1) {
let chunk = ps::ascii85_decode(&s[..s.find("~>").unwrap() + 2]).unwrap();
assert!(chunk.len() <= 65_535, "a string holds at most 65,535 bytes: {}", chunk.len());
data.extend(chunk);
}
unpack(&data)
}
}
}
/// The samples of a single image written where it is drawn.
fn inline_samples(ps: &str, level: Level) -> Vec<u8> {
match level {
Level::Three => ps::inflate(&image_data(ps), 1 << 28).unwrap(),
Level::Two => unpack(&image_data(ps)),
}
}
/// How many placements draw the image the setup defines as `VCim<i>`.
fn reuses(ps: &str, i: usize, level: Level) -> usize {
match level {
Level::Three => ps.matches(&format!("VCim{i} resetfile\n")).count(),
Level::Two => ps.matches(&format!("{{VCi VCim{i} length lt")).count(),
}
}
#[test]
fn an_image_placed_twice_writes_its_samples_once_at_both_levels() {
let single = png_doc();
let mut d = single.clone();
place_again(&mut d, 0, Affine::translate((60.0, 80.0)) * Affine::rotate(0.5));
for level in Level::ALL {
let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap();
let one_ps = text(&one);
assert!(!one_ps.contains("VCim"), "an image placed once is written where it is drawn: {one_ps}");
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
let ps = text(&out);
checked_page(&ps);
assert_eq!(reuses(&ps, 0, level), 2, "{ps}");
assert!(!ps.contains("VCim1"), "{ps}");
let body = &ps[ps.find("%%EndSetup").unwrap()..];
assert!(!body.contains("currentfile") && !body.contains("~>"), "no samples in the page: {ps}");
match level {
Level::Three => {
assert_eq!(ps.matches("/ReusableStreamDecode filter def").count(), 1, "{ps}");
assert!(ps.contains("/Intent 0 /AsyncRead false /CloseSource false"), "{ps}");
assert!(body.contains("/DataSource VCim0 /FlateDecode filter >> image\n"), "{ps}");
}
Level::Two => {
assert!(ps.contains("/VCim0 [\n<~") && !ps.contains("ReusableStreamDecode"), "{ps}");
assert!(body.contains("/VCi 0 def\n") && body.contains("/RunLengthDecode filter >> image\n"), "{ps}");
}
}
assert_eq!(reused_samples(&ps, level), inline_samples(&one_ps, level));
assert_eq!(out.warnings, one.warnings);
// Read back, each placement draws the image the single placement draws.
let once = imported_images(&one.bytes);
assert_eq!(once.len(), 1);
assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}");
}
}
/// An image in an envelope is drawn as clipped pieces, all from one copy of its samples, which the
/// image placed beside the envelope also draws.
#[test]
fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() {
let mut d = png_doc();
let mut content = (*d.layers[0].children().unwrap()[0]).clone();
content.id = d.alloc_id();
let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
let envelope = Node::new(
d.alloc_id(),
NodeKind::Envelope {
content: vec![Arc::new(content)],
kind: Box::new(kind),
fidelity: 50.0,
editing: false,
options: Default::default(),
frame: Box::new(Affine::IDENTITY),
},
);
d.insert(d.default_layer(), usize::MAX, envelope).unwrap();
for level in Level::ALL {
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
let ps = text(&out);
checked_page(&ps);
// The plain image and 200 pieces: 10 × 10 cells of two triangles.
assert_eq!(reuses(&ps, 0, level), 201, "{ps}");
assert!(!ps.contains("VCim1"), "{ps}");
assert_eq!(ps.matches(if level == Level::Three { "/ReusableStreamDecode" } else { "<~" }).count(), 1, "{ps}");
assert!(!out.warnings.iter().any(|w| w.contains("too large")), "{:?}", out.warnings);
}
}
#[test]
fn each_ink_of_a_colorized_image_placed_twice_is_written_once() {
let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
let mut d = colorized_doc(vec![0, 255, 0], Some(first));
let mut n = (*d.layers[0].children().unwrap()[0]).clone();
n.id = d.alloc_id();
n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 }));
d.insert(d.default_layer(), usize::MAX, n).unwrap();
place_again(&mut d, 0, Affine::translate((0.0, 50.0)));
place_again(&mut d, 1, Affine::translate((0.0, 100.0)));
for level in Level::ALL {
let ps = page_of(&d, &EpsOptions { level, ..opts(&d) });
assert_eq!((reuses(&ps, 0, level), reuses(&ps, 1, level)), (2, 2), "{ps}");
assert_eq!(ps.matches("VCsp0 setcolorspace 1 setcolor\n").count(), 2, "{ps}");
assert_eq!(ps.matches("VCsp0 setcolorspace 0.5 setcolor\n").count(), 2, "{ps}");
assert_eq!(ps.matches("imagemask").count(), 4, "{ps}");
if level == Level::Three {
assert_eq!(ps.matches("/Intent 1 ").count(), 2, "image masks: {ps}");
}
}
}
/// Samples longer than PostScript's longest string: one stream at Level 3, several strings at
/// Level 2, each placement reading all of them.
#[test]
fn samples_longer_than_a_string_are_reused_at_both_levels() {
let single = image_doc(&noise(160, 160), 1.0);
let mut d = single.clone();
place_again(&mut d, 0, Affine::translate((20.0, 0.0)));
for level in Level::ALL {
let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap();
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
let ps = text(&out);
checked_page(&ps);
assert_eq!(reuses(&ps, 0, level), 2);
if level == Level::Two {
assert_eq!(ps.matches("<~").count(), 2, "160 × 160 × 3 run-length bytes take two strings");
}
let samples = reused_samples(&ps, level);
assert_eq!(samples.len(), 160 * 160 * 3);
assert_eq!(samples, inline_samples(&text(&one), level));
let once = imported_images(&one.bytes);
assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}");
}
}
/// The limit on the page body counts the samples of an image placed many times once. Art taken
/// back for passing the limit takes its image placements with it.
#[test]
fn the_page_limit_counts_a_repeated_images_samples_once() {
let single = image_doc(&noise(40, 40), 1.0);
let o = opts(&single);
let inline = crate::scene::Scene::new(&single, &o).run().body.len();
let mut d = single.clone();
for k in 1..20 {
place_again(&mut d, 0, Affine::translate((f64::from(k), 0.0)));
}
let page = crate::scene::Scene::new(&d, &o).with_max_body(inline * 3).run();
assert!(page.warnings.is_empty(), "{:?}", page.warnings);
assert_eq!(reuses(&page.body, 0, Level::Three), 20);
assert!(page.setup.contains("/VCim0 VCsrc"));
// Past the limit, the placements that don't fit are left out with a warning.
let page = crate::scene::Scene::new(&d, &o).with_max_body(inline + 1000).run();
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings);
let placed = reuses(&page.body, 0, Level::Three);
assert!((2..20).contains(&placed), "{placed}");
assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len());
}
#[test]
fn run_length_and_ascii85_round_trip() {
let cycle: Vec<u8> = (0..=255u8).cycle().take(1000).collect();