Plug-ins: a piece's own effects keep to what the pieces before it leave of the budget

Each painted piece's own geometry effects now run within what the pieces
and the pieces before it leave of the budget of the object's geometry
effects, and stop at the first effect that would go past it or that would
make fewer Transform copies than it asks for. The pieces after it are not
built, and the object, or the fill or stroke the effect is on, draws the
geometry it was given. Before, each piece was reshaped with the whole
budget and checked afterwards, and on a fill every piece was reshaped
before any check.

Adds tests for SVG and PDF export and Expand Appearance of a piece's
opacity, blending mode and effects, and fuzz cases for hostile piece looks.
This commit is contained in:
dotCooCoo committed 2026-11-22 12:01:37 -08:00
1 parent cc83f5ab63
commit 10150cb77b
5 files changed
+290 -47

No files matched your search

+67 -32
View File
@@ -1625,12 +1625,27 @@ fn hoist_copies(art: &mut Node) {
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
/// masks keeps its shape under that effect.
fn reshape_leaves_apart(
art: &mut Node,
fx: &[&Effect],
owner: &[Effect],
budget: Budget,
flags: (bool, bool),
doc: Option<&Document>,
) -> crate::Carry {
reshape_leaves_checked(art, fx, owner, budget, flags, doc, None)
}
/// [`reshape_leaves_apart`] that, given `complete`, stops at the first effect that leaves a path in
/// the art with its shape or makes fewer copies than it asks for, past `budget` ([`Ran::kept`],
/// [`Ran::short`]), and sets `complete` to `false`; the art is then partly reshaped.
fn reshape_leaves_checked(
art: &mut Node,
fx: &[&Effect],
owner: &[Effect],
budget: Budget,
(apart, rows): (bool, bool),
doc: Option<&Document>,
mut complete: Option<&mut bool>,
) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
@@ -1668,11 +1683,18 @@ fn reshape_leaves_apart(
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
let strict = complete.is_some();
let step = Step { e, params: &params, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held, strict };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
if (ran.kept || ran.short)
&& let Some(complete) = complete.as_deref_mut()
{
*complete = false;
return whole;
}
if (ran.masks || ran.short)
&& let Some((was, cost)) = before
{
@@ -1704,7 +1726,8 @@ fn reshape_leaves_apart(
/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks, and whether one of
/// the object's effects holds the raster effects in its art back from its Transform effects
/// ([`follow_art`]).
/// ([`follow_art`]), and whether a Transform effect that makes fewer copies of anything in the art
/// than it asks for is reported ([`Ran::short`]) wherever it is (`strict`).
struct Step<'a> {
e: &'a Effect,
params: &'a serde_json::Value,
@@ -1716,6 +1739,7 @@ struct Step<'a> {
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
held: bool,
strict: bool,
}
/// What [`Step::run`] did to a piece of art.
@@ -1728,7 +1752,8 @@ struct Ran {
/// took the effect, or could have ([`Step::reshape_masks`]).
masks: bool,
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
/// (past the budget or out of reach), where a linked mask could take a different number.
/// (past the budget or out of reach), where a linked mask could take a different number, or
/// anywhere in the art for a [`Step`] with `strict`.
short: bool,
/// How what paints the art as a whole follows the effect, when it does.
whole: Option<crate::Carry>,
@@ -1840,7 +1865,8 @@ impl Step<'_> {
{
if !own {
*used = copy_art(art, m, copies, copy_scaling(options), max);
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
let short = self.strict && art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
return Ran { kept: false, took: true, masks: false, short, whole: None };
}
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
@@ -1861,7 +1887,7 @@ impl Step<'_> {
if watch && !own {
masked_ids(art, false, &mut covered);
}
let counts = |id: NodeId| watch && (own || covered.contains(&id));
let counts = |id: NodeId| self.strict || (watch && (own || covered.contains(&id)));
let mut short = false;
let mut took = false;
for_each_leaf(art, &mut |leaf| {
@@ -2545,11 +2571,8 @@ fn paint_leaf(
one.name = None;
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
set_geometry(&mut one, p.path.clone(), p.rule);
made = made.plus(dress_piece(&mut one, &p.look, doc));
// The pieces' own geometry effects keep to the budget too.
if !budget.fits(made) {
return None;
}
// The pieces' own geometry effects keep to what the pieces before them leave of the budget.
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
children.push(Arc::new(one));
}
let mut g = Node::group(leaf.id, children);
@@ -2560,18 +2583,19 @@ fn paint_leaf(
/// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the
/// object's, its blending mode, and its effects after the object's own. The visible geometry effects
/// among them, and only those, reshape the piece at once ([`reshape_leaves`], with `doc`), so they run
/// among them, and only those, reshape the piece at once ([`reshape_leaves_checked`], with `doc`), so they run
/// before the source's later effects and the effects of its fills and strokes stay for their own
/// stage; the object becomes a group with its id around the reshaped piece, carrying its
/// transparency and effects. The piece's raster effects stay on it and draw on it. When the object
/// has a blending mode other than Normal and the piece gives one, the same one included, the object
/// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs
/// past its own path.
pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, doc: Option<&Document>) -> Budget {
/// past its own path; `None` when its geometry effects would cost more than `room` past it: they stop at the first
/// effect that does not fit, and `one` is then incomplete.
pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, room: Budget, doc: Option<&Document>) -> Option<Budget> {
use vectorcraft_doc::color::BlendMode;
let none = Budget { anchors: 0, lines: 0 };
if look.is_empty() {
return none;
return Some(none);
}
let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend);
if let Some(o) = look.opacity {
@@ -2586,10 +2610,16 @@ pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::L
if !shape.is_empty() {
let before = art_cost(one);
let mut art = one_piece(one);
reshape_leaves(&mut art, &shape.iter().collect::<Vec<_>>(), &shape, doc);
let mut complete = true;
reshape_leaves_checked(&mut art, &shape.iter().collect::<Vec<_>>(), &shape, room.plus(before), (false, false), doc, Some(&mut complete));
#[cfg(test)]
DRESSED.with(|d| d.set(d.get().plus(art_cost(&art))));
extra = art_cost(&art).minus(before);
if !complete || !room.fits(extra) {
return None;
}
let mut art = dressed(art, one);
art.appearance.effects = one.appearance.effects.clone();
extra = art_cost(&art).minus(before);
*one = art;
}
if let Some(blend) = outer {
@@ -2597,7 +2627,13 @@ pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::L
g.blend = blend;
*one = g;
}
extra
Some(extra)
}
#[cfg(test)]
thread_local! {
/// What the art [`dress_piece`] has reshaped on this thread has cost, all together.
pub(crate) static DRESSED: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) };
}
/// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the
@@ -2662,10 +2698,7 @@ fn paint_piece(
let mut one = leaf.clone();
one.appearance.items = items;
set_geometry(&mut one, p.path.clone(), p.rule);
made = made.plus(dress_piece(&mut one, &p.look, doc));
if !budget.fits(made) {
return None;
}
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
children.push(Arc::new(one));
}
*leaf = Node::group(leaf.id, children);
@@ -2825,25 +2858,27 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::<Vec<_>>()
})
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
// The paths the pieces become, with their own geometry effects applied, and what they cost.
// The paths the pieces become, with their own geometry effects applied, and what they
// cost; `None` as soon as a piece's own geometry effects would pass `room`.
let build = |returned: Vec<(PathData, FillRule, Vec<AppearanceItem>, vectorcraft_plugins::painted::Look)>| {
let returned: Vec<_> = returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()).collect();
let mut made = returned.iter().map(|(path, ..)| piece_cost(path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
let mut group: Vec<Arc<Node>> = vec![];
let mut made = Budget { anchors: 0, lines: 0 };
for (path, rule, items, look) in returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()) {
made = made.plus(piece_cost(&path));
for (path, rule, items, look) in returned {
let mut p = piece(items);
set_geometry(&mut p, path, rule);
made = made.plus(dress_piece(&mut p, &look, doc));
made = made.plus(dress_piece(&mut p, &look, room.minus(made), doc)?);
group.push(Arc::new(p));
}
(group, made)
Some((group, made))
};
// A failed run, or pieces whose own geometry effects would pass the budget, draws the
// fill or stroke on the geometry it was given.
let (group, made) = painted
.map(&build)
.filter(|(_, made)| room.fits(*made))
.unwrap_or_else(|| build(vec![(g.clone(), rule, vec![it], Default::default())]));
// fill or stroke on the geometry it was given, at that geometry's own cost.
let (group, made) = painted.and_then(build).unwrap_or_else(|| {
let mut p = piece(vec![it]);
set_geometry(&mut p, g.clone(), rule);
(vec![Arc::new(p)], piece_cost(&g))
});
*used = used.plus(made);
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc);
+80 -4
View File
@@ -8,7 +8,7 @@ use vectorcraft_plugins::wat as tpl;
use crate::geometry::Budget;
use crate::reshape;
use crate::reshape::{HELD_PEAK, PLUGIN_RUNS};
use crate::reshape::{DRESSED, HELD_PEAK, PLUGIN_RUNS};
/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id:
/// its effect returns `output` whatever it is given.
@@ -348,6 +348,82 @@ fn a_piece_s_own_geometry_effects_keep_to_the_budget() {
vectorcraft_plugins::registry::remove(id);
}
/// Where [`many_heavy_pieces`] puts its effect.
#[derive(Clone, Copy, Debug)]
enum HeavyOn {
/// The object's own effects.
Object,
/// The square's fill, as its only effect.
Fill,
/// The square's fill, after a painted effect that returns the square.
LaterOnFill,
}
/// Ten painted pieces, each drawn with 4% of the effects' budget, each with a Transform effect that
/// makes 14 copies of it (60% of the budget per piece), from an effect on a square `on`: they would
/// pass the budget together, so the square is drawn as it was. The pieces' own geometry effects keep
/// to what the pieces before them left: the art reshaped for them costs less than the budget
/// together, and so does the art drawn.
fn many_heavy_pieces(on: HeavyOn) {
let id = format!("test.effects.look.heavy{on:?}").to_lowercase();
let pieces: Vec<_> = (0..10)
.map(|k| json!({"path": drawn_share(0.04, 1_000.0 * f64::from(k)), "effects": [{"id": "distort.transform", "params": {"copies": 14, "moveH": 10.0}}]}))
.collect();
let manifest = format!(
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
);
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": pieces }).to_string())).unwrap();
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0));
let first = format!("{id}.first");
install_painting(&first, &json!({"objects": [{"path": square}]}));
let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let heavy = Effect { id: format!("plugin.{id}"), params: json!({}), visible: true };
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
match on {
HeavyOn::Object => n.appearance.effects.push(heavy),
HeavyOn::Fill => n.appearance.items[fill].effects_mut().push(heavy),
HeavyOn::LaterOnFill => {
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{first}"), params: json!({}), visible: true });
n.appearance.items[fill].effects_mut().push(heavy);
}
}
DRESSED.with(|d| d.set(Budget { anchors: 0, lines: 0 }));
let art = reshape(None, &n, None).unwrap();
let dressed = DRESSED.with(std::cell::Cell::get);
assert!(Budget::EFFECTS.fits(dressed), "{on:?}: the pieces' own effects made {dressed:?}");
let (mut bounds, mut drawn) = (vec![], Budget { anchors: 0, lines: 0 });
art.walk(&mut |c| {
if let Some(p) = c.path_data() {
bounds.push(p.bounds());
drawn = drawn.plus(Budget::of(p));
}
});
// On a fill, the fill and the stroke are paths of their own.
assert!(!bounds.is_empty() && bounds.iter().all(|b| *b == square.bounds()), "{on:?}: {bounds:?}");
assert!(Budget::EFFECTS.fits(drawn), "{on:?}: the art costs {drawn:?}");
vectorcraft_plugins::registry::remove(&id);
vectorcraft_plugins::registry::remove(&first);
}
/// [`many_heavy_pieces`] from the object's own effect.
#[test]
fn heavy_pieces_of_an_object_s_effect_stop_within_the_budget() {
many_heavy_pieces(HeavyOn::Object);
}
/// [`many_heavy_pieces`] from an effect on a fill.
#[test]
fn heavy_pieces_of_a_fill_s_effect_stop_within_the_budget() {
many_heavy_pieces(HeavyOn::Fill);
}
/// [`many_heavy_pieces`] from a later effect on a fill.
#[test]
fn heavy_pieces_of_a_later_effect_on_a_fill_stop_within_the_budget() {
many_heavy_pieces(HeavyOn::LaterOnFill);
}
/// A piece's own geometry effect reshapes it before the source's later effects run, and those run
/// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the
/// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes.
@@ -395,7 +471,7 @@ fn a_piece_s_look_runs_only_its_own_geometry_effects() {
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
..Default::default()
};
crate::reshape::dress_piece(&mut n, &look, None);
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
let mut paths = vec![];
n.walk(&mut |c| {
if let Some(b) = c.path_data().and_then(PathData::bounds) {
@@ -417,7 +493,7 @@ fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() {
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
n.blend = BlendMode::Multiply;
let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() };
crate::reshape::dress_piece(&mut n, &look, None);
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
let mut blends = vec![];
n.walk(&mut |c| blends.push(c.blend));
assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]);
@@ -435,7 +511,7 @@ fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() {
blend: Some(BlendMode::Screen),
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
};
crate::reshape::dress_piece(&mut n, &look, None);
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
let (mut opacity, mut blends) = (1.0f32, vec![]);
n.walk(&mut |c| {
opacity *= c.opacity;
+45
View File
@@ -439,6 +439,51 @@ fn a_painted_live_effect_draws_its_pieces_with_their_own_paints() {
assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.paints");
}
/// A piece that an effect declaring `appearanceOutput` returns with 50% opacity, Multiply and
/// Offset Path keeps that look in SVG and PDF export, which leave the document alone, and Expand
/// Appearance writes it as an ordinary path that draws the same, with the opacity and blending
/// mode applied once, in one undo step.
#[test]
fn a_painted_piece_s_look_is_exported_and_expanded() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let piece = json!({"path": square_at(40.0), "fills": [solid("#00ff00")], "opacity": 0.5, "blend": "Multiply",
"effects": [{"id": "path.offsetPath", "params": {"offset": 5}}]});
let manifest =
r#"{"id":"test.engine.looks","name":"Looks","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#;
install_wat(&mut s, &tpl::returning(manifest, &json!({ "objects": [piece] }).to_string()));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.looks"}));
assert_eq!(run(&mut s, "plugin.info", json!({"id": "test.engine.looks"}))["lastError"], Value::Null);
let near = |got: [u8; 4], want: [u8; 3]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8);
let img = drawn(&s);
let (inside, grown, outside) = (img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50));
assert!(near(inside, [128, 255, 128]) && near(grown, [128, 255, 128]), "half green, grown by the offset: {inside:?} {grown:?}");
assert_eq!((outside, img.pixel(15, 15)), (WHITE, WHITE));
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
assert!(svg.contains("#00ff00") && svg.contains("multiply") && svg.contains("0.5"), "{svg}");
let pdf = s.execute("document.export", &json!({"format": "pdf"})).unwrap();
let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap();
assert!(pdf.windows(9).any(|w| w == b"/Multiply"), "the PDF sets the blending mode");
assert_eq!(s.doc().unwrap().doc, before, "export doesn't change the document");
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "effect.expandAppearance", json!({}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
let (mut opacity, mut multiplies) = (1.0_f32, 0);
s.doc().unwrap().doc.walk(|n| {
assert!(n.appearance.effects.iter().all(|e| !e.id.starts_with("plugin.")), "no plug-in effect left");
opacity *= n.opacity;
multiplies += usize::from(n.blend == vectorcraft_color::BlendMode::Multiply);
});
assert_eq!((opacity, multiplies), (0.5, 1), "the look applies once");
let img = drawn(&s);
assert_eq!((img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50)), (inside, grown, outside), "expanded, it draws the same");
run(&mut s, "edit.undo", json!({}));
assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.looks");
}
/// On a fill, a painted effect returns only fills: they replace that fill on each piece. A result
/// that breaks a rule (strokes from an effect on a fill, a swatch the document doesn't have) is
/// refused whole: the object is drawn as if the effect weren't there, and `plugin.info` names the
+82
View File
@@ -481,6 +481,44 @@ fn arb_object() -> impl Strategy<Value = (Option<usize>, Value)> {
})
}
/// The keys a piece or a fill or stroke of an effect that declares `appearanceOutput` may carry:
/// opacity, a blending mode (known, wrongly spelled or junk) and effect records (built-in ones
/// with random parameters, plug-in effects including the effect itself, junk), up to past the cap.
fn arb_look() -> impl Strategy<Value = Map<String, Value>> {
let id = prop_oneof![
Just(json!("path.offsetPath")),
Just(json!("stylize.dropShadow")),
Just(json!("distort.twist")),
Just(json!("blur.gaussianBlur")),
Just(json!("threeD.extrude")),
Just(json!("plugin.fuzz.looks")),
arb_junk(),
];
let params = prop_oneof![Just(Value::Null), arb_num().prop_map(|n| json!({"offset": n, "angle": n, "radius": n, "opacity": n})), arb_junk()];
let record = (id, params, prop::option::of(prop_oneof![any::<bool>().prop_map(Value::from), arb_junk()])).prop_map(|(id, params, visible)| {
let mut r = Map::new();
r.insert("id".into(), id);
if !params.is_null() {
r.insert("params".into(), params);
}
if let Some(v) = visible {
r.insert("visible".into(), v);
}
Value::Object(r)
});
let blend = prop_oneof![Just(json!("Multiply")), Just(json!("Screen")), Just(json!("multiply")), arb_junk()];
let effects = prop_oneof![prop::collection::vec(record, 0..20).prop_map(Value::from), arb_junk()];
(prop::option::of(arb_num()), prop::option::of(blend), prop::option::of(effects)).prop_map(|(opacity, blend, effects)| {
let mut m = Map::new();
for (k, v) in [("opacity", opacity), ("blend", blend), ("effects", effects)] {
if let Some(v) = v {
m.insert(k.into(), v);
}
}
m
})
}
/// The output document: objects (ids resolved against `inputs`; out-of-range indices become
/// unknown ids), or junk.
fn output(objects: &[(Option<usize>, Value)], inputs: &[u64], junk: Option<Value>) -> String {
@@ -559,6 +597,50 @@ proptest! {
renders(&s, &out)?;
}
/// A live effect that declares `appearanceOutput` returning pieces whose own looks, and their
/// first fill's, are hostile, on objects or on a fill: drawing, export and Expand Appearance
/// never crash.
#[test]
fn hostile_piece_looks_never_crash(
objects in prop::collection::vec((arb_object(), arb_look(), prop::option::of(arb_look())), 0..4),
on_fill in any::<bool>(),
) {
let mut s = rich_session();
s.execute("select.all", &json!({})).unwrap();
let pieces: Vec<(Option<usize>, Value)> = objects
.into_iter()
.map(|((_, mut o), look, fill_look)| {
if let Some(m) = o.as_object_mut() {
m.remove("name");
m.extend(look);
if let (Some(fl), Some(Value::Array(fills))) = (fill_look, m.get_mut("fills"))
&& let Some(first) = fills.first_mut()
{
let mut row = Map::new();
row.insert("paint".into(), first.take());
row.extend(fl);
*first = Value::Object(row);
}
}
(None, o)
})
.collect();
let out = output(&pieces, &[], None);
let manifest = r#"{"id":"fuzz.looks","name":"Fuzz","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#;
install(&mut s, &wat::parse_str(tpl::returning(manifest, &out)).unwrap()).unwrap();
let item = if on_fill { json!(0) } else { Value::Null };
let r = catch_quiet(|| s.execute("effect.apply", &json!({"effect": "plugin.fuzz.looks", "item": item})).map(|_| ()));
if let Err(msg) = r {
return Err(TestCaseError::fail(format!("panicked on {out}: {msg}")));
}
renders(&s, &out)?;
let r = catch_quiet(|| s.execute("effect.expandAppearance", &json!({})).map(|_| ()));
if let Err(msg) = r {
return Err(TestCaseError::fail(format!("expanding panicked on {out}: {msg}")));
}
renders(&s, &out)?;
}
/// An importer's hostile output (`document.open`) either opens a document that renders and
/// exports, or is an error that opens nothing.
#[test]
+16 -11
View File
@@ -327,8 +327,8 @@ capability model proposed for PhotoCraft plug-ins
- `api` is the plug-in API level the manifest is written for: `1` (the default), `2`, which adds the [host
imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and
symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects), or `3`, which
adds a painted live effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces). A higher one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for
are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the
adds a painted live effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces). A higher one is refused.
`plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the
user to grant them. A level 2 effect that declares `paintOutput` needs no other permission than `doc.read` and
`effect.render`.
- Parameter declarations are unchanged by permissions (`params`, below).
@@ -562,10 +562,11 @@ the module's start function, in a run that isn't a filter's run on a document, o
geometry, at any level. Hosts at `api` 1 refuse the manifest for its `api`, so such an effect never draws unpainted
there. A painted effect may say `"api": 3` without other changes.
- `appearanceOutput` (painted live effects at `api` 3 only): `true` lets the pieces, and the fills and strokes they
return, carry [opacity, a blending mode and effects](#opacity-blending-and-effects-on-pieces). `true` is the only value
the key takes; `false`, `null`, another type, an effect without `paintOutput`, another kind or an `api` below 3 is
refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond
`doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its `api`, so such an effect never draws without its looks.
return, carry [opacity, a blending mode and effects](#opacity-blending-and-effects-on-pieces). `true` is the only
value the key takes; `false`, `null`, another type, an effect without `paintOutput`, another kind or an `api` below 3
is refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond
`doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its
`api`, so such an effect never draws without its looks.
- `extensions` (exporters and importers only, and required): 1–8 file extensions, lower-case letters and digits
without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both
list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and
@@ -816,8 +817,9 @@ is a piece drawn by itself, in the order returned, with paints of its own:
- `path` is required; `fillRule` defaults to the object's. `type` and `bounds` may be handed back as given and are
ignored. Any other key (`opacity`, `effects`, `guide`, `locked`, `name`, a top-level `documentData`…) refuses the
result (an effect that declares `appearanceOutput` also takes `opacity`, `blend` and `effects`, [below](#opacity-blending-and-effects-on-pieces)), as does a key that a paint, its color, a gradient stop, a gradient's placement or a freeform point does not
have, such as `opacity` on a solid paint.
result (an effect that declares `appearanceOutput` also takes `opacity`, `blend` and `effects`,
[below](#opacity-blending-and-effects-on-pieces)), as does a key that a paint, its color, a gradient stop, a gradient's
placement or a freeform point does not have, such as `opacity` on a solid paint.
- `fills` and `strokes` take the forms a filter returns ([Input](#input)). A piece without `fills` (or `strokes`) is
painted with the ones the effect was given; an empty list paints none. Given ones replace the object's in order, as
a filter's output sets them: an existing fill or stroke keeps its own effects, opacity and blending, and a new stroke
@@ -877,15 +879,18 @@ fill and stroke the piece returns, three more keys:
`axes` and `name`, a Warp's `version`, a `color`, a Levels or Curves `channel`, a Radial Blur's center and the
Pathfinder Options. Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are
taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke
returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.<id>`), this effect's own included, is refused, so the effects a piece carries never
run a plug-in.
returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.<id>`),
this effect's own included, is refused, so the effects a piece carries never run a plug-in.
- Left out, a piece's opacity is the object's, its blending mode Normal and its effects none; a fill or stroke keeps
the opacity, blending and effects it would have without the keys. Given, a piece's opacity multiplies the object's,
and its effects and a fill's or stroke's come after the ones it already has. The object's own opacity, blending mode
and later effects still apply once to all the pieces together.
- A piece's geometry effects reshape it before the effects after this one in the object's stack, which then run on
the reshaped piece once. Its raster effects draw on the piece. What the geometry effects make counts against the
budget of the object's geometry effects, with the pieces.
budget of the object's geometry effects, with the pieces: each piece's effects run within what the pieces and the
pieces before it leave of it. When a piece's effects would go past that, or a Transform effect would make fewer
copies than it asks for, the pieces after it are not built, none of the effect's pieces are drawn, and the object, or
the fill or stroke the effect is on, draws the geometry it was given.
- A bad value refuses the whole result as any other fault does, naming the field: for example
`objects[1].blend: unknown blending mode; …` or `objects[0].fills[1].effects[2]: plug-in effects are not allowed in
returned effects`. Without `appearanceOutput`, the three keys are refused as before.