Merge main into fix/plugin-remove-revision-under-lock

# Conflicts:
#	docs/mcp.md
This commit is contained in:
dotCooCoo
2026-11-08 18:57:28 -08:00
114 changed files with 4943 additions and 541 deletions
+135 -25
View File
@@ -5,20 +5,25 @@
//! sees them ([`Paints`]): an effect can draw as wide as the stroke it sits on, or tell its fills
//! apart, without asking for them again as parameters.
//!
//! An effect whose manifest declares `"paintOutput": true` returns painted pieces instead
//! ([`apply_painted`], [`crate::painted`]): each is drawn by itself with paints of its own.
//!
//! Drawing evaluates effects often (every frame, hit tests, bounds), so results are cached by
//! plug-in installation, parameters, input geometry and paints: the plug-in runs again only when
//! one of them changes. Failures are cached too (the geometry is then drawn unchanged) and
//! reported by [`last_error`].
//! reported by [`last_error`]. The swatches and patterns a painted result names are checked
//! against the document each time it is used.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use vectorcraft_doc::{Appearance, AppearanceItem};
use vectorcraft_doc::{Appearance, AppearanceItem, Document};
use vectorcraft_geom::{FillRule, PathData, Rect};
use crate::objects::{decode, output_geometry, paint_lists};
use crate::painted::{self, Piece, Scope};
use crate::{Error, Kind, Limits, Result, registry};
/// The effect id prefix of live-effect plug-ins: `plugin.<plug-in id>`.
@@ -88,6 +93,15 @@ impl Paints<'_> {
};
Given { fills, strokes, item }
}
/// Where the effect sits: what the pieces of an effect that declares `paintOutput` may paint.
fn scope(&self) -> Scope {
match self.appearance.zip(self.item).and_then(|(ap, i)| ap.items.get(i)) {
Some(AppearanceItem::Fill(_)) => Scope::Fill,
Some(AppearanceItem::Stroke(_)) => Scope::Stroke,
None => Scope::Object,
}
}
}
#[derive(PartialEq)]
@@ -117,9 +131,27 @@ impl Key {
}
}
/// What one run of a live effect gave: geometry, or the painted pieces of an effect that declares
/// `paintOutput` ([`crate::painted`]).
#[derive(Clone, Debug, PartialEq)]
enum Out {
Path(PathData),
Pieces(Arc<Vec<Piece>>),
}
impl Out {
/// The geometry: the path, or every piece's path in order.
fn geometry(&self) -> PathData {
match self {
Out::Path(p) => p.clone(),
Out::Pieces(pieces) => PathData::new(pieces.iter().flat_map(|p| p.path.subpaths.iter().cloned()).collect()),
}
}
}
#[derive(Default)]
struct Cache {
entries: HashMap<u64, (Key, Option<PathData>)>,
entries: HashMap<u64, (Key, Option<Out>)>,
/// The anchors of the entries' inputs and results ([`CACHE_ANCHORS`]).
anchors: usize,
}
@@ -131,10 +163,16 @@ fn anchors(p: &PathData) -> usize {
p.subpaths.iter().map(|sp| sp.anchors.len() + 1).sum()
}
/// Cache units an entry takes: its input and result paths, and the serialized parameters and
/// paints its key owns (one unit per [`CACHE_ANCHORS`]'s 50 bytes an anchor stands for).
fn weight(key: &Key, out: Option<&PathData>) -> usize {
anchors(&key.path) + out.map_or(0, anchors) + (key.params.len() + key.paints.len()) / 50 + 1
/// Cache units an entry takes: its input and result paths, the serialized parameters and paints its
/// key owns (one unit per [`CACHE_ANCHORS`]'s 50 bytes an anchor stands for), and one for each
/// paint, gradient stop and freeform point a painted result holds.
fn weight(key: &Key, out: Option<&Out>) -> usize {
let out = match out {
None => 0,
Some(Out::Path(p)) => anchors(p),
Some(Out::Pieces(pieces)) => pieces.iter().map(|p| anchors(&p.path) + 1).sum::<usize>() + painted::paint_count(pieces),
};
anchors(&key.path) + out + (key.params.len() + key.paints.len()) / 50 + 1
}
static ERRORS: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
@@ -194,21 +232,77 @@ pub fn last_error(id: &str) -> Option<String> {
ERRORS.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.get(id).cloned()
}
fn note(id: &str, r: &Result<PathData>) {
/// Records how a run of plug-in `id` went: a failure as its last error (a painted effect's named
/// after the plug-in, [`painted::named`]), a success clearing it.
fn note(id: &str, plugin: &crate::Plugin, r: std::result::Result<(), &Error>) {
let mut errors = ERRORS.lock().unwrap_or_else(|e| e.into_inner());
let errors = errors.get_or_insert_with(HashMap::new);
match r {
Ok(_) => errors.remove(id),
Ok(()) => errors.remove(id),
Err(e) if plugin.manifest().paint_output => errors.insert(id.to_string(), painted::named(&plugin.manifest().name, e)),
Err(e) => errors.insert(id.to_string(), e.to_string()),
};
}
/// Does live-effect plug-in `id` return painted pieces (its manifest declares `paintOutput`)?
pub fn paints_output(id: &str) -> bool {
registry::get(id).is_some_and(|p| p.manifest().kind == Kind::Effect && p.manifest().paint_output)
}
/// Runs live-effect plug-in `id` on `path` (whose reference box is `bounds`), of an object painted
/// with `paints`: the new geometry, or `None` when the plug-in isn't installed, isn't an effect,
/// fails, or Safe Mode is on (the caller then keeps the geometry, and the object keeps its effect).
/// The launch marker names the plug-in during its first run in this process, and until every run
/// that started while it ran has ended too ([`crate::safe_mode::loading`]).
pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints) -> Option<PathData> {
/// For an effect that returns painted pieces, the geometry is every piece's path in order, and
/// `None` when the swatches and patterns they name are refused as [`apply_painted`] refuses them.
pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints, doc: Option<&Document>) -> Option<PathData> {
let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?;
if let Out::Pieces(pieces) = &out {
references_found(id, &plugin, pieces, doc)?;
}
Some(out.geometry())
}
/// Runs live-effect plug-in `id`, which declares `paintOutput`, as [`apply`] does: its painted
/// pieces, each to draw by itself in order with the paints it gives ([`painted::appearance`],
/// [`painted::items`]). Every swatch and pattern the pieces name must be in `doc`; without a
/// document, pieces that name one are refused ([`painted::check_references`]). A paint linked to a
/// global swatch has that swatch's current color. `None` when the
/// plug-in isn't installed, doesn't declare `paintOutput`, fails, or Safe Mode is on; the caller then
/// draws its input unchanged, and [`last_error`] says why a run failed (a refusal for want of a
/// document is not recorded).
pub fn apply_painted(
id: &str,
params: &Value,
path: &PathData,
bounds: Rect,
rule: FillRule,
paints: Paints,
doc: Option<&Document>,
) -> Option<Arc<Vec<Piece>>> {
let (plugin, out) = evaluate(id, params, path, bounds, rule, paints)?;
let Out::Pieces(pieces) = out else { return None };
references_found(id, &plugin, &pieces, doc)?;
Some(match doc {
Some(d) => painted::with_swatch_colors(pieces, d),
None => pieces,
})
}
/// `Some` when every swatch and pattern `pieces` name is in `doc` ([`painted::check_references`]),
/// recording the outcome for [`last_error`] when there is a document. The document's swatches and
/// patterns can change while a result stays cached, so each use checks them.
fn references_found(id: &str, plugin: &crate::Plugin, pieces: &[Piece], doc: Option<&Document>) -> Option<()> {
let checked = painted::check_references(pieces, doc);
if doc.is_some() {
note(id, plugin, checked.as_ref().map(|_| ()));
}
checked.ok()
}
/// Runs plug-in `id` as [`apply`] says, or takes its result from the cache: the plug-in and what
/// it gave. The launch marker names the plug-in during its first run in this process, and until
/// every run that started while it ran has ended too ([`crate::safe_mode::loading`]).
fn evaluate(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints) -> Option<(Arc<crate::Plugin>, Out)> {
if crate::safe_mode::active() {
return None;
}
@@ -227,10 +321,11 @@ pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: Fill
if let Some((k, out)) = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().and_then(|c| c.entries.get(&h))
&& *k == key
{
return out.clone();
return out.clone().map(|o| (plugin, o));
}
let scope = paints.scope();
let guarded = begin_run(&plugin);
let r = run(&plugin, resolved, path, bounds, rule, given);
let r = run(&plugin, resolved, path, bounds, rule, given, scope);
let cancelled = matches!(r, Err(Error::Cancelled));
if guarded {
end_run(plugin.serial(), cancelled);
@@ -239,11 +334,11 @@ pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: Fill
if cancelled {
return None;
}
note(id, &r);
note(id, &plugin, r.as_ref().map(|_| ()));
let out = r.ok();
let size = weight(&key, out.as_ref());
if size > CACHE_ANCHORS / 4 {
return out;
return out.map(|o| (plugin, o));
}
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
let cache = cache.get_or_insert_with(Cache::default);
@@ -254,22 +349,28 @@ pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: Fill
cache.anchors = cache.anchors.saturating_sub(weight(&old, old_out.as_ref()));
}
cache.anchors += size;
out
out.map(|o| (plugin, o))
}
/// One run of `plugin` on `path`, with the object's paints as `given`.
fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule, given: Given) -> Result<PathData> {
/// One run of `plugin` on `path`, with the object's paints as `given`: geometry, or for an effect
/// that declares `paintOutput` its pieces, checked for an effect in `scope`.
fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule, given: Given, scope: Scope) -> Result<Out> {
let b = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]);
params["_context"] = json!({"mode": "effect", "bounds": b, "item": given.item});
let rule = match rule {
let rule_name = match rule {
FillRule::NonZero => "nonzero",
FillRule::EvenOdd => "evenodd",
};
let input = json!({"objects": [{"type": "path", "path": path, "fillRule": rule, "bounds": b, "fills": given.fills, "strokes": given.strokes}]});
let input =
json!({"objects": [{"type": "path", "path": path, "fillRule": rule_name, "bounds": b, "fills": given.fills, "strokes": given.strokes}]});
let (input, params) = (serde_json::to_vec(&input), serde_json::to_vec(&params));
let (Ok(input), Ok(params)) = (input, params) else { return Err(Error::Params("can't encode the input".into())) };
let limits = Limits { wall_time_ms: WALL_TIME_MS, ..plugin.limits().clone() };
Ok(output_geometry(decode(&plugin.run_limited(&input, &params, &limits)?)?))
let output = plugin.run_limited(&input, &params, &limits)?;
if plugin.manifest().paint_output {
return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?)));
}
Ok(Out::Path(output_geometry(decode(&output)?)))
}
#[cfg(test)]
@@ -309,8 +410,17 @@ mod tests {
let plugin = registry::install(crate::Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap());
let ran_first =
|| RUNS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|r| matches!(r.get(&plugin.serial()), Some(Runs::Done)));
let draw =
|| apply("test.effect.cancelled", &json!({}), &PathData::default(), Rect::new(0.0, 0.0, 1.0, 1.0), FillRule::NonZero, Paints::default());
let draw = || {
apply(
"test.effect.cancelled",
&json!({}),
&PathData::default(),
Rect::new(0.0, 0.0, 1.0, 1.0),
FillRule::NonZero,
Paints::default(),
None,
)
};
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
assert_eq!(vectorcraft_doc::cancel::scope(&token, None, draw), None);
+3 -1
View File
@@ -21,7 +21,8 @@
//! their geometry, fills, strokes (gradients included) and opacity. An **object filter** returns
//! the objects to keep, change or add, applied to the document as one edit
//! ([`objects::apply_output`]); a **live effect** ([`effect`]) rewrites one object's geometry each
//! time it is drawn, from an appearance stack; an **exporter** ([`export`]) writes the whole
//! time it is drawn, from an appearance stack, and at `api` 2 may paint what it returns
//! ([`painted`]); an **exporter** ([`export`]) writes the whole
//! document in a file format of its own; an **importer** ([`import`]) reads a file in a format of
//! its own into a new document. The process-wide [`registry`] holds the installed
//! plug-ins; in [`safe_mode`] none of them loads or runs. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show
@@ -38,6 +39,7 @@ pub mod host;
pub mod import;
pub mod manifest;
pub mod objects;
pub mod painted;
pub mod permissions;
pub mod registry;
mod runtime;
+51
View File
@@ -292,6 +292,10 @@ pub struct Manifest {
/// How much a run may compute: only a filter may be [`Budget::Heavy`].
#[serde(default, skip_serializing_if = "Budget::is_light")]
pub budget: Budget,
/// A live effect at `api` 2 that returns painted pieces ([`crate::painted`]): `true` when the
/// manifest has `"paintOutput": true`, the only value the key may hold.
#[serde(default, rename = "paintOutput", skip_serializing_if = "std::ops::Not::not")]
pub paint_output: bool,
/// The menu commands it adds, in menu order (a filter or a live effect only).
#[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")]
pub commands: Vec<Command>,
@@ -304,6 +308,9 @@ impl Manifest {
return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len())));
}
let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?;
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
return Err(Error::Manifest("`paintOutput` may only be true".into()));
}
let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
man.validate()?;
Ok(man)
@@ -323,6 +330,7 @@ impl Manifest {
params: Vec::new(),
extensions: Vec::new(),
budget: Budget::Light,
paint_output: false,
commands: Vec::new(),
}
}
@@ -362,6 +370,9 @@ impl Manifest {
let permission = host.name();
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
}
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into()));
}
self.validate_extensions()?;
match (self.budget, self.kind) {
(Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {}
@@ -929,6 +940,46 @@ mod tests {
}
}
/// A live effect at `api` 2 may declare `"paintOutput": true`, and only that value; any other
/// kind or level, and `false`, `null` or another type, is refused naming the key. Without the
/// key, at any level, the effect returns geometry only.
#[test]
fn only_a_level_2_live_effect_declares_paint_output() {
let painted = Manifest::parse(br#"{"id":"org.example.tone","name":"Tone","kind":"effect","api":2,"paintOutput":true}"#).unwrap();
assert!(painted.paint_output);
assert_eq!(serde_json::to_value(&painted).unwrap()["paintOutput"], json!(true));
let listed =
Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"permissions":["doc.read","effect.render"]}"#)
.unwrap();
assert!(listed.paint_output);
for plain in [r#"{"id":"a","name":"x","kind":"effect","api":2}"#, r#"{"id":"a","name":"x","kind":"effect"}"#] {
let m = Manifest::parse(plain.as_bytes()).unwrap();
assert!(!m.paint_output, "{plain}");
assert!(serde_json::to_value(&m).unwrap().get("paintOutput").is_none(), "{plain}");
}
for bad in [
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":false}"#,
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":null}"#,
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":1}"#,
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":"true"}"#,
r#"{"id":"a","name":"x","kind":"effect","paintOutput":true}"#,
r#"{"id":"a","name":"x","kind":"effect","api":1,"paintOutput":true}"#,
r#"{"id":"a","name":"x","kind":"filter","api":2,"paintOutput":true}"#,
r#"{"id":"a","name":"x","kind":"exporter","api":2,"extensions":["plt"],"paintOutput":true}"#,
r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"permissions":["doc.read"]}"#,
] {
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
assert!(e.contains("paintOutput") || e.contains("effect.render"), "{bad}: {e}");
}
}
#[test]
fn commands_and_paint_output_may_both_be_declared_on_a_live_effect() {
let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"commands":[{"id":"c","label":"C"}]}"#).unwrap();
assert!(m.paint_output);
assert_eq!(m.commands.len(), 1);
}
/// A filter or a live effect lists menu commands with their own parameters; a `menu` key is
/// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many
/// commands are refused, and the error names the command.
+5 -5
View File
@@ -162,11 +162,11 @@ pub fn encode_input(doc: &Document, ids: &[NodeId]) -> Vec<u8> {
serde_json::to_vec(&json!({ "objects": objects })).unwrap_or_default()
}
fn out_err(at: &str, msg: impl std::fmt::Display) -> Error {
pub(crate) fn out_err(at: &str, msg: impl std::fmt::Display) -> Error {
Error::Output(format!("{at}: {msg}"))
}
fn check_point(p: Point, at: &str) -> Result<()> {
pub(crate) fn check_point(p: Point, at: &str) -> Result<()> {
if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD {
Ok(())
} else {
@@ -176,7 +176,7 @@ fn check_point(p: Point, at: &str) -> Result<()> {
/// A path from plug-in output: native `PathData` JSON, every coordinate finite and in range, empty
/// subpaths dropped; `anchors` counts towards [`MAX_ANCHORS`].
fn decode_path(v: &Value, at: &str, anchors: &mut usize) -> Result<PathData> {
pub(crate) fn decode_path(v: &Value, at: &str, anchors: &mut usize) -> Result<PathData> {
let mut path: PathData = serde_json::from_value(v.clone()).map_err(|e| out_err(at, e))?;
path.subpaths.retain(|sp| !sp.anchors.is_empty());
*anchors = anchors.saturating_add(path.anchor_count());
@@ -486,7 +486,7 @@ fn admit_paint(doc: &Document, p: Paint, was: Option<&Paint>, at: &str) -> Resul
/// Sets the paints of `ap`'s fills (`fill`) or strokes to `new` (a fill keeps everything but its
/// paint), in paint order: extra items are removed (from the top), missing ones added above the
/// last item of their kind (fills at the bottom, strokes on top when the object has none).
fn set_items(ap: &mut Appearance, fill: bool, new: Vec<OutStroke>) {
pub(crate) fn set_items(ap: &mut Appearance, fill: bool, new: Vec<OutStroke>) {
let idx: Vec<usize> = ap.items.iter().enumerate().filter(|(_, i)| i.is_fill() == fill).map(|(k, _)| k).collect();
for &i in idx.iter().skip(new.len()).rev() {
ap.remove_item(i);
@@ -513,7 +513,7 @@ fn set_items(ap: &mut Appearance, fill: bool, new: Vec<OutStroke>) {
}
/// Gives stroke `s` the paint of `o` and each of its weight, join, cap and miter limit it has.
fn style(s: &mut StrokeLayer, o: OutStroke) {
pub(crate) fn style(s: &mut StrokeLayer, o: OutStroke) {
s.paint = o.paint;
s.width = o.width.unwrap_or(s.width);
s.join = o.join.unwrap_or(s.join);
+447
View File
@@ -0,0 +1,447 @@
//! What a live effect that declares `"paintOutput": true` (at `api` 2) returns: painted pieces.
//!
//! Such an effect returns `{"objects": [...]}` as any live effect does, but each entry is a piece
//! drawn by itself, in the order returned, with paints of its own: `{"path", "fillRule"?,
//! "fills"?, "strokes"?}`. Fills and strokes take the forms a filter returns ([`crate::objects`]).
//! A piece without `fills` (or `strokes`) keeps the ones it was given; an empty list paints none.
//! An effect on a fill may return only `fills`, one on a stroke only `strokes`.
//!
//! The result is checked whole before any of it is used ([`decode`]): every number finite and in
//! range (nothing is clamped), every key known, and every swatch and pattern a paint names in the
//! document ([`check_references`]). One fault refuses the whole result, naming the field.
use serde_json::Value;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, LineCap, LineJoin};
use vectorcraft_geom::{FillRule, PathData};
use crate::objects::{MAX_COORD, MAX_ITEMS, MAX_OBJECTS, MAX_STROKE_WIDTH, MITER_LIMIT, OutStroke, check_point, out_err};
use crate::{Error, Result};
/// The keys a piece may have. `type` and `bounds` are read back from the input as it was given and
/// say nothing about the piece.
const PIECE_KEYS: [&str; 6] = ["type", "path", "fillRule", "bounds", "fills", "strokes"];
/// The keys a stroke of a piece may have.
const STROKE_KEYS: [&str; 5] = ["paint", "width", "join", "cap", "miterLimit"];
/// One piece a live effect returned: its geometry and fill rule, and its fills and strokes in paint
/// order (`None`: the ones it was given).
#[derive(Clone, Debug, PartialEq)]
pub struct Piece {
pub path: PathData,
pub rule: FillRule,
pub fills: Option<Vec<Paint>>,
pub strokes: Option<Vec<OutStroke>>,
}
/// Where in an appearance the effect sits, which says what its pieces may paint.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
/// One of the object's effects: a piece may return fills and strokes.
Object,
/// One of a fill's own effects: a piece may return only `fills`.
Fill,
/// One of a stroke's own effects: a piece may return only `strokes`.
Stroke,
}
/// Parses and checks a painted result: `{"objects": [...]}`, or `{"error": "message"}` when the
/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. Any other top-level
/// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of
/// range or a paint of the wrong form refuses the whole result, naming the field.
pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result<Vec<Piece>> {
let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?;
if let Some(e) = crate::objects::declined(&v) {
return Err(e);
}
let top = v.as_object().ok_or_else(|| out_err("output", "expected {\"objects\": [...]}"))?;
if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error")) {
return Err(out_err(k, "a painted live effect returns only `objects`"));
}
let objects = top.get("objects").and_then(Value::as_array).ok_or_else(|| out_err("objects", "expected {\"objects\": [...]}"))?;
if objects.len() > MAX_OBJECTS {
return Err(out_err("objects", format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
}
let mut anchors = 0;
objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut anchors)).collect()
}
fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) -> Result<Piece> {
let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?;
if let Some(k) = o.keys().find(|k| !PIECE_KEYS.contains(&k.as_str())) {
return Err(out_err(&format!("{at}.{k}"), "a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes`"));
}
if let Some(t) = o.get("type")
&& !matches!(t.as_str(), Some("path" | "compound"))
{
return Err(out_err(&format!("{at}.type"), "`type` must be \"path\" or \"compound\""));
}
let path = o.get("path").ok_or_else(|| out_err(&format!("{at}.path"), "each piece needs a `path`"))?;
// At most MAX_ANCHORS over all pieces.
let path = crate::objects::decode_path(path, &format!("{at}.path"), anchors)?;
let rule = match o.get("fillRule") {
None => rule,
Some(r) => match r.as_str() {
Some("nonzero") => FillRule::NonZero,
Some("evenodd") => FillRule::EvenOdd,
_ => return Err(out_err(&format!("{at}.fillRule"), "`fillRule` must be \"nonzero\" or \"evenodd\"")),
},
};
let list = |key: &str| -> Result<Option<&Vec<Value>>> {
match o.get(key) {
None => Ok(None),
Some(Value::Array(a)) if a.len() <= MAX_ITEMS => Ok(Some(a)),
Some(_) => Err(out_err(&format!("{at}.{key}"), format!("`{key}` must be an array of at most {MAX_ITEMS} entries"))),
}
};
let (fills, strokes) = (list("fills")?, list("strokes")?);
match scope {
Scope::Fill if strokes.is_some() => return Err(out_err(&format!("{at}.strokes"), "an effect on a fill returns only `fills`")),
Scope::Stroke if fills.is_some() => return Err(out_err(&format!("{at}.fills"), "an effect on a stroke returns only `strokes`")),
_ => {}
}
let fills = fills.map(|f| f.iter().enumerate().map(|(i, p)| paint(p, &format!("{at}.fills[{i}]"))).collect::<Result<Vec<_>>>()).transpose()?;
let strokes =
strokes.map(|s| s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"))).collect::<Result<Vec<_>>>()).transpose()?;
Ok(Piece { path, rule, fills, strokes })
}
/// A stroke `{paint, width?, join?, cap?, miterLimit?}`: a width of 0–[`MAX_STROKE_WIDTH`] and a
/// miter limit in [`MITER_LIMIT`].
fn stroke(v: &Value, at: &str) -> Result<OutStroke> {
let s = v.as_object().ok_or_else(|| out_err(at, "a stroke must be {\"paint\", \"width\"?, \"join\"?, \"cap\"?, \"miterLimit\"?}"))?;
if let Some(k) = s.keys().find(|k| !STROKE_KEYS.contains(&k.as_str())) {
return Err(out_err(&format!("{at}.{k}"), "a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit`"));
}
let number = |key: &str, range: std::ops::RangeInclusive<f64>| -> Result<Option<f64>> {
let Some(v) = s.get(key) else { return Ok(None) };
match v.as_f64().filter(|x| x.is_finite() && range.contains(x)) {
Some(x) => Ok(Some(x)),
None => Err(out_err(&format!("{at}.{key}"), format!("`{key}` must be a number from {} to {}", range.start(), range.end()))),
}
};
let join = match s.get("join").map(Value::as_str) {
None => None,
Some(Some("miter")) => Some(LineJoin::Miter),
Some(Some("round")) => Some(LineJoin::Round),
Some(Some("bevel")) => Some(LineJoin::Bevel),
Some(_) => return Err(out_err(&format!("{at}.join"), "`join` must be \"miter\", \"round\" or \"bevel\"")),
};
let cap = match s.get("cap").map(Value::as_str) {
None => None,
Some(Some("butt")) => Some(LineCap::Butt),
Some(Some("round")) => Some(LineCap::Round),
Some(Some("square")) => Some(LineCap::Square),
Some(_) => return Err(out_err(&format!("{at}.cap"), "`cap` must be \"butt\", \"round\" or \"square\"")),
};
let paint = paint(s.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?;
Ok(OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? })
}
/// Is `x` finite and in `lo..=hi`?
fn within(x: f64, lo: f64, hi: f64) -> bool {
x.is_finite() && (lo..=hi).contains(&x)
}
fn in_range(x: f32, lo: f32, hi: f32, at: &str, what: &str) -> Result<()> {
if within(f64::from(x), f64::from(lo), f64::from(hi)) { Ok(()) } else { Err(out_err(at, format!("{what} must be from {lo} to {hi}"))) }
}
/// A color with every component in range: 0–1, or Lab's L 0–100 and a, b −128–127.
fn color(c: &Color, at: &str) -> Result<()> {
let unit = |x: f32| in_range(x, 0.0, 1.0, at, "a color component");
match *c {
Color::Rgb { r, g, b } => [r, g, b].into_iter().try_for_each(unit),
Color::Cmyk { c, m, y, k } => [c, m, y, k].into_iter().try_for_each(unit),
Color::Gray { k } => unit(k),
Color::Lab { l, a, b } => {
in_range(l, 0.0, 100.0, at, "Lab's L")?;
in_range(a, -128.0, 127.0, at, "Lab's a")?;
in_range(b, -128.0, 127.0, at, "Lab's b")
}
}
}
/// Refuses a key of object `v` that is not in `keys`, naming it after `at`. A value that is not an
/// object passes, and deserializing it reports the fault.
fn only_keys(v: &Value, at: &str, keys: &[&str]) -> Result<()> {
match v.as_object().and_then(|o| o.keys().find(|k| !keys.contains(&k.as_str()))) {
Some(k) => Err(out_err(&format!("{at}.{k}"), format!("unknown key `{k}`; the keys here are {}", keys.join(", ")))),
None => Ok(()),
}
}
/// [`only_keys`] for a color, whose keys follow its `model`. An unknown model passes, and
/// deserializing it reports the fault.
fn color_keys(v: &Value, at: &str) -> Result<()> {
let keys: &[&str] = match v.get("model").and_then(Value::as_str) {
Some("rgb") => &["model", "r", "g", "b"],
Some("cmyk") => &["model", "c", "m", "y", "k"],
Some("gray") => &["model", "k"],
Some("lab") => &["model", "l", "a", "b"],
_ => return Ok(()),
};
only_keys(v, at, keys)
}
/// [`only_keys`] for a point `{x, y}`.
fn point_keys(v: Option<&Value>, at: &str) -> Result<()> {
v.map_or(Ok(()), |v| only_keys(v, at, &["x", "y"]))
}
/// Calls `f` on each entry of the array at `v`, named `at[i]`.
fn each(v: Option<&Value>, at: &str, f: impl Fn(&Value, &str) -> Result<()>) -> Result<()> {
v.and_then(Value::as_array).into_iter().flatten().enumerate().try_for_each(|(i, e)| f(e, &format!("{at}[{i}]")))
}
/// Refuses an unknown key at any level of paint `v`: the paint itself, its colors, a gradient's
/// stops, placement and freeform points. Deserializing a paint drops unknown keys, so a key such
/// as `opacity` on a solid paint would otherwise be accepted and do nothing.
fn paint_keys(v: &Value, at: &str) -> Result<()> {
match v.get("type").and_then(Value::as_str) {
Some("none") => only_keys(v, at, &["type"]),
Some("solid") => {
only_keys(v, at, &["type", "color", "swatch", "tint"])?;
v.get("color").map_or(Ok(()), |c| color_keys(c, &format!("{at}.color")))
}
Some("pattern") => only_keys(v, at, &["type", "pattern", "xf"]),
Some("gradient") => {
only_keys(v, at, &["type", "gradient", "geom", "angle", "swatch", "freeform"])?;
if let Some(g) = v.get("gradient") {
let at = format!("{at}.gradient");
only_keys(g, &at, &["kind", "stops", "dither", "method"])?;
each(g.get("stops"), &format!("{at}.stops"), |s, at| {
only_keys(s, at, &["offset", "color", "opacity", "midpoint", "swatch", "tint", "plates"])?;
s.get("color").map_or(Ok(()), |c| color_keys(c, &format!("{at}.color")))
})?;
}
if let Some(geom) = v.get("geom") {
let at = format!("{at}.geom");
only_keys(geom, &at, &["start", "end", "aspect", "focal"])?;
["start", "end", "focal"].into_iter().try_for_each(|k| point_keys(geom.get(k), &format!("{at}.{k}")))?;
}
if let Some(ff) = v.get("freeform") {
let at = format!("{at}.freeform");
only_keys(ff, &at, &["points", "lines", "mode"])?;
each(ff.get("points"), &format!("{at}.points"), |p, at| {
only_keys(p, at, &["at", "color", "opacity", "spread"])?;
point_keys(p.get("at"), &format!("{at}.at"))?;
p.get("color").map_or(Ok(()), |c| color_keys(c, &format!("{at}.color")))
})?;
}
Ok(())
}
_ => Ok(()),
}
}
/// A paint as the filter form has it (`null`: none), checked rather than clamped: colors, tints,
/// stops, opacities, midpoints and placements in range.
fn paint(v: &Value, at: &str) -> Result<Paint> {
if v.is_null() {
return Ok(Paint::None);
}
paint_keys(v, at)?;
let p: Paint = serde_json::from_value(v.clone()).map_err(|e| out_err(at, e))?;
let unit = |x: f32, at: &str, what: &str| in_range(x, 0.0, 1.0, at, what);
match &p {
Paint::None => {}
Paint::Solid { color: c, tint, .. } => {
color(c, &format!("{at}.color"))?;
unit(*tint, &format!("{at}.tint"), "`tint`")?;
}
Paint::Gradient(g) => {
let stops = &g.gradient.stops;
if stops.is_empty() || stops.len() > MAX_ITEMS {
return Err(out_err(&format!("{at}.gradient.stops"), format!("a gradient needs 1-{MAX_ITEMS} stops")));
}
for (i, s) in stops.iter().enumerate() {
let at = format!("{at}.gradient.stops[{i}]");
unit(s.offset, &format!("{at}.offset"), "`offset`")?;
unit(s.opacity, &format!("{at}.opacity"), "`opacity`")?;
in_range(s.midpoint, 0.13, 0.87, &format!("{at}.midpoint"), "`midpoint`")?;
unit(s.tint, &format!("{at}.tint"), "`tint`")?;
color(&s.color, &format!("{at}.color"))?;
for x in s.plates.iter().flatten() {
unit(*x, &format!("{at}.plates"), "a plate")?;
}
}
if stops.windows(2).any(|w| w[1].offset < w[0].offset) {
return Err(out_err(&format!("{at}.gradient.stops"), "stops must be in order of `offset`"));
}
if !g.angle.is_finite() {
return Err(out_err(&format!("{at}.angle"), "`angle` must be a number"));
}
if let Some(geom) = &g.geom {
check_point(geom.start, &format!("{at}.geom.start"))?;
check_point(geom.end, &format!("{at}.geom.end"))?;
if let Some(f) = geom.focal {
check_point(f, &format!("{at}.geom.focal"))?;
}
if !within(geom.aspect, 0.01, 100.0) {
return Err(out_err(&format!("{at}.geom.aspect"), "`aspect` must be from 0.01 to 100"));
}
}
if let Some(ff) = &g.freeform {
if ff.points.len() > MAX_ITEMS || ff.lines.len() > MAX_ITEMS || ff.lines.iter().any(|l| l.len() > MAX_ITEMS) {
return Err(out_err(&format!("{at}.freeform"), format!("a freeform gradient holds at most {MAX_ITEMS} points and lines")));
}
if ff.lines.iter().flatten().any(|i| *i >= ff.points.len()) {
return Err(out_err(&format!("{at}.freeform.lines"), "a freeform gradient line names a point it doesn't have"));
}
for (i, pt) in ff.points.iter().enumerate() {
let at = format!("{at}.freeform.points[{i}]");
check_point(pt.at, &format!("{at}.at"))?;
color(&pt.color, &format!("{at}.color"))?;
unit(pt.opacity, &format!("{at}.opacity"), "`opacity`")?;
unit(pt.spread, &format!("{at}.spread"), "`spread`")?;
}
}
}
Paint::Pattern { xf, .. } => {
if !xf.as_coeffs().iter().all(|c| within(*c, -MAX_COORD, MAX_COORD)) {
return Err(out_err(&format!("{at}.xf"), "pattern transform out of range"));
}
}
}
Ok(p)
}
/// Checks that every swatch a solid paint, gradient or gradient stop of `pieces` links to is a
/// swatch of `doc`, and every pattern a pattern paint names is one of its patterns. Without a
/// document (`None`), any swatch or pattern a piece names is refused.
pub fn check_references(pieces: &[Piece], doc: Option<&Document>) -> Result<()> {
let swatch = |name: &Option<String>, at: &str| match name {
Some(n) if doc.and_then(|d| d.swatch(n)).is_none() => Err(out_err(at, format!("the document has no swatch {n:?}"))),
_ => Ok(()),
};
let check = |p: &Paint, at: &str| -> Result<()> {
match p {
Paint::None => Ok(()),
Paint::Solid { swatch: s, .. } => swatch(s, &format!("{at}.swatch")),
Paint::Gradient(g) => {
swatch(&g.swatch, &format!("{at}.swatch"))?;
g.gradient.stops.iter().enumerate().try_for_each(|(i, s)| swatch(&s.swatch, &format!("{at}.gradient.stops[{i}].swatch")))
}
Paint::Pattern { pattern, .. } if doc.and_then(|d| d.pattern(pattern)).is_none() => {
Err(out_err(&format!("{at}.pattern"), format!("the document has no pattern {pattern:?}")))
}
Paint::Pattern { .. } => Ok(()),
}
};
for (i, p) in pieces.iter().enumerate() {
for (k, f) in p.fills.iter().flatten().enumerate() {
check(f, &format!("objects[{i}].fills[{k}]"))?;
}
for (k, s) in p.strokes.iter().flatten().enumerate() {
check(&s.paint, &format!("objects[{i}].strokes[{k}].paint"))?;
}
}
Ok(())
}
/// The current color of a paint or stop linked to global swatch `name` at `tint`, when it differs
/// from `color`.
fn newer_color(color: Color, name: Option<&str>, tint: f32, doc: &Document) -> Option<Color> {
doc.global_color(name?).map(|c| c.tinted(tint)).filter(|c| *c != color)
}
/// Does `p` hold a color older than the global swatch it is linked to?
fn behind_swatches(p: &Paint, doc: &Document) -> bool {
match p {
Paint::Solid { color, swatch, tint } => newer_color(*color, swatch.as_deref(), *tint, doc).is_some(),
Paint::Gradient(g) => g.gradient.stops.iter().any(|s| newer_color(s.color, s.swatch.as_deref(), s.tint, doc).is_some()),
Paint::None | Paint::Pattern { .. } => false,
}
}
/// Gives a solid paint or gradient stop of `p` linked to a global swatch that swatch's current
/// color at its own tint.
fn take_swatch_colors(p: &mut Paint, doc: &Document) {
match p {
Paint::Solid { color, swatch, tint } => {
if let Some(c) = newer_color(*color, swatch.as_deref(), *tint, doc) {
*color = c;
}
}
Paint::Gradient(g) => {
for s in &mut g.gradient.stops {
if let Some(c) = newer_color(s.color, s.swatch.as_deref(), s.tint, doc) {
s.color = c;
}
}
}
Paint::None | Paint::Pattern { .. } => {}
}
}
/// `pieces` with every paint linked to a global swatch of `doc` in that swatch's current color, as
/// a global swatch edit changes linked art. A paint linked to a swatch that isn't global keeps the
/// color the plug-in gave.
pub(crate) fn with_swatch_colors(mut pieces: std::sync::Arc<Vec<Piece>>, doc: &Document) -> std::sync::Arc<Vec<Piece>> {
let behind =
|p: &Piece| p.fills.iter().flatten().any(|f| behind_swatches(f, doc)) || p.strokes.iter().flatten().any(|s| behind_swatches(&s.paint, doc));
if pieces.iter().any(behind) {
for p in std::sync::Arc::make_mut(&mut pieces) {
p.fills.iter_mut().flatten().for_each(|f| take_swatch_colors(f, doc));
p.strokes.iter_mut().flatten().for_each(|s| take_swatch_colors(&mut s.paint, doc));
}
}
pieces
}
/// How many paints, gradient stops and freeform points `pieces` hold: what a cache counts them as
/// besides their anchors.
pub(crate) fn paint_count(pieces: &[Piece]) -> usize {
let one = |p: &Paint| match p {
Paint::Gradient(g) => 1 + g.gradient.stops.len() + g.freeform.as_ref().map_or(0, |f| f.points.len()),
_ => 1,
};
pieces.iter().map(|p| p.fills.iter().flatten().map(one).sum::<usize>() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::<usize>()).sum()
}
/// The appearance piece `p` of an object-level effect is drawn with: `base` (the object's) with
/// its fills, then its strokes, replaced by the piece's where it has them, as a filter's output
/// sets them (an existing item keeps everything but what the piece gives; new ones take the
/// defaults).
pub fn appearance(base: &Appearance, p: &Piece) -> Appearance {
let mut ap = base.clone();
if let Some(fills) = &p.fills {
crate::objects::set_items(&mut ap, true, fills.iter().cloned().map(OutStroke::paint).collect());
}
if let Some(strokes) = &p.strokes {
crate::objects::set_items(&mut ap, false, strokes.clone());
}
ap
}
/// The items piece `p` of an effect on `item` (a fill or a stroke) is drawn with, in paint order:
/// `item` itself when the piece keeps it, else one copy of it for each paint or stroke the piece
/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given).
pub fn items(item: &AppearanceItem, p: &Piece) -> Vec<AppearanceItem> {
match item {
AppearanceItem::Fill(f) => match &p.fills {
None => vec![item.clone()],
Some(fills) => fills.iter().map(|paint| AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() })).collect(),
},
AppearanceItem::Stroke(s) => match &p.strokes {
None => vec![item.clone()],
Some(strokes) => strokes
.iter()
.map(|o| {
let mut s = s.clone();
crate::objects::style(&mut s, o.clone());
AppearanceItem::Stroke(s)
})
.collect(),
},
}
}
/// An error naming `name`, the plug-in, before what went wrong (`plugin.info`'s `lastError`).
pub(crate) fn named(name: &str, e: &Error) -> String {
format!("{name}: {e}")
}
#[cfg(test)]
mod tests;
+241
View File
@@ -0,0 +1,241 @@
use serde_json::json;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, StrokeLayer};
use super::*;
const SQUARE: &str = r#"{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[10,0]},{"p":[10,10]},{"p":[0,10]}]}]}"#;
fn red() -> Value {
serde_json::to_value(Paint::solid(Color::rgb(1.0, 0.0, 0.0))).unwrap()
}
fn out(pieces: Value) -> Vec<u8> {
serde_json::to_vec(&json!({ "objects": pieces })).unwrap()
}
fn square() -> Value {
serde_json::from_str(SQUARE).unwrap()
}
/// Each piece keeps its own paints in the order returned; a piece without `fills` or `strokes`
/// keeps the ones it was given (`None`) and an empty list paints none.
#[test]
fn pieces_keep_their_own_paints_in_order() {
let blue = serde_json::to_value(Paint::solid(Color::rgb(0.0, 0.0, 1.0))).unwrap();
let pieces = decode(
&out(json!([
{"path": square(), "fills": [red()], "strokes": [{"paint": blue, "width": 4, "join": "round", "cap": "square", "miterLimit": 2}]},
{"type": "path", "path": square(), "fillRule": "evenodd", "fills": [], "bounds": [0, 0, 10, 10]},
{"path": square()},
])),
Scope::Object,
FillRule::NonZero,
)
.unwrap();
assert_eq!(pieces.len(), 3);
assert_eq!(pieces[0].fills, Some(vec![Paint::solid(Color::rgb(1.0, 0.0, 0.0))]));
let s = &pieces[0].strokes.as_ref().unwrap()[0];
assert_eq!((s.width, s.join, s.cap, s.miter_limit), (Some(4.0), Some(LineJoin::Round), Some(LineCap::Square), Some(2.0)));
assert_eq!((pieces[1].rule, pieces[1].fills.as_deref(), &pieces[1].strokes), (FillRule::EvenOdd, Some(&[][..]), &None));
assert_eq!((pieces[2].rule, &pieces[2].fills, &pieces[2].strokes), (FillRule::NonZero, &None, &None));
}
/// A solid paint or gradient stop linked to a global swatch takes the swatch's color at its own
/// tint. A link to a swatch that isn't global and a paint without a link keep the color given.
#[test]
fn linked_paints_take_the_global_swatch_color() {
let brand = Color::rgb(0.2, 0.4, 0.6);
let mut doc = Document::new(100.0, 100.0);
doc.swatches.push(Swatch { name: "Brand".into(), paint: Paint::solid(brand), global: true, spot: false });
doc.swatches.push(Swatch { name: "Plain".into(), paint: Paint::solid(brand), global: false, spot: false });
let given = json!({"model": "rgb", "r": 1, "g": 1, "b": 0});
let solid = |extra: Value| {
let mut p = json!({"type": "solid", "color": given});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
p
};
let stop = json!({"offset": 0, "color": given, "swatch": "Brand", "tint": 0.5});
let gradient = json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [stop]}});
let fills = json!([solid(json!({"swatch": "Brand", "tint": 0.5})), solid(json!({"swatch": "Plain"})), solid(json!({})), gradient]);
let strokes = json!([{"paint": solid(json!({"swatch": "Brand"}))}]);
let pieces = decode(&out(json!([{"path": square(), "fills": fills, "strokes": strokes}])), Scope::Object, FillRule::NonZero).unwrap();
let pieces = with_swatch_colors(std::sync::Arc::new(pieces), &doc);
let color = |p: &Paint| match p {
Paint::Solid { color, .. } => *color,
Paint::Gradient(g) => g.gradient.stops[0].color,
_ => panic!("{p:?}"),
};
let fills = pieces[0].fills.as_ref().unwrap();
let old = Color::rgb(1.0, 1.0, 0.0);
assert_eq!([color(&fills[0]), color(&fills[1]), color(&fills[2]), color(&fills[3])], [brand.tinted(0.5), old, old, brand.tinted(0.5)]);
assert_eq!(color(&pieces[0].strokes.as_ref().unwrap()[0].paint), brand);
}
/// What a piece is drawn with: the object's appearance with the paints the piece gives in place of
/// its own (kept, cleared or replaced), and for an effect on one fill or stroke, copies of that item.
#[test]
fn a_piece_s_appearance_inherits_or_replaces() {
let base = Appearance {
items: vec![
AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE))),
AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 3.0)),
],
..Appearance::default()
};
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let piece =
|fills: Option<Vec<Paint>>, strokes: Option<Vec<OutStroke>>| Piece { path: PathData::default(), rule: FillRule::NonZero, fills, strokes };
assert_eq!(appearance(&base, &piece(None, None)), base, "inherited");
let ap = appearance(&base, &piece(Some(vec![red.clone()]), Some(vec![])));
assert_eq!(ap.items.len(), 1);
assert_eq!(ap.items[0].paint(), &red);
let ap = appearance(&base, &piece(None, Some(vec![OutStroke { width: Some(8.0), ..OutStroke::paint(red.clone()) }])));
let AppearanceItem::Stroke(s) = &ap.items[1] else { panic!("a stroke") };
assert_eq!((s.width, &s.paint), (8.0, &red));
let two = items(&base.items[0], &piece(Some(vec![red.clone(), Paint::None]), None));
assert_eq!(two.iter().map(|i| i.paint().clone()).collect::<Vec<_>>(), [red.clone(), Paint::None]);
assert_eq!(items(&base.items[1], &piece(None, None)), vec![base.items[1].clone()]);
let none = items(&base.items[1], &piece(None, Some(vec![])));
assert!(none.is_empty());
}
/// An effect on a fill returns only fills, one on a stroke only strokes.
#[test]
fn an_item_s_effect_paints_only_its_kind() {
let fills = out(json!([{"path": square(), "fills": [red()]}]));
let strokes = out(json!([{"path": square(), "strokes": [{"paint": red()}]}]));
assert!(decode(&fills, Scope::Fill, FillRule::NonZero).is_ok());
assert!(decode(&strokes, Scope::Stroke, FillRule::NonZero).is_ok());
let e = decode(&strokes, Scope::Fill, FillRule::NonZero).unwrap_err().to_string();
assert!(e.contains("objects[0].strokes"), "{e}");
let e = decode(&fills, Scope::Stroke, FillRule::NonZero).unwrap_err().to_string();
assert!(e.contains("objects[0].fills"), "{e}");
}
/// Every fault refuses the whole result and names its field; nothing is clamped.
#[test]
fn faults_refuse_the_whole_result_by_field() {
let ok = json!({"path": square(), "fills": [red()]});
let stop = |offset: f64| json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [{"offset": offset, "color": {"model": "rgb", "r": 0, "g": 0, "b": 0}}]}});
let many: Vec<Value> = (0..=MAX_ITEMS).map(|_| red()).collect();
let stops: Vec<Value> = (0..=MAX_ITEMS).map(|_| json!({"offset": 0, "color": {"model": "gray", "k": 0}})).collect();
for (piece, at) in [
(json!({"path": square(), "fills": [{"type": "plaid"}]}), "objects[1].fills[0]"),
(json!({"path": square(), "fills": [{"type": "solid", "color": {"model": "rgb", "r": 2, "g": 0, "b": 0}}]}), "objects[1].fills[0].color"),
(json!({"path": square(), "fills": [{"type": "solid", "color": {"model": "rgb", "r": 1e300, "g": 0, "b": 0}}]}), "objects[1].fills[0].color"),
(json!({"path": square(), "fills": [{"type": "solid", "color": {"model": "gray", "k": 0.5}, "tint": 1.5}]}), "objects[1].fills[0].tint"),
(json!({"path": square(), "strokes": [{"paint": red(), "width": 1001}]}), "objects[1].strokes[0].width"),
(json!({"path": square(), "strokes": [{"paint": red(), "width": -1}]}), "objects[1].strokes[0].width"),
(json!({"path": square(), "strokes": [{"paint": red(), "miterLimit": 0.5}]}), "objects[1].strokes[0].miterLimit"),
(json!({"path": square(), "strokes": [{"paint": red(), "join": "wobbly"}]}), "objects[1].strokes[0].join"),
(json!({"path": square(), "strokes": [{"paint": red(), "dashes": [1, 2]}]}), "objects[1].strokes[0].dashes"),
(json!({"path": square(), "fills": [stop(1.5)]}), "objects[1].fills[0].gradient.stops[0].offset"),
(
json!({"path": square(), "fills": [{"type": "gradient", "gradient": {"kind": "Linear", "stops": stops}}]}),
"objects[1].fills[0].gradient.stops",
),
(json!({"path": square(), "fills": many}), "objects[1].fills"),
(json!({"path": square(), "fills": [red()], "opacity": 0.5}), "objects[1].opacity"),
(json!({"path": square(), "effects": []}), "objects[1].effects"),
(json!({"path": square(), "guide": true}), "objects[1].guide"),
(json!({"path": square(), "locked": true}), "objects[1].locked"),
(json!({"fills": [red()]}), "objects[1].path"),
(json!({"path": square(), "fillRule": "inside"}), "objects[1].fillRule"),
(json!({"path": {"subpaths": [{"closed": true, "anchors": [{"p": [1e9, 0]}]}]}}), "objects[1].path"),
] {
let e = decode(&out(json!([ok, piece])), Scope::Object, FillRule::NonZero).unwrap_err();
let e = e.to_string();
assert!(e.contains(&format!("{at}:")), "{at}: {e}");
}
let e = decode(&serde_json::to_vec(&json!({"objects": [ok], "documentData": {}})).unwrap(), Scope::Object, FillRule::NonZero).unwrap_err();
assert!(e.to_string().contains("documentData"), "{e}");
let declined = decode(br#"{"error":"nothing to do"}"#, Scope::Object, FillRule::NonZero).unwrap_err();
assert_eq!(declined, Error::Failed("nothing to do".into()));
}
/// A key a paint does not have, at any level of it, refuses the result and is named; it is not
/// dropped.
#[test]
fn unknown_keys_inside_a_paint_are_refused_by_field() {
let gray = json!({"model": "gray", "k": 0});
let stop = |extra: Value| {
let mut s = json!({"offset": 0, "color": gray});
s.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [s]}})
};
let point = json!({"x": 0, "y": 0});
for (fill, at) in [
(json!({"type": "solid", "color": {"model": "rgb", "r": 1, "g": 0, "b": 0}, "opacity": 0.5}), "objects[0].fills[0].opacity"),
(json!({"type": "solid", "color": {"model": "gray", "k": 0, "alpha": 0.5}}), "objects[0].fills[0].color.alpha"),
(json!({"type": "none", "color": gray}), "objects[0].fills[0].color"),
(json!({"type": "pattern", "pattern": "Dots", "scale": 2}), "objects[0].fills[0].scale"),
(stop(json!({"blend": "multiply"})), "objects[0].fills[0].gradient.stops[0].blend"),
(stop(json!({"color": {"model": "lab", "l": 50, "a": 0, "b": 0, "c": 1}})), "objects[0].fills[0].gradient.stops[0].color.c"),
(
json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [{"offset": 0, "color": gray}], "opacity": 0.5}}),
"objects[0].fills[0].gradient.opacity",
),
(
json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [{"offset": 0, "color": gray}]}, "opacity": 0.5}),
"objects[0].fills[0].opacity",
),
(
json!({"type": "gradient", "gradient": {"kind": "Radial", "stops": [{"offset": 0, "color": gray}]},
"geom": {"start": point, "end": {"x": 1, "y": 0, "z": 0}}}),
"objects[0].fills[0].geom.end.z",
),
(
json!({"type": "gradient", "gradient": {"kind": "Freeform", "stops": [{"offset": 0, "color": gray}]},
"freeform": {"points": [{"at": point, "color": gray, "glow": 1}]}}),
"objects[0].fills[0].freeform.points[0].glow",
),
] {
let e = decode(&out(json!([{"path": square(), "fills": [fill]}])), Scope::Object, FillRule::NonZero).unwrap_err().to_string();
assert!(e.contains(&format!("{at}:")), "{at}: {e}");
}
let e = decode(
&out(json!([{"path": square(), "strokes": [{"paint": {"type": "solid", "color": gray, "opacity": 0.5}}]}])),
Scope::Object,
FillRule::NonZero,
)
.unwrap_err()
.to_string();
assert!(e.contains("objects[0].strokes[0].paint.opacity:"), "{e}");
// Every key a paint does have is still taken.
let full = json!({"type": "gradient", "angle": 30, "swatch": "Ramp",
"gradient": {"kind": "Freeform", "dither": true, "method": "Perceptual",
"stops": [{"offset": 0, "color": gray, "opacity": 1, "midpoint": 0.5, "swatch": "Ink", "tint": 0.5, "plates": [0, 0, 0, 0]}]},
"geom": {"start": point, "end": {"x": 1, "y": 0}, "aspect": 1, "focal": point},
"freeform": {"points": [{"at": point, "color": gray, "opacity": 1, "spread": 0.5}], "lines": [[0]], "mode": "lines"}});
let solid = json!({"type": "solid", "color": {"model": "cmyk", "c": 0, "m": 0, "y": 0, "k": 1}, "swatch": "Ink", "tint": 0.5});
let pattern = json!({"type": "pattern", "pattern": "Dots", "xf": [1, 0, 0, 1, 0, 0]});
assert!(
decode(&out(json!([{"path": square(), "fills": [full, solid, pattern, {"type": "none"}, null]}])), Scope::Object, FillRule::NonZero).is_ok()
);
}
/// The swatches and patterns a piece's paints name must be in the document.
#[test]
fn named_swatches_and_patterns_must_exist() {
let mut doc = Document::new(100.0, 100.0);
doc.swatches.push(Swatch { name: "Brand".into(), paint: Paint::solid(Color::rgb(0.2, 0.4, 0.6)), global: true, spot: false });
let linked = |name: &str| json!({"type": "solid", "color": {"model": "rgb", "r": 0.2, "g": 0.4, "b": 0.6}, "swatch": name});
let pieces = |pieces: Value| decode(&out(pieces), Scope::Object, FillRule::NonZero).unwrap();
let check = |p: Value| check_references(&pieces(p), Some(&doc));
assert!(check(json!([{"path": square(), "fills": [linked("Brand")]}])).is_ok());
let e = check(json!([{"path": square()}, {"path": square(), "strokes": [{"paint": linked("Gone")}]}])).unwrap_err().to_string();
assert!(e.contains("objects[1].strokes[0].paint.swatch"), "{e}");
let stop =
json!({"type": "gradient", "gradient": {"kind": "Linear", "stops": [{"offset": 0, "color": {"model": "gray", "k": 0}, "swatch": "Gone"}]}});
let e = check(json!([{"path": square(), "fills": [stop]}])).unwrap_err().to_string();
assert!(e.contains("objects[0].fills[0].gradient.stops[0].swatch"), "{e}");
let e = check(json!([{"path": square(), "fills": [{"type": "pattern", "pattern": "Dots"}]}])).unwrap_err().to_string();
assert!(e.contains("objects[0].fills[0].pattern"), "{e}");
// Without a document to look them up in, no swatch or pattern may be named.
assert!(check_references(&pieces(json!([{"path": square(), "fills": [red()]}])), None).is_ok());
let e = check_references(&pieces(json!([{"path": square(), "fills": [linked("Brand")]}])), None).unwrap_err().to_string();
assert!(e.contains("objects[0].fills[0].swatch"), "{e}");
let e = check_references(&pieces(json!([{"path": square(), "fills": [{"type": "pattern", "pattern": "Dots"}]}])), None).unwrap_err().to_string();
assert!(e.contains("objects[0].fills[0].pattern"), "{e}");
}
+2 -1
View File
@@ -14,7 +14,8 @@ use serde::{Deserialize, Serialize};
use crate::{Error, Kind, Result};
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
/// this.
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
/// ([`crate::painted`]).
pub const API_LEVEL: u32 = 2;
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,