mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into feat/plugin-api-context-menus
This commit is contained in:
255 files changed
+16955
-1226
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`,
|
||||
//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters).
|
||||
//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one
|
||||
//! (docs/plugins.md › Parameters).
|
||||
//!
|
||||
//! These keys are presentation only. A host from before them ignores them, so a plug-in that
|
||||
//! declares them still installs there, and a plug-in is given every parameter whether its dialog
|
||||
@@ -58,6 +59,48 @@ pub struct ParamUi {
|
||||
/// Shown only while each parameter named here has one of the values listed for it.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub visible_when: BTreeMap<String, Vec<Value>>,
|
||||
/// The control that shows a number: [`Widget::Slider`] adds a slider beside its field.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub widget: Option<Widget>,
|
||||
}
|
||||
|
||||
/// The control a `number` or `int` parameter's row shows besides its number field (`widget`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Widget {
|
||||
/// A slider over `min..max`, beside the number field.
|
||||
Slider,
|
||||
}
|
||||
|
||||
/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range.
|
||||
const EXACT_INT: i64 = 1 << 53;
|
||||
|
||||
impl ParamUi {
|
||||
/// The range a slider shows `spec`'s value over, when the parameter asks for one
|
||||
/// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on.
|
||||
pub fn slider_range(&self, spec: &ParamSpec) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
if self.widget != Some(Widget::Slider) {
|
||||
return None;
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max),
|
||||
ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `widget` against parameter `spec`; `bad` builds the error.
|
||||
fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> {
|
||||
if self.widget.is_none() || self.slider_range(spec).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
match spec {
|
||||
ParamSpec::Number { .. } | ParamSpec::Int { .. } => {
|
||||
bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}"))
|
||||
}
|
||||
_ => bad("a slider is only for `number` and `int` parameters"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless
|
||||
@@ -86,6 +129,9 @@ impl ParamUi {
|
||||
return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes"));
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = m.params.get(index) {
|
||||
self.validate_slider(&p.spec, bad)?;
|
||||
}
|
||||
if self.visible_when.len() > MAX_CONDITIONS {
|
||||
return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters"));
|
||||
}
|
||||
@@ -304,4 +350,46 @@ mod tests {
|
||||
let fine = with("help", r#""Two\nlines.""#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
/// A `number` or `int` parameter with a range may ask for a slider; the key reads back as
|
||||
/// written, and a parameter without it asks for none.
|
||||
#[test]
|
||||
fn slider_key_parses_and_round_trips() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","params":{
|
||||
"area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"},
|
||||
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
|
||||
"plain":{"type":"number","min":0,"max":100,"default":10}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap());
|
||||
assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0));
|
||||
assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0));
|
||||
assert_eq!(plain.ui.slider_range(&plain.spec), None);
|
||||
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slider_keys_that_cannot_apply_are_refused() {
|
||||
let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#);
|
||||
for bad in [
|
||||
// Only numbers have a slider, over a range that has room to move.
|
||||
r#"{"type":"bool","widget":"slider"}"#,
|
||||
r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#,
|
||||
r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#,
|
||||
r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#,
|
||||
r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#,
|
||||
// A control the host doesn't have.
|
||||
r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#,
|
||||
] {
|
||||
assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}");
|
||||
}
|
||||
// A command's parameters are checked the same way.
|
||||
let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#);
|
||||
assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok());
|
||||
assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err());
|
||||
let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#);
|
||||
assert!(Manifest::parse(fine.as_bytes()).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission};
|
||||
use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -608,6 +608,11 @@ pub struct Manifest {
|
||||
/// lists them. Left out or empty, it is given paths and compound paths alone.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
|
||||
pub inputs: Vec<String>,
|
||||
/// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at
|
||||
/// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or
|
||||
/// empty, every kind it reads stays read-only.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")]
|
||||
pub writes: Vec<String>,
|
||||
/// The parts of the document a run is given in `_context.document`, by
|
||||
/// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command
|
||||
/// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty,
|
||||
@@ -671,6 +676,7 @@ impl Manifest {
|
||||
api: 1,
|
||||
permissions: None,
|
||||
inputs: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
context: Vec::new(),
|
||||
params: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
@@ -759,6 +765,7 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_inputs()?;
|
||||
self.validate_writes()?;
|
||||
self.validate_context()?;
|
||||
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()));
|
||||
@@ -859,6 +866,37 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at
|
||||
/// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`.
|
||||
fn validate_writes(&self) -> Result<()> {
|
||||
if self.writes.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.kind != Kind::Filter {
|
||||
return Err(Error::Manifest("only a filter declares `writes`".into()));
|
||||
}
|
||||
for (i, name) in self.writes.iter().enumerate() {
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
if InputKind::parse(name).is_none() {
|
||||
return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance")));
|
||||
}
|
||||
if self.writes.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}` twice")));
|
||||
}
|
||||
if !self.inputs.contains(name) {
|
||||
return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list")));
|
||||
}
|
||||
}
|
||||
if self.api < WRITES_API {
|
||||
return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later")));
|
||||
}
|
||||
let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name()));
|
||||
if !listed(Permission::DocWrite) {
|
||||
return Err(Error::Manifest("`writes` needs the permission `doc.write`".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect
|
||||
/// with commands, at `api` 3 or later lists any, with a `permissions` list that holds
|
||||
/// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]).
|
||||
@@ -932,6 +970,11 @@ impl Manifest {
|
||||
self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// The kinds among those it reads that it may change (`writes`).
|
||||
pub fn write_kinds(&self) -> Vec<InputKind> {
|
||||
self.writes.iter().filter_map(|n| InputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16
|
||||
/// lower-case letters and digits; other kinds list none.
|
||||
fn validate_extensions(&self) -> Result<()> {
|
||||
@@ -1101,6 +1144,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `writes` as [`input_names`] reads `inputs`.
|
||||
fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance");
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `context`: a list of names (`null`: none). Anything else is the error
|
||||
/// [`Manifest::validate_context`] gives a wrong entry.
|
||||
fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
@@ -1587,6 +1640,64 @@ mod tests {
|
||||
assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice"));
|
||||
}
|
||||
|
||||
/// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with
|
||||
/// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key
|
||||
/// isn't written back. Anything else is refused naming `writes`.
|
||||
#[test]
|
||||
fn a_filter_at_api_3_lists_the_kinds_it_writes() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.write_kinds(), InputKind::ALL);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"]));
|
||||
let some = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image]));
|
||||
for none in [
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"filter","writes":null}"#,
|
||||
] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.write_kinds().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}");
|
||||
}
|
||||
let rw = r#""permissions":["doc.read","doc.write"]"#;
|
||||
for (bad, says) in [
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#),
|
||||
"`writes` names an unknown object kind `text`",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#),
|
||||
"`writes` lists `type` twice",
|
||||
),
|
||||
(
|
||||
format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#),
|
||||
"`writes` lists `image`, which `inputs` doesn't list",
|
||||
),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"),
|
||||
(format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`writes` needs the permission `doc.write`",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(),
|
||||
"`inputs` needs the permission `doc.read`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document
|
||||
/// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks
|
||||
/// for approval. Left out or empty, it asks for none and isn't written back. Anything else is
|
||||
|
||||
@@ -82,6 +82,10 @@ pub struct OutObject {
|
||||
/// A read-only input object (type, an image or a symbol instance) returned as it was given:
|
||||
/// it stays as it is, and new objects listed after it go above it.
|
||||
pub kept: bool,
|
||||
/// A type object, an image or a symbol instance of a kind the filter may change (`writes`)
|
||||
/// returned with changes: the fields it changes, by their names in the input, checked when
|
||||
/// they are applied ([`apply_output`]).
|
||||
pub edit: Option<serde_json::Map<String, Value>>,
|
||||
}
|
||||
|
||||
/// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's
|
||||
@@ -295,7 +299,7 @@ fn affine_json(xf: Affine) -> Value {
|
||||
/// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style
|
||||
/// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`]
|
||||
/// or [`MAX_INPUT_RUNS`];
|
||||
/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`,
|
||||
/// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`]
|
||||
/// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks
|
||||
/// through the working CMYK profile, as sRGB). A linked image's file and path are never read or
|
||||
@@ -332,6 +336,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left
|
||||
if let Some(q) = n.image_quad() {
|
||||
o["corners"] = json!(q.map(|p| [p.x, p.y]));
|
||||
}
|
||||
o["opacity"] = json!(n.opacity);
|
||||
o["pixelSize"] = json!([im.width, im.height]);
|
||||
o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode));
|
||||
o["linked"] = json!(im.link.is_some());
|
||||
@@ -672,6 +677,15 @@ fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// An object's name from plug-in output (`null`: no name), without control characters and at most
|
||||
/// 256 of them.
|
||||
fn decode_name(n: &Value, at: &str) -> Result<String> {
|
||||
Ok(match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn opt<'a>(o: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value> {
|
||||
o.get(key).filter(|v| !v.is_null())
|
||||
}
|
||||
@@ -693,11 +707,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject>
|
||||
});
|
||||
}
|
||||
if let Some(n) = o.get("name") {
|
||||
let name = match n {
|
||||
Value::Null => String::new(),
|
||||
n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
};
|
||||
out.name = Some(name);
|
||||
out.name = Some(decode_name(n, at)?);
|
||||
}
|
||||
if let Some(p) = opt(o, "path") {
|
||||
out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?);
|
||||
@@ -813,8 +823,18 @@ pub fn decode_output(bytes: &[u8]) -> Result<Output> {
|
||||
/// differs, before anything changes. Each object is parsed from `input` only to compare it, one at
|
||||
/// a time, and an object that can't be read from there is an error.
|
||||
pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result<Output> {
|
||||
decode_output_writing(bytes, input, read_only, &[])
|
||||
}
|
||||
|
||||
/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them
|
||||
/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may
|
||||
/// leave fields out, which keep their values, and give its name, its transform, and type's
|
||||
/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed.
|
||||
/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is
|
||||
/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't.
|
||||
pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Output> {
|
||||
let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
let objects = decode_objects(&v, input, read_only)?;
|
||||
let objects = decode_objects(&v, input, read_only, writes)?;
|
||||
let document_data = match v.get_mut("documentData").map(Value::take) {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
@@ -896,12 +916,12 @@ fn draws_nothing(c: char) -> bool {
|
||||
/// declined (the message reaches the user). A live effect's other keys don't matter.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Vec<OutObject>> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
decode_objects(&v, &[], &HashMap::new())
|
||||
decode_objects(&v, &[], &HashMap::new(), &[])
|
||||
}
|
||||
|
||||
/// The objects of output `v`, or its decline; entries for `read_only` objects as
|
||||
/// [`decode_output_with`] reads them.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<Vec<OutObject>> {
|
||||
/// [`decode_output_writing`] reads them, those of kinds `writes` changeable.
|
||||
fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result<Vec<OutObject>> {
|
||||
if let Some(e) = declined(v) {
|
||||
return Err(e);
|
||||
}
|
||||
@@ -910,6 +930,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
|
||||
}
|
||||
let mut anchors = 0;
|
||||
// Bytes of type text the output writes, over all its objects.
|
||||
let mut text = 0;
|
||||
let mut returned: HashSet<NodeId> = HashSet::new();
|
||||
let out = objects
|
||||
.iter()
|
||||
@@ -920,12 +942,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result<
|
||||
if !returned.insert(id) {
|
||||
return Err(out_err(&at, "is listed twice"));
|
||||
}
|
||||
let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() };
|
||||
// `{"id": …}` alone keeps the object, so there is nothing to compare it with.
|
||||
if o.as_object().is_none_or(|m| m.len() != 1) {
|
||||
let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) };
|
||||
let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?;
|
||||
let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k));
|
||||
let Some(kind) = kind else {
|
||||
check_unchanged(o, &given, &at)?;
|
||||
}
|
||||
Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() })
|
||||
return Ok(kept);
|
||||
};
|
||||
Ok(match writes::changes(entry, &given, kind, &at, &mut text)? {
|
||||
Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() },
|
||||
None => kept,
|
||||
})
|
||||
}
|
||||
None => decode_object(o, &format!("objects[{i}]"), &mut anchors),
|
||||
})
|
||||
@@ -951,28 +980,40 @@ fn output_id(o: &Value) -> Option<NodeId> {
|
||||
/// numbers compared by value. Otherwise the error names the first field that differs
|
||||
/// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the
|
||||
/// plug-in's.
|
||||
/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left
|
||||
/// out, so an entry that a filter built for level 2 writes as it was given there still matches.
|
||||
fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> {
|
||||
let changed = match (o, given) {
|
||||
(Value::Object(x), Value::Object(y)) => {
|
||||
let mut keys: Vec<&String> = x.keys().collect();
|
||||
keys.sort();
|
||||
keys.into_iter().find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
keys.into_iter()
|
||||
.find_map(|k| match y.get(k) {
|
||||
Some(q) => first_difference(&x[k], q, k),
|
||||
None => Some(k.clone()),
|
||||
})
|
||||
.or_else(|| {
|
||||
let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name());
|
||||
let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect();
|
||||
missing.sort();
|
||||
missing.first().map(|k| (*k).clone())
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
_ => first_difference(o, given, ""),
|
||||
};
|
||||
match changed.or_else(|| first_difference(o, given, "")) {
|
||||
match changed {
|
||||
None => Ok(()),
|
||||
Some(field) => {
|
||||
let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("read-only field '{field}' changed")))
|
||||
}
|
||||
Some(field) => Err(read_only_changed(at, &field)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an entry at `at` that changes read-only `field`, which is shown as
|
||||
/// [`crate::permissions::display_text`] shows a manifest string.
|
||||
fn read_only_changed(at: &str, field: &str) -> Error {
|
||||
let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(at, format!("read-only field '{field}' changed"))
|
||||
}
|
||||
|
||||
/// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they
|
||||
/// are the same JSON with numbers compared by value.
|
||||
fn first_difference(a: &Value, b: &Value, at: &str) -> Option<String> {
|
||||
@@ -1328,7 +1369,9 @@ impl Plan {
|
||||
/// input object, just below the first one listed after them (at the first input object's place
|
||||
/// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing
|
||||
/// from the output are deleted. An object's effect records replace its own once `admit` lets them
|
||||
/// in. Returns the resulting objects in output order (to select).
|
||||
/// in. Type, images and symbol instances stay as they are, or take the changes of their
|
||||
/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order
|
||||
/// (to select).
|
||||
pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>, parent: Option<NodeId>, admit: AdmitEffects) -> Result<Vec<NodeId>> {
|
||||
let wanted: HashSet<NodeId> = inputs.iter().copied().collect();
|
||||
let mut originals: HashMap<NodeId, Node> = HashMap::new();
|
||||
@@ -1353,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec<OutObject>,
|
||||
out_err(&at, format!("{} is not the id of an input object", id.0))
|
||||
}
|
||||
})?;
|
||||
// Type, images and symbol instances are only read: writing one would make it a path.
|
||||
if input_kind(&n).is_some() && !o.kept {
|
||||
return Err(out_err(&at, format!("{} is read-only", id.0)));
|
||||
}
|
||||
// Type, images and symbol instances change only through the fields a filter that
|
||||
// may write them returns: writing one as a path would make it a path.
|
||||
let kept = o.kept;
|
||||
if !kept {
|
||||
if input_kind(&n).is_some() && !kept {
|
||||
let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) };
|
||||
writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?;
|
||||
} else if o.edit.is_some() {
|
||||
return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0)));
|
||||
} else if !kept {
|
||||
write(doc, &mut n, o, &at, admit)?;
|
||||
}
|
||||
if !run.is_empty() {
|
||||
@@ -1415,5 +1461,7 @@ pub fn output_geometry(objects: Vec<OutObject>) -> PathData {
|
||||
PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect())
|
||||
}
|
||||
|
||||
mod writes;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() {
|
||||
}
|
||||
|
||||
/// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by
|
||||
/// value), and they stay as they are, new objects listed after one going just above it. Any change,
|
||||
/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed
|
||||
/// after one going just above it. Any change,
|
||||
/// an object left out or listed twice, and a new object of such a kind are refused before anything
|
||||
/// changes.
|
||||
#[test]
|
||||
@@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
let mut echo = input.clone();
|
||||
echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]);
|
||||
assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok());
|
||||
// An image without `opacity`, as plug-in API level 2 gave it, is the image as given.
|
||||
let mut echo = input.clone();
|
||||
for i in [4, 5] {
|
||||
assert_eq!(echo["objects"][i]["type"], json!("image"));
|
||||
echo["objects"][i].as_object_mut().unwrap().remove("opacity");
|
||||
}
|
||||
let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap();
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5);
|
||||
// So is an id written as a float; a fractional one names no object.
|
||||
let id = input["objects"][3]["id"].as_u64().unwrap();
|
||||
let mut echo = input.clone();
|
||||
@@ -1151,6 +1160,486 @@ fn read_only_kind_field_and_omission_refuse() {
|
||||
assert_eq!(d, before);
|
||||
}
|
||||
|
||||
/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may
|
||||
/// change every kind.
|
||||
fn writable() -> (Document, Vec<NodeId>, Vec<u8>, ReadOnlySpans, [NodeId; 5]) {
|
||||
let (mut d, _, layer, extra) = mixed();
|
||||
let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default()));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false });
|
||||
let targets = filter_targets_with(&d, &[layer], &InputKind::ALL);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap();
|
||||
(d, targets, bytes, read_only, extra)
|
||||
}
|
||||
|
||||
/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`.
|
||||
fn write_out(
|
||||
d: &mut Document,
|
||||
targets: &[NodeId],
|
||||
bytes: &[u8],
|
||||
read_only: &ReadOnlySpans,
|
||||
writes: &[InputKind],
|
||||
out: &Value,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?;
|
||||
apply_output(d, targets, out.objects, None, &keep)
|
||||
}
|
||||
|
||||
/// A filter that may write type, images and symbol instances changes type's runs and character
|
||||
/// attributes, an image's transform and opacity, and the symbol and transform of an instance,
|
||||
/// with entries that give only the fields they change. What it writes reads back the same. An
|
||||
/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing.
|
||||
#[test]
|
||||
fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() {
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle};
|
||||
let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let before = d.clone();
|
||||
let all = &InputKind::ALL;
|
||||
let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap();
|
||||
assert!(echo.objects.iter().all(|o| o.edit.is_none()));
|
||||
apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap();
|
||||
assert_eq!(d, before, "an exact echo changes nothing");
|
||||
let ro = |id: NodeId| json!({"id": id.0});
|
||||
let paths: Vec<Value> = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect();
|
||||
let with = |entries: Vec<Value>| {
|
||||
let objects = [paths.clone(), entries].concat();
|
||||
json!({ "objects": objects })
|
||||
};
|
||||
let same = with(vec![
|
||||
json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}),
|
||||
json!({"id": embedded.0, "opacity": 1}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Star"}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap();
|
||||
assert!(out.objects.iter().all(|o| o.edit.is_none()));
|
||||
assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing");
|
||||
// The changes, each entry giving only what it changes.
|
||||
let big = CharStyle { size: 24.0, ..CharStyle::default() };
|
||||
let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]);
|
||||
let out = with(vec![
|
||||
json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}),
|
||||
json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}),
|
||||
ro(linked),
|
||||
json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}),
|
||||
ro(ghost),
|
||||
]);
|
||||
let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert_eq!(made.len(), targets.len());
|
||||
let node = |id: NodeId| d.node(id).unwrap().clone();
|
||||
let NodeKind::Text(t) = &node(text).kind else { panic!("type") };
|
||||
assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0));
|
||||
assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles");
|
||||
assert_eq!(t.para_at(0), &ParaStyle::default());
|
||||
assert_eq!(node(text).name.as_deref(), Some("Renamed"));
|
||||
let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") };
|
||||
assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5));
|
||||
assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) });
|
||||
for id in [linked, ghost] {
|
||||
assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were");
|
||||
}
|
||||
// Read again, the changed objects give what was written.
|
||||
let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap();
|
||||
assert_eq!(read(text)["text"]["runs"], runs);
|
||||
assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5)));
|
||||
assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0])));
|
||||
assert!(read(star).get("missing").is_none());
|
||||
// An instance of a symbol the document lacks can point to one it has.
|
||||
let mut d = before.clone();
|
||||
let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]);
|
||||
write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap();
|
||||
assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star"));
|
||||
}
|
||||
|
||||
/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in
|
||||
/// `writes`, or gives a value out of range is refused naming the object and the field, before
|
||||
/// anything changes.
|
||||
#[test]
|
||||
fn bad_writes_are_refused_naming_the_object_and_the_field() {
|
||||
use vectorcraft_doc::CharStyle;
|
||||
let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let styled = |f: &dyn Fn(&mut Value)| {
|
||||
let mut s = style.clone();
|
||||
f(&mut s);
|
||||
json!([{"text": "Hi\nthere", "style": s}])
|
||||
};
|
||||
let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0);
|
||||
let (ti, ei, si) = (at(text), at(embedded), at(star));
|
||||
let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![
|
||||
(text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")),
|
||||
(text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")),
|
||||
(text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")),
|
||||
(text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")),
|
||||
(text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style: unknown key 'fontSzie'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}),
|
||||
&InputKind::ALL,
|
||||
"font_family: must be 1-256 printable characters".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.fill: unknown key 'tintt'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke: unknown key 'pattern'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs: expected 3 paragraph styles, one per paragraph".into(),
|
||||
),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()),
|
||||
(text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")),
|
||||
(text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()),
|
||||
(text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()),
|
||||
(text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[0].justification: unknown key 'wordSpacng'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}),
|
||||
&InputKind::ALL,
|
||||
"text.paragraphs[1].tabs[1]: unknown key 'aling'".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}),
|
||||
&InputKind::ALL,
|
||||
"text.runs[0].style.stroke_dash: unknown key 'ofset'".into(),
|
||||
),
|
||||
(
|
||||
text,
|
||||
json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}),
|
||||
&InputKind::ALL,
|
||||
"holds the character of an inline graphic".into(),
|
||||
),
|
||||
(text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()),
|
||||
(text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()),
|
||||
(embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")),
|
||||
(embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")),
|
||||
(embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()),
|
||||
(linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")),
|
||||
(embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")),
|
||||
(
|
||||
star,
|
||||
json!({"symbolId": "Nowhere"}),
|
||||
&InputKind::ALL,
|
||||
format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"),
|
||||
),
|
||||
(star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()),
|
||||
(star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")),
|
||||
(ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()),
|
||||
(star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")),
|
||||
];
|
||||
for (id, entry, writes, says) in cases {
|
||||
let mut out = input.clone();
|
||||
let mut e = entry.clone();
|
||||
e["id"] = json!(id.0);
|
||||
out["objects"][at(id)] = e;
|
||||
let mut doc = d.clone();
|
||||
let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(err.contains(&says), "{entry}: {says}: {err}");
|
||||
assert_eq!(doc, d, "{entry}: nothing changed");
|
||||
}
|
||||
// Leaving a writable object out is still refused: it isn't deleted.
|
||||
let mut out = input.clone();
|
||||
out["objects"].as_array_mut().unwrap().remove(at(star));
|
||||
let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}");
|
||||
}
|
||||
|
||||
/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and
|
||||
/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated`
|
||||
/// keeps its text, though it can still move.
|
||||
#[test]
|
||||
fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
let (mut d, _, layer, [text, ..]) = mixed();
|
||||
let long = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))),
|
||||
);
|
||||
let long = d.insert(Some(layer), usize::MAX, long).unwrap();
|
||||
let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]);
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap();
|
||||
assert_eq!(input["objects"][at(long)]["truncated"], json!(true));
|
||||
let style = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
let run = |s: String| json!({"text": s, "style": style});
|
||||
let writes = &[InputKind::Type];
|
||||
for (id, text_v, says) in [
|
||||
(text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")),
|
||||
(text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)),
|
||||
(text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")),
|
||||
(long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()),
|
||||
] {
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(id)] = json!({"id": id.0, "text": text_v});
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string();
|
||||
assert!(e.contains(&says), "{says}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
// At the limit the text is written; truncated type still moves.
|
||||
let mut out = input.clone();
|
||||
out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}});
|
||||
out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap();
|
||||
assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT));
|
||||
assert!(
|
||||
matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1)
|
||||
);
|
||||
}
|
||||
|
||||
/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs
|
||||
/// around it can change, and adding, removing or changing one is refused.
|
||||
#[test]
|
||||
fn inline_graphics_in_written_type_stay_as_they_were() {
|
||||
use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default());
|
||||
t.runs = vec![
|
||||
TextRun::new("A", CharStyle::default()),
|
||||
TextRun::inline(InlineArt::new("Star"), CharStyle::default()),
|
||||
TextRun::new("B", CharStyle::default()),
|
||||
];
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let input: Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let runs = input["objects"][0]["text"]["runs"].clone();
|
||||
let writes = &[InputKind::Type];
|
||||
let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]});
|
||||
let mut changed = runs.clone();
|
||||
changed[0]["text"] = json!("Before ");
|
||||
changed[2]["text"] = json!(" after");
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), "Before \u{FFFC} after");
|
||||
assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star"));
|
||||
let mut moved = runs.clone();
|
||||
moved[1]["inline"]["symbol"] = json!("Moon");
|
||||
let without = json!([runs[0], runs[2]]);
|
||||
let doubled = json!([runs[0], runs[1], runs[1], runs[2]]);
|
||||
for bad in [moved, without, doubled] {
|
||||
let mut doc = d.clone();
|
||||
let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string();
|
||||
assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}");
|
||||
assert_eq!(doc, d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs
|
||||
/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text
|
||||
/// stays keeps its style, also when changes are made at two places, a paragraph added at the start
|
||||
/// takes the style of the next one and one added later the style of the one before it, and joining
|
||||
/// two paragraphs keeps the first one's style.
|
||||
#[test]
|
||||
fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default());
|
||||
let styled = |justify| ParaStyle { justify, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let justified = |text: &str| {
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
let mut doc = d.clone();
|
||||
write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.plain_text(), text);
|
||||
(0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]);
|
||||
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// Two separate changes: B and C keep their styles.
|
||||
assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
|
||||
// A changed paragraph takes the style of the one it replaces; the one added after it, that style.
|
||||
assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]);
|
||||
assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]);
|
||||
}
|
||||
|
||||
/// A paragraph that a change adds next to a numbered one takes its style without the number, and
|
||||
/// the numbered paragraph keeps it.
|
||||
#[test]
|
||||
fn written_runs_give_an_added_paragraph_no_list_number() {
|
||||
use vectorcraft_doc::text::ParaList;
|
||||
use vectorcraft_doc::{CharStyle, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![ParaStyle::default(), numbered]);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect();
|
||||
assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]);
|
||||
}
|
||||
|
||||
/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order.
|
||||
#[test]
|
||||
fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() {
|
||||
use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
let paras: Vec<String> = (0..600).map(|i| format!("p{i}")).collect();
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default());
|
||||
let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles((0..600).map(styled).collect());
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let id = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let targets = vec![id];
|
||||
let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap();
|
||||
// 600 old paragraphs times 602 new ones: none starts or ends both texts.
|
||||
let text = format!("X\n{}\nY", paras.join("\n"));
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]});
|
||||
write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.paragraph_count(), 602);
|
||||
let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect();
|
||||
let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect();
|
||||
assert_eq!(got, want);
|
||||
}
|
||||
|
||||
/// Every number in the character and paragraph styles a filter writes is checked against the range
|
||||
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
|
||||
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
|
||||
/// object and the field, and the document stays as it was. A set of the document's, given by
|
||||
/// name, takes the document's characters.
|
||||
#[test]
|
||||
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
|
||||
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
|
||||
let (mut d, _, layer, _) = mixed();
|
||||
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
|
||||
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
|
||||
let bad_chars: [(&str, CharStyle, &str); 5] = [
|
||||
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
|
||||
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
|
||||
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
|
||||
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
|
||||
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
|
||||
];
|
||||
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
|
||||
let bad_paras: [(&str, ParaStyle, &str); 4] = [
|
||||
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
|
||||
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
|
||||
(
|
||||
"hyphenation",
|
||||
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
|
||||
"paragraphs[0].hyphenation.after_first",
|
||||
),
|
||||
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
|
||||
];
|
||||
// `own`: the type already has the bad style, and the filter changes only its other run or
|
||||
// paragraph; otherwise the bad style is the filter's own.
|
||||
let run = |id: NodeId, own: bool, bad: &CharStyle| {
|
||||
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
|
||||
if own {
|
||||
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
|
||||
}
|
||||
let mut doc = d.clone();
|
||||
let n = Node::new(id, NodeKind::Text(Box::new(t)));
|
||||
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
(doc, id)
|
||||
};
|
||||
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
|
||||
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let mut entry = entry;
|
||||
entry["id"] = json!(id.0);
|
||||
let mut changed = doc.clone();
|
||||
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
|
||||
assert_eq!(&changed, doc, "{what}: nothing changed");
|
||||
};
|
||||
let fresh = d.clone().alloc_id();
|
||||
for (what, bad, says) in &bad_chars {
|
||||
let (doc, id) = run(fresh, false, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
|
||||
let (doc, id) = run(fresh, true, bad);
|
||||
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
|
||||
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
|
||||
for (what, bad, says) in &bad_paras {
|
||||
let (doc, id) = run(fresh, false, &CharStyle::default());
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
|
||||
let mut doc = doc;
|
||||
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
|
||||
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
|
||||
}
|
||||
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
|
||||
}
|
||||
// A set the document has, by name, takes the document's characters.
|
||||
let (mut doc, id) = run(fresh, false, &CharStyle::default());
|
||||
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
|
||||
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
|
||||
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
|
||||
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
|
||||
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
|
||||
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
|
||||
}
|
||||
|
||||
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
|
||||
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
//! What a filter whose manifest lists `writes` may change about the type, images and symbol
|
||||
//! instances it was given: each one's name and transform; type's runs, with their character
|
||||
//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows.
|
||||
//! Every other field stays read-only, and every value is checked before anything changes.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
|
||||
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::{
|
||||
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
|
||||
read_only_changed,
|
||||
};
|
||||
use crate::{Error, InputKind, Result};
|
||||
|
||||
/// The longest font family name a filter may set, in characters.
|
||||
const MAX_FAMILY: usize = 256;
|
||||
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
|
||||
const MIN_DETERMINANT: f64 = 1e-12;
|
||||
/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a
|
||||
/// change of the paragraph count compares by their text ([`moved_para_styles`]).
|
||||
const MAX_MATCHED_PAIRS: usize = 1 << 18;
|
||||
|
||||
/// The fields of an object of `kind` a filter that lists the kind in `writes` may change.
|
||||
fn writable(kind: InputKind) -> &'static [&'static str] {
|
||||
match kind {
|
||||
InputKind::Type => &["name", "transform", "text"],
|
||||
InputKind::Image => &["name", "transform", "opacity"],
|
||||
InputKind::SymbolInstance => &["name", "transform", "symbolId"],
|
||||
}
|
||||
}
|
||||
|
||||
/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave
|
||||
/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives
|
||||
/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of
|
||||
/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`,
|
||||
/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]).
|
||||
pub(super) fn changes(o: &Map<String, Value>, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result<Option<Map<String, Value>>> {
|
||||
let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect();
|
||||
keys.sort();
|
||||
let mut out = Map::new();
|
||||
for k in keys {
|
||||
let v = &o[k];
|
||||
let was = given.get(k);
|
||||
if !writable(kind).contains(&k.as_str()) {
|
||||
if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) {
|
||||
return Err(read_only_changed(at, &field));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (k.as_str(), was) {
|
||||
("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?,
|
||||
("name", None) if v.is_null() => {}
|
||||
(_, Some(was)) if first_difference(v, was, "").is_none() => {}
|
||||
_ => {
|
||||
out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((!out.is_empty()).then_some(out))
|
||||
}
|
||||
|
||||
/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was`
|
||||
/// (the text the input gave), into `out`; its other fields must be as given, and type given as
|
||||
/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed
|
||||
/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to
|
||||
/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs`
|
||||
/// given as they were go into `out` too, to be checked against the new paragraphs.
|
||||
fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map<String, Value>) -> Result<()> {
|
||||
let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?;
|
||||
let mut keys: Vec<&String> = t.keys().collect();
|
||||
keys.sort();
|
||||
for k in keys {
|
||||
let field = format!("{key}.{k}");
|
||||
let given = was.get(k);
|
||||
let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some());
|
||||
if !matches!(k.as_str(), "runs" | "paragraphs") {
|
||||
if differs {
|
||||
let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone());
|
||||
return Err(read_only_changed(at, &shown));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !differs {
|
||||
continue;
|
||||
}
|
||||
if truncated {
|
||||
return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed"));
|
||||
}
|
||||
let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS);
|
||||
let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?;
|
||||
if k == "runs" {
|
||||
if list.is_empty() {
|
||||
return Err(out_err(&format!("{at}.{field}"), "type needs at least one run"));
|
||||
}
|
||||
let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len)));
|
||||
if bytes > MAX_INPUT_TEXT {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})")));
|
||||
}
|
||||
// Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs.
|
||||
let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count());
|
||||
let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r)));
|
||||
if paragraphs > MAX_INPUT_RUNS {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})")));
|
||||
}
|
||||
*total = total.saturating_add(bytes);
|
||||
if *total > MAX_INPUT_TEXT_TOTAL {
|
||||
return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output")));
|
||||
}
|
||||
}
|
||||
out.insert(k.clone(), t[k].clone());
|
||||
}
|
||||
// Paragraph styles given as they were still need one per paragraph of the new runs.
|
||||
if out.contains_key("runs")
|
||||
&& !out.contains_key("paragraphs")
|
||||
&& let Some(p) = t.get("paragraphs")
|
||||
{
|
||||
out.insert("paragraphs".into(), p.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field
|
||||
/// names serde's derive hands `deserialize_struct`.
|
||||
fn attr_names<T: DeserializeOwned>() -> &'static [&'static str] {
|
||||
use serde::de::{Error as _, Visitor, value::Error};
|
||||
|
||||
struct Names<'a>(&'a mut &'static [&'static str]);
|
||||
impl<'de> serde::Deserializer<'de> for Names<'_> {
|
||||
type Error = Error;
|
||||
fn deserialize_any<V: Visitor<'de>>(self, _: V) -> std::result::Result<V::Value, Error> {
|
||||
Err(Error::custom("not a struct"))
|
||||
}
|
||||
fn deserialize_struct<V: Visitor<'de>>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result<V::Value, Error> {
|
||||
*self.0 = fields;
|
||||
Err(Error::custom("field names only"))
|
||||
}
|
||||
serde::forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit
|
||||
unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
let mut fields: &'static [&'static str] = &[];
|
||||
// Always an error: the probe only records the names.
|
||||
let _ = T::deserialize(Names(&mut fields));
|
||||
fields
|
||||
}
|
||||
|
||||
/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads:
|
||||
/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value,
|
||||
/// an error at `parent.key`.
|
||||
fn strict<T: DeserializeOwned>(v: &Value, parent: &str, key: &str) -> Result<T> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?;
|
||||
let at = format!("{parent}.{key}");
|
||||
let names = attr_names::<T>();
|
||||
if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e))
|
||||
}
|
||||
|
||||
/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each
|
||||
/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left
|
||||
/// to the style's own checks.
|
||||
fn known_keys<T: DeserializeOwned>(v: &Value, at: &str, key: &str) -> Result<()> {
|
||||
let names = attr_names::<T>();
|
||||
let check = |o: &Map<String, Value>, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) {
|
||||
Some(k) => {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
Err(out_err(at, format!("unknown key '{k}'")))
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
match v.get(key) {
|
||||
Some(Value::Object(o)) => check(o, &format!("{at}.{key}")),
|
||||
Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e {
|
||||
Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")),
|
||||
_ => Ok(()),
|
||||
}),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't
|
||||
/// flatten the object.
|
||||
fn decode_transform(v: &Value, at: &str) -> Result<Affine> {
|
||||
let c: Option<Vec<f64>> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect());
|
||||
let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?;
|
||||
if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) {
|
||||
return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})")));
|
||||
}
|
||||
let xf = Affine::new(c);
|
||||
if xf.determinant().abs() < MIN_DETERMINANT {
|
||||
return Err(out_err(at, "flattens the object to a line or a point"));
|
||||
}
|
||||
Ok(xf)
|
||||
}
|
||||
|
||||
/// The transform object `n` is given with: type's and an instance's own, an image's (for a
|
||||
/// distorted image, the placement nearest its corners at its middle).
|
||||
fn given_transform(n: &Node) -> Option<Affine> {
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.xf),
|
||||
NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)),
|
||||
NodeKind::SymbolInstance { xf, .. } => Some(*xf),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each
|
||||
/// value is checked first, and an error leaves `n` to be dropped.
|
||||
pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>, at: &str) -> Result<()> {
|
||||
if let Some(v) = changes.get("transform") {
|
||||
let at = format!("{at}.transform");
|
||||
let new = decode_transform(v, &at)?;
|
||||
let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT);
|
||||
let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?;
|
||||
// Everything the object carries moves with it: a distorted image's corners, its gradients.
|
||||
n.transform(new * old.inverse(), false);
|
||||
let distorted = n.is_distorted_image();
|
||||
match &mut n.kind {
|
||||
NodeKind::Text(t) => t.xf = new,
|
||||
NodeKind::SymbolInstance { xf, .. } => *xf = new,
|
||||
NodeKind::Image(im) if !distorted => im.xf = new,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(v) = changes.get("opacity") {
|
||||
let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o));
|
||||
n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32;
|
||||
}
|
||||
if let Some(v) = changes.get("symbolId") {
|
||||
let at = format!("{at}.symbolId");
|
||||
let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?;
|
||||
if !doc.symbols.iter().any(|s| s.name == name) {
|
||||
let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("'{shown}' is not a symbol in this document")));
|
||||
}
|
||||
let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind {
|
||||
*symbol = name.to_string();
|
||||
}
|
||||
// An edited part's path names an object of the old symbol's art, as Replace Symbol finds.
|
||||
if other && !n.extras().symbol_overrides.is_empty() {
|
||||
n.extras_mut().symbol_overrides.clear();
|
||||
}
|
||||
}
|
||||
if changes.contains_key("runs") || changes.contains_key("paragraphs") {
|
||||
let story = doc.story_of(n.id).len();
|
||||
let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) };
|
||||
set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?;
|
||||
}
|
||||
if let Some(v) = changes.get("name") {
|
||||
n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`:
|
||||
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
|
||||
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
|
||||
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
|
||||
/// were. Every number of every run's style is in the range the character style commands keep it
|
||||
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
|
||||
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
|
||||
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
|
||||
/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]).
|
||||
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
|
||||
if let Some(runs) = runs {
|
||||
let at = format!("{at}.text.runs");
|
||||
let list = runs.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
// The type's own styles, as JSON text, to look each run's style up once.
|
||||
let own: HashSet<String> = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect();
|
||||
let mut new = Vec::with_capacity(list.len());
|
||||
for (i, v) in list.iter().enumerate() {
|
||||
let at = format!("{at}[{i}]");
|
||||
let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?;
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(&at, format!("unknown key '{k}'")));
|
||||
}
|
||||
let key = "text";
|
||||
let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?;
|
||||
let style_v = o.get("style").unwrap_or(&Value::Null);
|
||||
let mut style: CharStyle = strict(style_v, &at, "style")?;
|
||||
known_keys::<vectorcraft_doc::Dash>(style_v, &format!("{at}.style"), "stroke_dash")?;
|
||||
let inline = match o.get("inline") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?),
|
||||
};
|
||||
if inline.is_none() {
|
||||
if text.contains(INLINE_CHAR) {
|
||||
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
|
||||
}
|
||||
// Every number goes to the layout, so it is checked even in a style the type has.
|
||||
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
|
||||
for key in ["fill", "stroke"] {
|
||||
if let Some(p) = style_v.get(key) {
|
||||
check_paint_keys(p, &format!("{at}.style.{key}"))?;
|
||||
}
|
||||
}
|
||||
if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) {
|
||||
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
|
||||
}
|
||||
}
|
||||
new.push(TextRun { text: text.to_string(), style, inline });
|
||||
}
|
||||
// Inline graphics are compared as saved (their measured bounds aren't), and keep those.
|
||||
let saved = |r: &&TextRun| serde_json::to_value(r).ok();
|
||||
let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect();
|
||||
let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect();
|
||||
if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) {
|
||||
return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed"));
|
||||
}
|
||||
let mut kept = old_inline.into_iter().cloned().collect::<Vec<_>>().into_iter();
|
||||
for r in new.iter_mut().filter(|r| r.inline.is_some()) {
|
||||
if let Some(old) = kept.next() {
|
||||
*r = old;
|
||||
}
|
||||
}
|
||||
let plain: String = new.iter().map(|r| r.text.as_str()).collect();
|
||||
let old = t.plain_text();
|
||||
let mut moved = None;
|
||||
if plain != old {
|
||||
if threaded {
|
||||
return Err(out_err(&at, "the characters of threaded type can't be changed"));
|
||||
}
|
||||
if !t.ruby.is_empty() {
|
||||
return Err(out_err(&at, "the characters of type with ruby can't be changed"));
|
||||
}
|
||||
let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count();
|
||||
if paragraphs.is_none() && breaks(&plain) != breaks(&old) {
|
||||
// Paragraphs added or joined: the styles follow the paragraphs' text. With as many
|
||||
// paragraphs as before, each keeps its style.
|
||||
moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain));
|
||||
}
|
||||
}
|
||||
t.runs = new;
|
||||
if let Some(styles) = moved {
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
}
|
||||
match paragraphs {
|
||||
Some(v) => {
|
||||
let text = format!("{at}.text");
|
||||
let list = v.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let count = t.paragraph_count();
|
||||
if list.len() != count {
|
||||
return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph")));
|
||||
}
|
||||
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::<Result<_>>()?;
|
||||
t.set_paragraph_styles(styles);
|
||||
}
|
||||
None => t.normalize_paras(),
|
||||
}
|
||||
// The layout is measured again before the type is drawn.
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per
|
||||
/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their
|
||||
/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in
|
||||
/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order
|
||||
/// instead. A
|
||||
/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the
|
||||
/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs
|
||||
/// added where there were none take the style of the paragraph before them, or of the next one at
|
||||
/// the start. A style copied to a paragraph that was not there loses its list number
|
||||
/// ([`vectorcraft_doc::text::ParaList::start`]).
|
||||
fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec<ParaStyle> {
|
||||
let a: Vec<&str> = old.split('\n').collect();
|
||||
let b: Vec<&str> = new.split('\n').collect();
|
||||
let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default());
|
||||
let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count();
|
||||
// `matched[j]`: the old paragraph that new paragraph `j` is, if any.
|
||||
let mut matched: Vec<Option<usize>> = vec![None; b.len()];
|
||||
for (j, m) in matched.iter_mut().enumerate().take(pre) {
|
||||
*m = Some(j);
|
||||
}
|
||||
for k in 0..suf {
|
||||
if let Some(m) = matched.get_mut(b.len() - 1 - k) {
|
||||
*m = Some(a.len() - 1 - k);
|
||||
}
|
||||
}
|
||||
let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default());
|
||||
if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS {
|
||||
let mut ids = std::collections::HashMap::new();
|
||||
let mut id = |s: &str| {
|
||||
let next = ids.len();
|
||||
*ids.entry(s.to_string()).or_insert(next)
|
||||
};
|
||||
let ai: Vec<usize> = am.iter().map(|s| id(s)).collect();
|
||||
let bi: Vec<usize> = bm.iter().map(|s| id(s)).collect();
|
||||
// `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`.
|
||||
let w = bi.len() + 1;
|
||||
let mut len = vec![0u32; (ai.len() + 1) * w];
|
||||
for i in (0..ai.len()).rev() {
|
||||
for j in (0..bi.len()).rev() {
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) };
|
||||
if let Some(c) = len.get_mut(i * w + j) {
|
||||
*c = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0);
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < ai.len() && j < bi.len() {
|
||||
if ai.get(i) == bi.get(j) {
|
||||
if let Some(m) = matched.get_mut(pre + j) {
|
||||
*m = Some(pre + i);
|
||||
}
|
||||
(i, j) = (i + 1, j + 1);
|
||||
} else if at(i + 1, j) >= at(i, j + 1) {
|
||||
i += 1;
|
||||
} else {
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let style = |i: usize, numbered: bool| {
|
||||
let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default();
|
||||
if !numbered && let Some(l) = s.list.as_mut() {
|
||||
l.start = None;
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let (mut next_old, mut j) = (0, 0);
|
||||
while j < b.len() {
|
||||
if let Some(&Some(i)) = matched.get(j) {
|
||||
out.push(style(i, true));
|
||||
(next_old, j) = (i + 1, j + 1);
|
||||
continue;
|
||||
}
|
||||
// New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were.
|
||||
let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len());
|
||||
let old_end = matched.get(end).copied().flatten().unwrap_or(a.len());
|
||||
for g in 0..end - j {
|
||||
out.push(if next_old < old_end {
|
||||
style((next_old + g).min(old_end - 1), next_old + g < old_end)
|
||||
} else {
|
||||
style(next_old.checked_sub(1).unwrap_or(old_end), false)
|
||||
});
|
||||
}
|
||||
j = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An attribute of the style at `at` out of its range, naming the attribute.
|
||||
fn range_err(at: &str, e: &AttrRangeError) -> Error {
|
||||
out_err(&format!("{at}.{}", e.key), &e.message)
|
||||
}
|
||||
|
||||
/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each
|
||||
/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it
|
||||
/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set
|
||||
/// one of `doc`'s, by name, whose characters it takes.
|
||||
fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result<ParaStyle> {
|
||||
let mut st: ParaStyle = strict(v, parent, key)?;
|
||||
let at = format!("{parent}.{key}");
|
||||
known_keys::<vectorcraft_doc::HyphenationOptions>(v, &at, "hyphenation")?;
|
||||
known_keys::<JustificationOptions>(v, &at, "justification")?;
|
||||
known_keys::<vectorcraft_doc::TabStop>(v, &at, "tabs")?;
|
||||
known_keys::<vectorcraft_doc::text::ParaList>(v, &at, "list")?;
|
||||
let justification = match v.get("justification") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
|
||||
};
|
||||
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?;
|
||||
if let Some(set) = &st.kinsoku_set {
|
||||
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
|
||||
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
|
||||
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
|
||||
})?;
|
||||
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
|
||||
}
|
||||
Ok(st)
|
||||
}
|
||||
|
||||
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
|
||||
/// its font family is 1 to [`MAX_FAMILY`] printable characters, counted as given, and its fill and
|
||||
/// stroke are admitted as an object's paints are. Its numbers and its paints' keys are checked for
|
||||
/// every run ([`set_text`]).
|
||||
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
|
||||
let family = s.font_family.trim();
|
||||
if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
|
||||
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
|
||||
}
|
||||
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
|
||||
let at = format!("{at}.{key}");
|
||||
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;
|
||||
admit_paint(doc, decode_paint(&v, &at)?, was, &at)
|
||||
};
|
||||
s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?;
|
||||
s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type`
|
||||
/// reads; a key of another paint, or an unknown one, is an error naming it.
|
||||
fn check_paint_keys(v: &Value, at: &str) -> Result<()> {
|
||||
let Some(o) = v.as_object() else { return Ok(()) };
|
||||
let known: &[&str] = match o.get("type").and_then(Value::as_str) {
|
||||
Some("solid") => &["color", "swatch", "tint"],
|
||||
Some("gradient") => attr_names::<vectorcraft_color::GradientPaint>(),
|
||||
Some("pattern") => &["pattern", "xf"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(out_err(at, format!("unknown key '{k}'")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -15,7 +15,8 @@ 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. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]).
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's
|
||||
/// `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
|
||||
/// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`,
|
||||
@@ -25,6 +26,9 @@ pub const PROGRESS_API: u32 = 2;
|
||||
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
|
||||
pub const INPUTS_API: u32 = 2;
|
||||
|
||||
/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change.
|
||||
pub const WRITES_API: u32 = 3;
|
||||
|
||||
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
|
||||
/// is ignored.
|
||||
pub const MENU_API: u32 = 2;
|
||||
|
||||
Reference in new issue
Block a user