mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 22:39:07 +00:00
Merge main into feat/plugin-importers
This commit is contained in:
@@ -26,7 +26,9 @@
|
||||
//! 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
|
||||
//! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is
|
||||
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed.
|
||||
//! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A
|
||||
//! filter or a live effect may also add menu commands of its own ([`Command`]), which the host
|
||||
//! runs through `vc_run` with the command's id in `_context`.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod dialog;
|
||||
@@ -45,7 +47,7 @@ pub mod wat;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Kind, Manifest, Param, ParamSpec};
|
||||
pub use manifest::{Budget, Command, Kind, Manifest, Param, ParamSpec};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms};
|
||||
|
||||
/// What the host puts before a plug-in's id to name what it adds: its live effect
|
||||
|
||||
@@ -20,6 +20,10 @@ pub const MAX_TEXT: usize = 4_096;
|
||||
pub const MAX_LIST: usize = 256;
|
||||
/// Most file extensions an exporter or an importer may declare.
|
||||
pub const MAX_EXTENSIONS: usize = 8;
|
||||
/// Most menu commands a plug-in may add (`commands`).
|
||||
pub const MAX_COMMANDS: usize = 32;
|
||||
/// Longest command id, in characters.
|
||||
pub const MAX_COMMAND_ID: usize = 32;
|
||||
|
||||
/// What a plug-in is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -176,6 +180,30 @@ pub struct Param {
|
||||
pub ui: ParamUi,
|
||||
}
|
||||
|
||||
/// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the
|
||||
/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command
|
||||
/// `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with `_context.command` set to
|
||||
/// `id` and the parameters it declares.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Command {
|
||||
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
|
||||
pub id: String,
|
||||
/// The menu label: 1 to 64 printable characters, shown with bidirectional characters escaped
|
||||
/// ([`crate::permissions::display_text`]).
|
||||
pub label: String,
|
||||
/// Parameters in declaration (dialog) order, declared as the manifest's own are.
|
||||
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
|
||||
pub params: Vec<(String, Param)>,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// The label as menus and errors show it: control and bidirectional characters escaped, at
|
||||
/// most [`crate::permissions::MAX_SHOWN_NAME`] characters.
|
||||
pub fn shown_label(&self) -> String {
|
||||
crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParamSpec> for Param {
|
||||
fn from(spec: ParamSpec) -> Self {
|
||||
Param { spec, ui: ParamUi::default() }
|
||||
@@ -264,6 +292,9 @@ 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,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -292,9 +323,21 @@ impl Manifest {
|
||||
params: Vec::new(),
|
||||
extensions: Vec::new(),
|
||||
budget: Budget::Light,
|
||||
commands: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The manifest command `c` runs with: this one with `c`'s label as its name and `c`'s
|
||||
/// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them.
|
||||
pub fn for_command(&self, c: &Command) -> Manifest {
|
||||
Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), ..self.clone() }
|
||||
}
|
||||
|
||||
/// The command with id `id`.
|
||||
pub fn command(&self, id: &str) -> Option<&Command> {
|
||||
self.commands.iter().find(|c| c.id == id)
|
||||
}
|
||||
|
||||
/// Checks what the module declared: its id, name and text lengths, its extensions, a budget its
|
||||
/// kind may have (only a filter may be heavy), and each parameter and its dialog layout.
|
||||
fn validate(&self) -> Result<()> {
|
||||
@@ -312,7 +355,8 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("`api` is {}; this host implements plug-in API levels 1 to {API_LEVEL}", self.api)));
|
||||
}
|
||||
if let Some(names) = &self.permissions
|
||||
&& let Some(host) = permissions::validate(self.kind, names)?.into_iter().find(|p| permissions::HOST.contains(p))
|
||||
&& let Some(host) =
|
||||
permissions::validate(self.kind, !self.commands.is_empty(), names)?.into_iter().find(|p| permissions::HOST.contains(p))
|
||||
&& self.api < PROGRESS_API
|
||||
{
|
||||
let permission = host.name();
|
||||
@@ -331,6 +375,12 @@ impl Manifest {
|
||||
return Err(Error::Manifest("an importer always gets an import's budget: leave `budget` out".into()));
|
||||
}
|
||||
}
|
||||
self.validate_params()?;
|
||||
self.validate_commands()
|
||||
}
|
||||
|
||||
/// Checks each parameter and its dialog layout.
|
||||
fn validate_params(&self) -> Result<()> {
|
||||
for (i, (k, p)) in self.params.iter().enumerate() {
|
||||
if !valid_key(k) {
|
||||
return Err(Error::Manifest(format!("invalid parameter name {k:?}")));
|
||||
@@ -344,6 +394,47 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A filter or a live effect lists at most [`MAX_COMMANDS`] commands, each with a distinct
|
||||
/// id, a printable label and parameters declared as the manifest's own are. A heavy filter
|
||||
/// lists none. The error names the command: its id, or its place in the list.
|
||||
fn validate_commands(&self) -> Result<()> {
|
||||
if self.commands.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.kind, Kind::Exporter | Kind::Importer) {
|
||||
return Err(Error::Manifest("only a filter or a live effect declares `commands`".into()));
|
||||
}
|
||||
if self.budget == Budget::Heavy {
|
||||
return Err(Error::Manifest("a heavy filter runs in the background, so it can't declare `commands`".into()));
|
||||
}
|
||||
if self.commands.len() > MAX_COMMANDS {
|
||||
return Err(Error::Manifest(format!("at most {MAX_COMMANDS} `commands`")));
|
||||
}
|
||||
for (i, c) in self.commands.iter().enumerate() {
|
||||
let name = command_name(i, &c.id);
|
||||
if !valid_command_id(&c.id) {
|
||||
return Err(Error::Manifest(format!(
|
||||
"command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter"
|
||||
)));
|
||||
}
|
||||
let label = c.label.trim();
|
||||
if label.is_empty() || label.chars().count() > 64 || label.chars().any(char::is_control) {
|
||||
return Err(Error::Manifest(format!("command {name}: `label` must be 1-64 printable characters")));
|
||||
}
|
||||
if self.commands.get(..i).is_some_and(|before| before.iter().any(|b| b.id == c.id)) {
|
||||
return Err(Error::Manifest(format!("command {name} is declared twice")));
|
||||
}
|
||||
self.for_command(c).validate_params().map_err(|e| {
|
||||
let e = match e {
|
||||
Error::Manifest(why) => why,
|
||||
other => other.to_string(),
|
||||
};
|
||||
Error::Manifest(format!("command {name}: {e}"))
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -396,11 +487,14 @@ impl Manifest {
|
||||
self.params.iter().map(|(k, p)| (k.clone(), p.spec.default_value())).collect()
|
||||
}
|
||||
|
||||
/// What the plug-in may do: the permissions it lists, else the ones its kind implies.
|
||||
/// What the plug-in may do: the permissions it lists, else every one its kind may list
|
||||
/// ([`Permission::allowed`]: a live effect with commands also changes the document and keeps
|
||||
/// data with it).
|
||||
pub fn permissions(&self) -> Vec<Permission> {
|
||||
let commands = !self.commands.is_empty();
|
||||
match &self.permissions {
|
||||
Some(names) => permissions::validate(self.kind, names).unwrap_or_default(),
|
||||
None => Permission::implied(self.kind).to_vec(),
|
||||
Some(names) => permissions::validate(self.kind, commands, names).unwrap_or_default(),
|
||||
None => Permission::allowed(self.kind, commands).to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,6 +593,119 @@ fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result
|
||||
d.deserialize_any(V)
|
||||
}
|
||||
|
||||
/// Reads the `commands` list one entry at a time from the manifest itself, so each command's
|
||||
/// `params` keep their declaration order and a repeated parameter is refused. A malformed entry
|
||||
/// is an error that names it (its id when the id comes before the fault, otherwise its place in
|
||||
/// the list), and a list is refused at its first entry past [`MAX_COMMANDS`].
|
||||
fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<Command>, D::Error> {
|
||||
use serde::de::{Error as _, IgnoredAny, MapAccess, SeqAccess, Visitor};
|
||||
|
||||
/// A command's `params`, read in declaration order.
|
||||
struct Params(Vec<(String, Param)>);
|
||||
impl<'de> Deserialize<'de> for Params {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
|
||||
ordered_params(d).map(Params)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry at place `.0` in the list.
|
||||
struct Entry(usize);
|
||||
impl<'de> serde::de::DeserializeSeed<'de> for Entry {
|
||||
type Value = Command;
|
||||
fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> std::result::Result<Command, D::Error> {
|
||||
d.deserialize_any(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for Entry {
|
||||
type Value = Command;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "command [{}] as {{id, label, params?}}", self.0)
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
|
||||
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
|
||||
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
|
||||
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
|
||||
};
|
||||
while let Some(key) = map.next_key::<String>().map_err(|e| named(&id, &e))? {
|
||||
let repeated = match key.as_str() {
|
||||
"id" if id.is_none() => {
|
||||
id = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"label" if label.is_none() => {
|
||||
label = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"params" if params.is_none() => {
|
||||
params = Some(map.next_value().map_err(|e| named(&id, &e))?);
|
||||
false
|
||||
}
|
||||
"id" | "label" | "params" => true,
|
||||
_ => {
|
||||
map.next_value::<IgnoredAny>().map_err(|e| named(&id, &e))?;
|
||||
false
|
||||
}
|
||||
};
|
||||
if repeated {
|
||||
return Err(named(&id, &format_args!("duplicate field `{key}`")));
|
||||
}
|
||||
}
|
||||
let Some(id) = id else {
|
||||
return Err(named(&None, &"missing field `id`"));
|
||||
};
|
||||
let Some(label) = label else {
|
||||
return Err(named(&Some(id), &"missing field `label`"));
|
||||
};
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() })
|
||||
}
|
||||
}
|
||||
|
||||
struct List;
|
||||
impl<'de> Visitor<'de> for List {
|
||||
type Value = Vec<Command>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("`commands` as a list of {id, label, params?}")
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, _: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
Err(A::Error::custom("`commands` must be a list of {id, label, params?}"))
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while out.len() < MAX_COMMANDS {
|
||||
match seq.next_element_seed(Entry(out.len()))? {
|
||||
Some(c) => out.push(c),
|
||||
None => return Ok(out),
|
||||
}
|
||||
}
|
||||
match seq.next_element::<IgnoredAny>()? {
|
||||
Some(_) => Err(A::Error::custom(format!("at most {MAX_COMMANDS} `commands`"))),
|
||||
None => Ok(out),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
d.deserialize_any(List)
|
||||
}
|
||||
|
||||
/// How errors name the command at place `i` with id `id`: the id in backticks, escaped and capped
|
||||
/// as prompts show text, or `[i]` when it has none.
|
||||
fn command_name(i: usize, id: &str) -> String {
|
||||
match id {
|
||||
"" => format!("[{i}]"),
|
||||
id => format!("`{}`", crate::permissions::display_text(id, crate::permissions::MAX_SHOWN_FIELD)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `[a-z][a-z0-9_]*`, 1 to [`MAX_COMMAND_ID`] characters.
|
||||
fn valid_command_id(id: &str) -> bool {
|
||||
id.len() <= MAX_COMMAND_ID
|
||||
&& id.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
|
||||
&& id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
|
||||
}
|
||||
|
||||
fn params_as_object<S: serde::Serializer>(p: &[(String, Param)], s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
use serde::ser::SerializeMap;
|
||||
let mut m = s.serialize_map(Some(p.len()))?;
|
||||
@@ -682,6 +889,16 @@ mod tests {
|
||||
assert!(serde_json::to_value(&plain).unwrap().get("permissions").is_none());
|
||||
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect"}"#).unwrap();
|
||||
assert_eq!(effect.permissions(), [Permission::DocRead, Permission::EffectRender]);
|
||||
// A live effect's commands may change the document: one with commands gets `doc.write`
|
||||
// and `state` too, and may list them.
|
||||
let commands = br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#;
|
||||
let with_commands = Manifest::parse(commands).unwrap();
|
||||
assert_eq!(with_commands.permissions(), [Permission::DocRead, Permission::DocWrite, Permission::State, Permission::EffectRender]);
|
||||
let listing =
|
||||
br#"{"id":"a","name":"x","kind":"effect","permissions":["doc.read","effect.render","doc.write"],"commands":[{"id":"c","label":"C"}]}"#;
|
||||
assert_eq!(Manifest::parse(listing).unwrap().permissions(), [Permission::DocRead, Permission::DocWrite, Permission::EffectRender]);
|
||||
let without = br#"{"id":"a","name":"x","kind":"effect","permissions":["doc.read","effect.render","doc.write"]}"#;
|
||||
assert!(Manifest::parse(without).unwrap_err().to_string().contains("`doc.write` doesn't apply"));
|
||||
let exporter = Manifest::parse(br#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"]}"#).unwrap();
|
||||
assert_eq!(exporter.permissions(), [Permission::DocRead, Permission::ExportWrite]);
|
||||
assert!(!Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","permissions":[]}"#).unwrap().asks_permissions());
|
||||
@@ -712,6 +929,72 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn commands_are_checked_and_errors_name_them() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"org.example.tidy","name":"Tidy","kind":"filter","commands":[
|
||||
{"id":"tidy_all","label":"Tidy All","menu":"File"},
|
||||
{"id":"grow","label":"Grow","params":{"mode":{"type":"bool"},"by":{"type":"number","min":0,"max":10,"default":2}}}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.commands.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), ["tidy_all", "grow"]);
|
||||
let grow = m.command("grow").unwrap();
|
||||
assert_eq!(grow.params.iter().map(|p| p.0.as_str()).collect::<Vec<_>>(), ["mode", "by"], "declaration order");
|
||||
let run = m.for_command(grow);
|
||||
assert_eq!((run.name.as_str(), run.id.as_str()), ("Grow", "org.example.tidy"));
|
||||
assert_eq!(Value::Object(run.resolve_params(&json!({"by": 50})).unwrap()), json!({"by": 10.0, "mode": false}));
|
||||
let written = serde_json::to_value(&m).unwrap();
|
||||
assert_eq!(written["commands"][1]["params"]["by"]["max"], json!(10.0));
|
||||
assert!(written["commands"][0].get("menu").is_none(), "a menu key is not kept");
|
||||
assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none());
|
||||
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap();
|
||||
assert_eq!(effect.commands.len(), 1);
|
||||
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label();
|
||||
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
|
||||
|
||||
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
|
||||
let too_many = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{}]}}"#, many.join(","));
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"ok","label":"A"},{"label":"B"}]}"#, "command [1]: missing field `id`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"nolabel"}]}"#, "command `nolabel`: missing field `label`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"Upper","label":"A"}]}"#, "command `Upper`: use an id"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"9lives","label":"A"}]}"#, "command `9lives`: use an id"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"a.b","label":"A"}]}"#, "command `a.b`: use an id"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"","label":"A"}]}"#, "command [0]: use an id"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":" "}]}"#, "command `x`: `label`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"a\nb"}]}"#, "command `x`: `label`"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A"},{"id":"x","label":"B"}]}"#, "command `x` is declared twice"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"r":{"type":"number","min":5,"max":1,"default":1}}}]}"#,
|
||||
"command `x`: parameter `r`: bad range",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"id":{"type":"bool"}}}]}"#,
|
||||
"command `x`: invalid parameter",
|
||||
),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"filter","commands":[{"id":"x","label":"A","params":{"r":{"type":"bool"},"r":{"type":"int"}}}]}"#,
|
||||
"command `x`: parameter `r` is declared twice",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":[1]}"#, "command [0]"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","commands":{"id":"x"}}"#, "must be a list"),
|
||||
(r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"commands":[{"id":"x","label":"A"}]}"#, "only a filter or a live effect"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","budget":"heavy","commands":[{"id":"x","label":"A"}]}"#, "heavy filter"),
|
||||
(too_many.as_str(), "at most 32 `commands`"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
let long_id = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"{}","label":"A"}}]}}"#, "c".repeat(MAX_COMMAND_ID + 1));
|
||||
assert!(Manifest::parse(long_id.as_bytes()).is_err());
|
||||
let hidden =
|
||||
Manifest::parse("{\"id\":\"a\",\"name\":\"x\",\"kind\":\"filter\",\"commands\":[{\"id\":\"x\u{202E}\",\"label\":\"A\"}]}".as_bytes());
|
||||
assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_number_lists_resolve_like_the_other_types() {
|
||||
let m = Manifest::parse(
|
||||
|
||||
@@ -121,10 +121,10 @@ impl Permission {
|
||||
}
|
||||
}
|
||||
|
||||
/// May a plug-in of `kind` list it: one its kind implies, or one of the host imports' ([`HOST`]),
|
||||
/// which any kind may list.
|
||||
pub fn applies(self, kind: Kind) -> bool {
|
||||
HOST.contains(&self) || Permission::implied(kind).contains(&self)
|
||||
/// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`]
|
||||
/// gives it, or one of the host imports' ([`HOST`]), which any kind may list.
|
||||
pub fn applies(self, kind: Kind, commands: bool) -> bool {
|
||||
HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self)
|
||||
}
|
||||
|
||||
/// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list
|
||||
@@ -138,6 +138,17 @@ impl Permission {
|
||||
}
|
||||
}
|
||||
|
||||
/// The permissions a plug-in of `kind` that declares `commands` or not may list besides
|
||||
/// `progress`, which are also the ones its manifest gets without `permissions`: those `kind`
|
||||
/// implies, and for a live effect with commands also `doc.write` and `state`, which only its
|
||||
/// commands use (drawing the effect changes no object and keeps no data).
|
||||
pub fn allowed(kind: Kind, commands: bool) -> &'static [Permission] {
|
||||
match kind {
|
||||
Kind::Effect if commands => &[Permission::DocRead, Permission::DocWrite, Permission::State, Permission::EffectRender],
|
||||
_ => Permission::implied(kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// The permissions a plug-in of `kind` can't work without, which its list must hold: a live
|
||||
/// effect and an exporter are always handed objects, and only draw or write; an importer is
|
||||
/// always handed the file being opened. A filter may leave any of its permissions out.
|
||||
@@ -149,10 +160,11 @@ impl Permission {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the `permissions` a manifest of `kind` lists → them, in the order [`ALL`] has. A name
|
||||
/// that is not a permission, a reserved one, one that doesn't apply to the kind, one listed twice
|
||||
/// and a list without what the kind needs are errors that name it.
|
||||
pub(crate) fn validate(kind: Kind, names: &[String]) -> Result<Vec<Permission>> {
|
||||
/// Checks the `permissions` a manifest of `kind` lists → them, in the order [`ALL`] has; `commands`
|
||||
/// is whether it declares commands ([`Permission::allowed`]). A name that is not a permission, a
|
||||
/// reserved one, one that doesn't apply to the kind, one listed twice and a list without what the
|
||||
/// kind needs are errors that name it.
|
||||
pub(crate) fn validate(kind: Kind, commands: bool, names: &[String]) -> Result<Vec<Permission>> {
|
||||
if names.len() > MAX_PERMISSIONS {
|
||||
return Err(Error::Manifest(format!("at most {MAX_PERMISSIONS} `permissions`")));
|
||||
}
|
||||
@@ -165,7 +177,7 @@ pub(crate) fn validate(kind: Kind, names: &[String]) -> Result<Vec<Permission>>
|
||||
}
|
||||
return Err(Error::Manifest(format!("unknown permission `{shown}`")));
|
||||
};
|
||||
if !p.applies(kind) {
|
||||
if !p.applies(kind, commands) {
|
||||
return Err(Error::Manifest(format!("permission `{shown}` doesn't apply to a plug-in of kind `{}`", kind.name())));
|
||||
}
|
||||
if out.contains(&p) {
|
||||
@@ -262,48 +274,63 @@ mod tests {
|
||||
#[test]
|
||||
fn lists_are_checked_against_the_kind() {
|
||||
let list = |names: &[&str]| names.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(validate(Kind::Filter, &list(&["doc.write", "doc.read"])).unwrap(), [Permission::DocRead, Permission::DocWrite]);
|
||||
assert_eq!(validate(Kind::Filter, &[]).unwrap(), []);
|
||||
assert!(validate(Kind::Effect, &list(&["doc.read", "effect.render"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, &list(&["export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, &list(&["import.read"])).unwrap(), [Permission::ImportRead]);
|
||||
assert_eq!(validate(Kind::Filter, false, &list(&["doc.write", "doc.read"])).unwrap(), [Permission::DocRead, Permission::DocWrite]);
|
||||
assert_eq!(validate(Kind::Filter, false, &[]).unwrap(), []);
|
||||
assert!(validate(Kind::Effect, false, &list(&["doc.read", "effect.render"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, false, &list(&["export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, false, &list(&["import.read"])).unwrap(), [Permission::ImportRead]);
|
||||
// Any kind may list `progress`, which no kind implies.
|
||||
assert_eq!(validate(Kind::Filter, &list(&["progress", "doc.read"])).unwrap(), [Permission::DocRead, Permission::Progress]);
|
||||
assert!(validate(Kind::Effect, &list(&["doc.read", "effect.render", "progress"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, &list(&["progress", "export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, &list(&["progress", "import.read"])).unwrap(), [Permission::ImportRead, Permission::Progress]);
|
||||
assert_eq!(validate(Kind::Filter, false, &list(&["progress", "doc.read"])).unwrap(), [Permission::DocRead, Permission::Progress]);
|
||||
assert!(validate(Kind::Effect, false, &list(&["doc.read", "effect.render", "progress"])).is_ok());
|
||||
assert!(validate(Kind::Effect, true, &list(&["doc.read", "effect.render", "progress"])).is_ok());
|
||||
assert!(validate(Kind::Exporter, false, &list(&["progress", "export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Importer, false, &list(&["progress", "import.read"])).unwrap(), [Permission::ImportRead, Permission::Progress]);
|
||||
assert!(
|
||||
[Kind::Filter, Kind::Effect, Kind::Exporter, Kind::Importer].iter().all(|k| !Permission::implied(*k).contains(&Permission::Progress))
|
||||
);
|
||||
// So may `settings` and `cache`, which no kind implies either.
|
||||
assert_eq!(
|
||||
validate(Kind::Effect, &list(&["cache", "settings", "doc.read", "effect.render"])).unwrap(),
|
||||
validate(Kind::Effect, false, &list(&["cache", "settings", "doc.read", "effect.render"])).unwrap(),
|
||||
[Permission::DocRead, Permission::EffectRender, Permission::Settings, Permission::Cache]
|
||||
);
|
||||
assert!(validate(Kind::Exporter, &list(&["settings", "export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Filter, &list(&["cache"])).unwrap(), [Permission::Cache]);
|
||||
assert!(validate(Kind::Exporter, false, &list(&["settings", "export.write", "doc.read"])).is_ok());
|
||||
assert_eq!(validate(Kind::Filter, false, &list(&["cache"])).unwrap(), [Permission::Cache]);
|
||||
for kind in [Kind::Filter, Kind::Effect, Kind::Exporter, Kind::Importer] {
|
||||
assert!(HOST.iter().all(|p| p.applies(kind) && !Permission::implied(kind).contains(p)));
|
||||
for commands in [false, true] {
|
||||
assert!(HOST.iter().all(|p| p.applies(kind, commands) && !Permission::implied(kind).contains(p)));
|
||||
}
|
||||
}
|
||||
for (kind, names, says) in [
|
||||
(Kind::Importer, &["import.read", "doc.read"][..], "`doc.read` doesn't apply to a plug-in of kind `importer`"),
|
||||
(Kind::Importer, &[], "needs the permission `import.read`"),
|
||||
(Kind::Exporter, &["export.write", "doc.read", "import.read"], "`import.read` doesn't apply to a plug-in of kind `exporter`"),
|
||||
(Kind::Filter, &["doc.read", "clipboard"][..], "unknown permission `clipboard`"),
|
||||
(Kind::Filter, &["ui.panel"], "`ui.panel` is reserved"),
|
||||
(Kind::Filter, &["progress", "progress"], "`progress` is listed twice"),
|
||||
(Kind::Filter, &["cache", "cache"], "`cache` is listed twice"),
|
||||
(Kind::Filter, &["storage"], "unknown permission `storage`"),
|
||||
(Kind::Filter, &["export.write"], "doesn't apply to a plug-in of kind `filter`"),
|
||||
(Kind::Exporter, &["doc.read", "export.write", "doc.read"], "`doc.read` is listed twice"),
|
||||
(Kind::Effect, &["doc.read"], "needs the permission `effect.render`"),
|
||||
(Kind::Exporter, &["export.write"], "needs the permission `doc.read`"),
|
||||
// A live effect with commands may also change the document and keep data with it.
|
||||
assert_eq!(
|
||||
validate(Kind::Effect, true, &list(&["state", "effect.render", "doc.write", "doc.read"])).unwrap(),
|
||||
[Permission::DocRead, Permission::DocWrite, Permission::State, Permission::EffectRender]
|
||||
);
|
||||
assert_eq!(Permission::allowed(Kind::Effect, false), Permission::implied(Kind::Effect));
|
||||
assert_eq!(Permission::allowed(Kind::Filter, true), Permission::implied(Kind::Filter));
|
||||
for (kind, commands, names, says) in [
|
||||
(Kind::Filter, false, &["doc.read", "clipboard"][..], "unknown permission `clipboard`"),
|
||||
(Kind::Filter, false, &["ui.panel"], "`ui.panel` is reserved"),
|
||||
(Kind::Filter, false, &["progress", "progress"], "`progress` is listed twice"),
|
||||
(Kind::Filter, false, &["export.write"], "doesn't apply to a plug-in of kind `filter`"),
|
||||
(Kind::Exporter, false, &["doc.read", "export.write", "doc.read"], "`doc.read` is listed twice"),
|
||||
(Kind::Effect, false, &["doc.read"], "needs the permission `effect.render`"),
|
||||
(Kind::Effect, false, &["doc.read", "effect.render", "doc.write"], "`doc.write` doesn't apply to a plug-in of kind `effect`"),
|
||||
(Kind::Effect, true, &["doc.read", "doc.write"], "needs the permission `effect.render`"),
|
||||
(Kind::Effect, true, &["doc.read", "effect.render", "export.write"], "`export.write` doesn't apply"),
|
||||
(Kind::Exporter, true, &["doc.read", "export.write", "doc.write"], "`doc.write` doesn't apply"),
|
||||
(Kind::Exporter, false, &["export.write"], "needs the permission `doc.read`"),
|
||||
(Kind::Filter, false, &["cache", "cache"], "`cache` is listed twice"),
|
||||
(Kind::Filter, false, &["storage"], "unknown permission `storage`"),
|
||||
(Kind::Importer, false, &["import.read", "doc.read"], "`doc.read` doesn't apply to a plug-in of kind `importer`"),
|
||||
(Kind::Importer, true, &["import.read", "doc.write"], "`doc.write` doesn't apply to a plug-in of kind `importer`"),
|
||||
(Kind::Importer, false, &[], "needs the permission `import.read`"),
|
||||
(Kind::Exporter, false, &["export.write", "doc.read", "import.read"], "`import.read` doesn't apply to a plug-in of kind `exporter`"),
|
||||
] {
|
||||
let e = validate(kind, &list(names)).unwrap_err().to_string();
|
||||
let e = validate(kind, commands, &list(names)).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{names:?}: {e}");
|
||||
}
|
||||
let many = list(&["doc.read"; MAX_PERMISSIONS + 1]);
|
||||
assert!(validate(Kind::Filter, &many).unwrap_err().to_string().contains("at most"));
|
||||
assert!(validate(Kind::Filter, false, &many).unwrap_err().to_string().contains("at most"));
|
||||
}
|
||||
|
||||
/// Control, bidirectional override and separator characters show as escapes, so a name can't
|
||||
|
||||
Reference in New Issue
Block a user