mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 18:19:03 +00:00
Merge remote-tracking branch 'origin/main' into feat/4943-more-indian-languages
# Conflicts: # docs/type-parity.md # docs/ui-parity.md
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod actionset;
|
||||
mod addons;
|
||||
mod apiref;
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
@@ -82,6 +83,7 @@ mod select;
|
||||
pub(crate) mod shaper;
|
||||
pub mod shortcutset;
|
||||
pub(crate) mod slices;
|
||||
pub mod spelling;
|
||||
mod stroke;
|
||||
mod style;
|
||||
pub mod stylelib;
|
||||
@@ -129,6 +131,9 @@ pub struct CommandSpec {
|
||||
pub run: Run,
|
||||
/// Record in the journal (false for queries and selection-only helpers).
|
||||
pub journal: bool,
|
||||
/// The parameters' schema: [`Session::execute`] checks the params against it before the
|
||||
/// command runs, and `params` is the text it writes ([`crate::schemas`]).
|
||||
pub schema: Option<&'static vectorcraft_apischema::ParamSchema>,
|
||||
}
|
||||
|
||||
/// Serializable command metadata.
|
||||
@@ -142,11 +147,29 @@ pub struct CommandInfo {
|
||||
pub enabled: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub disabled_reason: Option<String>,
|
||||
/// The parameters' schema as a JSON Schema 2020-12 object schema, for a command that has one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub schema: Option<Value>,
|
||||
/// The same schema in the form an MCP tool's `inputSchema` takes ([`input_schema`]).
|
||||
#[serde(rename = "inputSchema", skip_serializing_if = "Option::is_none")]
|
||||
pub input_schema: Option<Value>,
|
||||
}
|
||||
|
||||
/// `schema` as an MCP tool input schema: the root `type` is `"object"`, since the arguments are
|
||||
/// always an object, and every other keyword is kept. The root of [`CommandInfo::schema`] also
|
||||
/// takes null when no parameter is required.
|
||||
pub(crate) fn input_schema(schema: &Value) -> Value {
|
||||
let mut o = schema.clone();
|
||||
if let Some(map) = o.as_object_mut() {
|
||||
map.insert("type".into(), "object".into());
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
impl CommandSpec {
|
||||
pub fn info(&self, s: &Session) -> CommandInfo {
|
||||
let e = (self.enabled)(s);
|
||||
let schema = self.schema.map(vectorcraft_apischema::ParamSchema::to_json);
|
||||
CommandInfo {
|
||||
id: self.id,
|
||||
label: self.label,
|
||||
@@ -155,6 +178,8 @@ impl CommandSpec {
|
||||
params: self.params,
|
||||
enabled: e.is_ok(),
|
||||
disabled_reason: e.err(),
|
||||
input_schema: schema.as_ref().map(input_schema),
|
||||
schema,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,10 +262,17 @@ pub fn has_clipboard(s: &Session) -> std::result::Result<(), String> {
|
||||
|
||||
macro_rules! cmd {
|
||||
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: true, schema: None }
|
||||
};
|
||||
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false }
|
||||
$crate::cmd::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run, journal: false, schema: None }
|
||||
};
|
||||
// With a parameter schema: `schema: &SCHEMA` after the run function.
|
||||
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
|
||||
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!($id, $label, [$($m),*], $sc, $params, $en, $run) }
|
||||
};
|
||||
(query $id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr, schema: $schema:expr) => {
|
||||
$crate::cmd::CommandSpec { schema: Some($schema), ..$crate::cmd::cmd!(query $id, $label, [$($m),*], $sc, $params, $en, $run) }
|
||||
};
|
||||
}
|
||||
pub(crate) use cmd;
|
||||
@@ -321,6 +353,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
@@ -352,6 +385,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(actionset::specs());
|
||||
v.extend(importmatches::specs());
|
||||
v.extend(addons::specs());
|
||||
// Last, so the reference it writes ends with its own section.
|
||||
v.extend(apiref::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -368,6 +403,14 @@ pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result
|
||||
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
|
||||
}
|
||||
|
||||
/// [`run_spec`] for a command run outside [`Session::execute`]: with params checked against the
|
||||
/// command's schema, and the defaults of omitted values filled in, as `execute` does
|
||||
/// ([`crate::schemas::check`]).
|
||||
pub(crate) fn run_checked(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
|
||||
let checked = crate::schemas::check(spec, p, s.replaying())?;
|
||||
run_spec(s, spec, checked.as_ref().unwrap_or(p))
|
||||
}
|
||||
|
||||
// ---------- param helpers ----------
|
||||
|
||||
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
|
||||
@@ -275,6 +275,7 @@ fn same_art(a: &NodeKind, b: &NodeKind) -> bool {
|
||||
moved.xf = a.xf;
|
||||
moved.cached_bounds = a.cached_bounds;
|
||||
moved.cached_baselines.clone_from(&a.cached_baselines);
|
||||
moved.cached_ink = a.cached_ink;
|
||||
**a == moved
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
//! `engine.apiReference`: the command API reference in Markdown, written when it is asked for from
|
||||
//! the parameter schemas of the built-in commands ([`crate::schemas`]). Each command that has a
|
||||
//! schema gets a section, in registry order, with its parameters in the schema's order; a command
|
||||
//! without a schema, a plug-in's included, is left out. The text depends only on the registry, so
|
||||
//! every call in one build returns the same bytes.
|
||||
//!
|
||||
//! Text from a schema is escaped before it goes into a heading, a list item or a table cell: the
|
||||
//! Markdown punctuation characters get a backslash (CommonMark 0.31.2, backslash escapes,
|
||||
//! <https://spec.commonmark.org/0.31.2/#backslash-escapes>), so a description shows as plain text and
|
||||
//! cannot end a table cell or make a link, an image or HTML; line breaks, tabs and other control
|
||||
//! characters become spaces.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_apischema::{Bound, MAX_DEPTH, MAX_ID, Omitted, Param, ParamSchema, Type, Writes};
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, cmd, command_specs};
|
||||
use crate::EngineError;
|
||||
|
||||
const ID: &str = "engine.apiReference";
|
||||
|
||||
/// The largest reference the command returns, in bytes of UTF-8.
|
||||
pub const MAX_BYTES: usize = 1 << 20;
|
||||
|
||||
static REFERENCE: ParamSchema = ParamSchema::new(
|
||||
&[],
|
||||
"the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order",
|
||||
)
|
||||
.returns("{markdown: string}")
|
||||
.writes(Writes::Nothing)
|
||||
.since(2);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "engine.apiReference",
|
||||
"Command API Reference",
|
||||
[],
|
||||
None,
|
||||
"{} the command API reference in Markdown, written from the built-in commands' parameter schemas: a section for each command that has one, in registry order → {markdown: string}",
|
||||
always,
|
||||
api_reference,
|
||||
schema: &REFERENCE
|
||||
)]
|
||||
}
|
||||
|
||||
fn api_reference(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "markdown": reference(command_specs())? }))
|
||||
}
|
||||
|
||||
const HEADER: &str = "# VectorCraft command API reference\n\nThis reference lists only the commands that have a parameter schema, in registry order. `engine.commands` lists every command, with its params text and whether it can run now.\n";
|
||||
|
||||
/// The reference for the commands of `specs` that have a schema, or an error when it would be
|
||||
/// larger than [`MAX_BYTES`]; a reference that is too large is never cut short.
|
||||
pub(crate) fn reference(specs: &[CommandSpec]) -> Result<String> {
|
||||
let mut out = String::from(HEADER);
|
||||
let mut sections = 0;
|
||||
for spec in specs {
|
||||
let Some(schema) = spec.schema else { continue };
|
||||
let text = section(spec, schema);
|
||||
if out.len() + text.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("`{ID}`: the reference would be larger than {MAX_BYTES} bytes")));
|
||||
}
|
||||
out.push_str(&text);
|
||||
sections += 1;
|
||||
}
|
||||
if sections == 0 {
|
||||
out.push_str("\nNo commands have parameter schemas.\n");
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One command's section: its heading, a list of what it is, and its parameters.
|
||||
fn section(spec: &CommandSpec, schema: &ParamSchema) -> String {
|
||||
let menu = if spec.menu.is_empty() { "None".to_string() } else { spec.menu.iter().map(|m| escape(m)).collect::<Vec<_>>().join(" › ") };
|
||||
let mut s = format!("\n## {}\n\n", escape(spec.id));
|
||||
s.push_str(&format!("- Label: {}\n", escape(spec.label)));
|
||||
s.push_str(&format!("- Menu: {menu}\n"));
|
||||
s.push_str(&format!("- API level: {}\n", schema.since));
|
||||
s.push_str(&format!("- Deprecated: {}\n", level_text(schema.deprecated)));
|
||||
s.push_str(&format!("- Writes: {}\n", writes_text(schema.writes)));
|
||||
s.push_str(&format!("- Cost: {}\n", schema.cost));
|
||||
s.push_str(&format!("- Summary: {}\n", text_or_none(schema.summary)));
|
||||
s.push_str(&format!("- Returns: {}\n\n", text_or_none(schema.returns)));
|
||||
if schema.params.is_empty() {
|
||||
s.push_str("No parameters.\n");
|
||||
return s;
|
||||
}
|
||||
s.push_str("| Parameter | Type | Range | Unit | Default | Required | Since | Deprecated | Description |\n");
|
||||
s.push_str("|---|---|---|---|---|---|---|---|---|\n");
|
||||
rows("", schema.params, 0, &mut s);
|
||||
s
|
||||
}
|
||||
|
||||
/// A table row for each of `params`, and after each one the rows of the members of an object it
|
||||
/// holds: `edits[].name` for an object in a list, `options.size` for an object.
|
||||
fn rows(prefix: &str, params: &[Param], depth: usize, out: &mut String) {
|
||||
for p in params {
|
||||
let name = if prefix.is_empty() { p.name.to_string() } else { format!("{prefix}.{}", p.name) };
|
||||
let (range, unit) = range_and_unit(&p.ty);
|
||||
out.push_str(&format!(
|
||||
"| {} | {} | {range} | {unit} | {} | {} | {} | {} | {} |\n",
|
||||
escape(&name),
|
||||
type_text(&p.ty, depth),
|
||||
default_text(p.omitted),
|
||||
if p.required { "Yes" } else { "No" },
|
||||
p.since,
|
||||
level_text(p.deprecated),
|
||||
description(p),
|
||||
));
|
||||
if depth < MAX_DEPTH
|
||||
&& let Some((members, path)) = members(&p.ty, name, depth)
|
||||
{
|
||||
rows(&path, members, depth + 1, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of the object `ty` holds, directly or as the items of lists, with the path of
|
||||
/// its members' prefix (`name`, `name[]`, `name[][]`).
|
||||
fn members(ty: &Type, mut path: String, depth: usize) -> Option<(&'static [Param], String)> {
|
||||
let mut ty = ty;
|
||||
for _ in depth..MAX_DEPTH {
|
||||
match ty {
|
||||
Type::Object(params) => return Some((params, path)),
|
||||
Type::Array(item) => {
|
||||
path.push_str("[]");
|
||||
ty = item;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn type_text(ty: &Type, depth: usize) -> String {
|
||||
match ty {
|
||||
Type::Number { .. } => "number".into(),
|
||||
Type::Integer { .. } => "integer".into(),
|
||||
Type::Boolean => "boolean".into(),
|
||||
Type::String => "string".into(),
|
||||
Type::Enum(names) => format!("one of {}", names.iter().map(|n| format!("\"{}\"", escape(n))).collect::<Vec<_>>().join(", ")),
|
||||
Type::Id => "object id (integer)".into(),
|
||||
Type::Ids => "list of object ids".into(),
|
||||
Type::Color => escape("color (a string, [r, g, b] or an object)"),
|
||||
Type::Point => escape("point ([x, y], two numbers)"),
|
||||
Type::Object(_) => "object".into(),
|
||||
Type::Array(_) if depth >= MAX_DEPTH => "list".into(),
|
||||
Type::Array(item) => format!("list of {}", type_text(item, depth + 1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The range and unit cells of a value of type `ty`.
|
||||
fn range_and_unit(ty: &Type) -> (String, String) {
|
||||
let ends = |low: Option<String>, high: Option<String>| {
|
||||
let both: Vec<String> = low.into_iter().chain(high).collect();
|
||||
if both.is_empty() { "None".to_string() } else { both.join(", ") }
|
||||
};
|
||||
match ty {
|
||||
Type::Number { min, max, unit } => {
|
||||
let low = min.map(|b| match b {
|
||||
Bound::Inclusive(a) => format!("at least {a}"),
|
||||
Bound::Exclusive(a) => format!("more than {a}"),
|
||||
});
|
||||
let high = max.map(|b| match b {
|
||||
Bound::Inclusive(a) => format!("at most {a}"),
|
||||
Bound::Exclusive(a) => format!("less than {a}"),
|
||||
});
|
||||
(ends(low, high), unit.map_or("None".to_string(), escape))
|
||||
}
|
||||
Type::Integer { min, max } => (ends(min.map(|a| format!("at least {a}")), max.map(|a| format!("at most {a}"))), "None".into()),
|
||||
Type::Id => (format!("at least 0, at most {MAX_ID}"), "None".into()),
|
||||
_ => ("None".into(), "None".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_text(omitted: Omitted) -> String {
|
||||
match omitted {
|
||||
Omitted::Nothing => "None".into(),
|
||||
Omitted::Value(json) => format!("{} (JSON)", escape(json)),
|
||||
Omitted::Note(note) => format!("{} (worked out by the command)", escape(note)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameter's doc text, and what the schema says about how its value is checked.
|
||||
fn description(p: &Param) -> String {
|
||||
let mut parts = Vec::new();
|
||||
if !p.doc.is_empty() {
|
||||
parts.push(escape(p.doc));
|
||||
}
|
||||
if p.null_omitted {
|
||||
parts.push("null reads as omitted".to_string());
|
||||
}
|
||||
if p.lenient {
|
||||
parts.push("lenient (a value of another type or out of range is passed to the command, not refused)".to_string());
|
||||
}
|
||||
if parts.is_empty() { "None".to_string() } else { parts.join("; ") }
|
||||
}
|
||||
|
||||
fn level_text(level: Option<u32>) -> String {
|
||||
level.map_or("None".to_string(), |l| format!("API level {l}"))
|
||||
}
|
||||
|
||||
fn writes_text(writes: Writes) -> &'static str {
|
||||
match writes {
|
||||
Writes::Nothing => "nothing",
|
||||
Writes::Session => "session",
|
||||
Writes::Preferences => "preferences",
|
||||
Writes::Document => "document",
|
||||
}
|
||||
}
|
||||
|
||||
fn text_or_none(text: &str) -> String {
|
||||
if text.is_empty() { "None".to_string() } else { escape(text) }
|
||||
}
|
||||
|
||||
/// The characters [`escape`] puts a backslash before.
|
||||
const ESCAPED: &[char] = &['\\', '|', '[', ']', '<', '>', '`', '*', '_', '!', '&', '#', '~', ':', '@'];
|
||||
|
||||
/// `text` as plain Markdown text on one line: each of [`ESCAPED`] with a backslash before it, the
|
||||
/// `.` after `www` too (so no autolink starts), and each control character as a space.
|
||||
pub(crate) fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
if c.is_control() {
|
||||
out.push(' ');
|
||||
continue;
|
||||
}
|
||||
let after_www = out.len().checked_sub(3).and_then(|at| out.as_bytes().get(at..)).is_some_and(|b| b.eq_ignore_ascii_case(b"www"));
|
||||
if ESCAPED.contains(&c) || (c == '.' && after_www) {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn run(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn spec(id: &'static str, menu: &'static [&'static str], schema: Option<&'static ParamSchema>) -> CommandSpec {
|
||||
CommandSpec { id, label: "Label", menu, shortcut: None, params: "", enabled: always, run, journal: false, schema }
|
||||
}
|
||||
|
||||
/// The cells of a table row as a GFM table reads them: split at each `|` that has no backslash
|
||||
/// before it, with the outer pipes and the spaces around each cell taken off.
|
||||
fn cells(row: &str) -> Vec<String> {
|
||||
let inner = row.strip_prefix('|').and_then(|r| r.strip_suffix('|')).unwrap_or_else(|| panic!("not a table row: {row}"));
|
||||
let (mut out, mut cell, mut chars) = (Vec::new(), String::new(), inner.chars());
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\\' => {
|
||||
cell.push(c);
|
||||
cell.extend(chars.next());
|
||||
}
|
||||
'|' => out.push(std::mem::take(&mut cell).trim().to_string()),
|
||||
_ => cell.push(c),
|
||||
}
|
||||
}
|
||||
out.push(cell.trim().to_string());
|
||||
out
|
||||
}
|
||||
|
||||
/// What `text` shows as: each escaped character as itself. Panics on a Markdown punctuation
|
||||
/// character without its backslash, or a backslash before a character that needs none.
|
||||
fn literal(text: &str) -> String {
|
||||
let (mut out, mut chars) = (String::new(), text.chars());
|
||||
while let Some(c) = chars.next() {
|
||||
assert!(!ESCAPED.contains(&c) || c == '\\', "`{c}` is not escaped in {text}");
|
||||
if c == '\\' {
|
||||
let next = chars.next().unwrap_or_else(|| panic!("a backslash ends {text}"));
|
||||
assert!(ESCAPED.contains(&next) || next == '.', "`\\{next}` in {text}");
|
||||
out.push(next);
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The shown cells of the row of parameter `name`.
|
||||
fn row(markdown: &str, name: &str) -> Vec<String> {
|
||||
let found = markdown.lines().filter(|l| l.starts_with('|')).find(|l| cells(l).first().map(|c| literal(c)).as_deref() == Some(name));
|
||||
let row = found.unwrap_or_else(|| panic!("no row for {name} in\n{markdown}"));
|
||||
let cells = cells(row);
|
||||
assert_eq!(cells.len(), 9, "{row}");
|
||||
cells.iter().map(|c| literal(c)).collect()
|
||||
}
|
||||
|
||||
/// The text after `- {label}: ` in the section's list.
|
||||
fn item(markdown: &str, label: &str) -> String {
|
||||
let prefix = format!("- {label}: ");
|
||||
let line = markdown.lines().find_map(|l| l.strip_prefix(prefix.as_str()));
|
||||
literal(line.unwrap_or_else(|| panic!("no {label} in\n{markdown}")))
|
||||
}
|
||||
|
||||
/// Two calls give the same bytes, with no document open, and the reference has one section
|
||||
/// for each built-in command that has a schema, in registry order, ending with this command's.
|
||||
#[test]
|
||||
fn the_reference_lists_each_schema_once_in_registry_order_and_is_the_same_each_time() {
|
||||
let mut s = Session::new();
|
||||
let first = s.execute(ID, &json!({})).unwrap();
|
||||
let second = s.execute(ID, &Value::Null).unwrap();
|
||||
assert_eq!(first, second);
|
||||
let markdown = first["markdown"].as_str().unwrap();
|
||||
assert_eq!(markdown, reference(command_specs()).unwrap());
|
||||
assert!(markdown.len() < MAX_BYTES / 10, "{} bytes", markdown.len());
|
||||
let headings: Vec<String> = markdown.lines().filter_map(|l| l.strip_prefix("## ")).map(literal).collect();
|
||||
let expected: Vec<&str> = command_specs().iter().filter(|c| c.schema.is_some()).map(|c| c.id).collect();
|
||||
assert_eq!(headings, expected);
|
||||
assert_eq!(headings.last().map(String::as_str), Some(ID));
|
||||
assert!(expected.contains(&"view.saved.new") && !headings.iter().any(|h| h == "file.new"));
|
||||
let new_view = &markdown[markdown.find("## view.saved.new").unwrap()..];
|
||||
let names: Vec<String> = new_view
|
||||
.lines()
|
||||
.skip_while(|l| !l.starts_with("|---"))
|
||||
.skip(1)
|
||||
.take_while(|l| l.starts_with('|'))
|
||||
.map(|l| literal(&cells(l)[0]))
|
||||
.collect();
|
||||
assert_eq!(names, ["name", "center", "zoom", "rotation"]);
|
||||
let edit = &markdown[markdown.find("## view.saved.edit").unwrap()..];
|
||||
assert_eq!(row(edit, "edits[].newName")[8], "null reads as omitted");
|
||||
assert_eq!(row(edit, "newName")[8], "rename; null reads as omitted");
|
||||
}
|
||||
|
||||
const INNER: &[Param] =
|
||||
&[Param::new("size", Type::Integer { min: Some(1), max: Some(10) }), Param::new("mode", Type::Enum(&["a", "b"])).defaults_to("\"a\"")];
|
||||
|
||||
static FULL: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: Some(Bound::Inclusive(64.0)), unit: Some("pt") })
|
||||
.doc("1 = 100%"),
|
||||
Param::new("name", Type::String).default_note("the first free name").null_omitted(),
|
||||
Param::new("old", Type::Boolean).defaults_to("true").since(2).deprecated(3).lenient(),
|
||||
Param::new("edits", Type::Array(&Type::Object(INNER))).optional(),
|
||||
Param::new("ids", Type::Ids).optional(),
|
||||
Param::new("at", Type::Point).optional(),
|
||||
Param::new("color", Type::Color).optional(),
|
||||
Param::new("id", Type::Id).optional(),
|
||||
Param::new("ratio", Type::Number { min: Some(Bound::Inclusive(-1.5)), max: Some(Bound::Exclusive(2.0)), unit: None }).optional(),
|
||||
],
|
||||
"do the thing",
|
||||
)
|
||||
.returns("{done}")
|
||||
.writes(Writes::Preferences)
|
||||
.since(2)
|
||||
.deprecated(4)
|
||||
.cost(5);
|
||||
|
||||
/// Each field of a schema shows, nested members in their order under dotted names.
|
||||
#[test]
|
||||
fn every_field_of_a_schema_is_shown() {
|
||||
let markdown = reference(&[spec("test.full", &["View", "Saved"], Some(&FULL))]).unwrap();
|
||||
for (label, shown) in [
|
||||
("Label", "Label"),
|
||||
("Menu", "View › Saved"),
|
||||
("API level", "2"),
|
||||
("Deprecated", "API level 4"),
|
||||
("Writes", "preferences"),
|
||||
("Cost", "5"),
|
||||
("Summary", "do the thing"),
|
||||
("Returns", "{done}"),
|
||||
] {
|
||||
assert_eq!(item(&markdown, label), shown, "{label}");
|
||||
}
|
||||
let lenient = "lenient (a value of another type or out of range is passed to the command, not refused)";
|
||||
let expected: [[&str; 9]; 11] = [
|
||||
["zoom", "number", "more than 0, at most 64", "pt", "None", "Yes", "1", "None", "1 = 100%"],
|
||||
["name", "string", "None", "None", "the first free name (worked out by the command)", "No", "1", "None", "null reads as omitted"],
|
||||
["old", "boolean", "None", "None", "true (JSON)", "No", "2", "API level 3", lenient],
|
||||
["edits", "list of object", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["edits[].size", "integer", "at least 1, at most 10", "None", "None", "Yes", "1", "None", "None"],
|
||||
["edits[].mode", "one of \"a\", \"b\"", "None", "None", "\"a\" (JSON)", "No", "1", "None", "None"],
|
||||
["ids", "list of object ids", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["at", "point ([x, y], two numbers)", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["color", "color (a string, [r, g, b] or an object)", "None", "None", "None", "No", "1", "None", "None"],
|
||||
["id", "object id (integer)", "at least 0, at most 9007199254740991", "None", "None", "No", "1", "None", "None"],
|
||||
["ratio", "number", "at least -1.5, less than 2", "None", "None", "No", "1", "None", "None"],
|
||||
];
|
||||
let names: Vec<String> =
|
||||
markdown.lines().filter(|l| l.starts_with("| ") && !l.starts_with("| Parameter")).map(|l| literal(&cells(l)[0])).collect();
|
||||
assert_eq!(names, expected.map(|r| r[0]));
|
||||
for want in expected {
|
||||
assert_eq!(row(&markdown, want[0]), want, "{}", want[0]);
|
||||
}
|
||||
}
|
||||
|
||||
const HOSTILE: &str = "a | b [link](https://evil.example) <script>x</script> `code` \\ *em* _u_  & ~~s~~ # h www.example.com me@example.com\r\nnext\tline";
|
||||
|
||||
static ESCAPES: ParamSchema =
|
||||
ParamSchema::new(&[Param::new("a|b", Type::String).doc(HOSTILE).defaults_to("\"<b>|</b>\"")], HOSTILE).returns(HOSTILE);
|
||||
|
||||
/// Markdown in a schema's text shows as plain text: a description stays in its own cell of a
|
||||
/// nine-cell row, every punctuation character is escaped, and line breaks and tabs are spaces.
|
||||
#[test]
|
||||
fn markdown_in_schema_text_stays_literal_in_its_cell() {
|
||||
let markdown = reference(&[spec("test.escapes", &["A|B", "[x](y)"], Some(&ESCAPES))]).unwrap();
|
||||
let shown = HOSTILE.replace(['\r', '\n', '\t'], " ");
|
||||
let cells = row(&markdown, "a|b");
|
||||
assert_eq!(cells[4], "\"<b>|</b>\" (JSON)");
|
||||
assert_eq!(cells[8], shown);
|
||||
assert_eq!(item(&markdown, "Summary"), shown);
|
||||
assert_eq!(item(&markdown, "Returns"), shown);
|
||||
assert_eq!(item(&markdown, "Menu"), "A|B › [x](y)");
|
||||
assert!(markdown.contains("www\\.example"), "{markdown}");
|
||||
let table: Vec<&str> = markdown.lines().filter(|l| l.starts_with('|')).collect();
|
||||
assert_eq!(table.len(), 3, "the header, the delimiter row and one row: {table:?}");
|
||||
assert!(!markdown.contains('\r') && !markdown.contains('\t'));
|
||||
}
|
||||
|
||||
/// A registry with no schema gives the header and a line that says so; a command without a
|
||||
/// schema adds nothing.
|
||||
#[test]
|
||||
fn a_registry_without_schemas_gives_a_document_that_says_so() {
|
||||
let empty = format!("{HEADER}\nNo commands have parameter schemas.\n");
|
||||
assert_eq!(reference(&[]).unwrap(), empty);
|
||||
assert_eq!(reference(&[spec("test.none", &["View"], None)]).unwrap(), empty);
|
||||
let one = reference(&[spec("test.none", &[], None), spec("test.full", &[], Some(&FULL)), spec("test.other", &[], None)]).unwrap();
|
||||
assert_eq!(one, reference(&[spec("test.full", &[], Some(&FULL))]).unwrap());
|
||||
}
|
||||
|
||||
/// A reference of exactly [`MAX_BYTES`] is returned; one byte more is an error naming the
|
||||
/// command, with no part of the reference.
|
||||
#[test]
|
||||
fn a_reference_past_the_limit_is_an_error() {
|
||||
let with = |summary: String| -> Result<String> {
|
||||
let schema: &'static ParamSchema = Box::leak(Box::new(ParamSchema::new(&[], Box::leak(summary.into_boxed_str()))));
|
||||
reference(&[spec("test.big", &[], Some(schema))])
|
||||
};
|
||||
let base = with("x".into()).unwrap().len();
|
||||
let fits = with("x".repeat(MAX_BYTES - base + 1)).unwrap();
|
||||
assert_eq!(fits.len(), MAX_BYTES);
|
||||
let e = with("x".repeat(MAX_BYTES - base + 2)).unwrap_err().to_string();
|
||||
assert!(e.contains(ID) && e.contains("larger than 1048576 bytes"), "{e}");
|
||||
assert!(e.len() < 200, "{e}");
|
||||
}
|
||||
|
||||
/// An unknown key is refused with a parameter error naming it, and the command needs no
|
||||
/// document.
|
||||
#[test]
|
||||
fn an_unknown_parameter_is_refused_naming_it() {
|
||||
let mut s = Session::new();
|
||||
let e = s.execute(ID, &json!({"prefix": "view."})).unwrap_err().to_string();
|
||||
assert!(e.contains(ID) && e.contains("`prefix`"), "{e}");
|
||||
assert!(s.execute(ID, &json!([])).is_err());
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute(ID, &json!({})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_marks_each_punctuation_character_and_flattens_control_characters() {
|
||||
assert_eq!(escape("a|b"), "a\\|b");
|
||||
assert_eq!(escape("WWW.x and w.x"), "WWW\\.x and w.x");
|
||||
assert_eq!(escape("é\u{7}\u{85}z"), "é z");
|
||||
assert_eq!(escape("1.5 > 1"), "1.5 \\> 1");
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's solid fill and stroke for this instance only, as the Eyedropper Options allow, and a sampled gradient or pattern, a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -1204,11 +1204,10 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let attrs = s.prefs.eyedropper.attrs(p).map_err(|e| bad(C, e))?;
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection takes the clicked
|
||||
// object's solid fill and stroke, as the Eyedropper Options allow, for this instance only. A
|
||||
// gradient or pattern sampled for it, a source that is not a path, compound path or type (a
|
||||
// symbol instance's own appearance is empty), and options that pick up neither color are
|
||||
// refused, and the paint defaults stay as they are. A path of a compound path stands for the
|
||||
// compound path, which holds the paint.
|
||||
// object's fill and stroke, as the Eyedropper Options allow, for this instance only. A source
|
||||
// that is not a path, compound path or type (a symbol instance's own appearance is empty) and
|
||||
// options that pick up neither color are refused, and the paint defaults stay as they are. A
|
||||
// path of a compound path stands for the compound path, which holds the paint.
|
||||
if !reverse
|
||||
&& !append
|
||||
&& !defaults_only
|
||||
@@ -1219,11 +1218,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src = Arc::new(d.node(super::path::compound_or_self(d, clicked)).ok_or(EngineError::NoNode(clicked))?.clone());
|
||||
let (fill, stroke) = (super::paint::proxy_paint(&src, false, None), super::paint::proxy_paint(&src, true, None));
|
||||
let a = attrs.appearance;
|
||||
if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src)
|
||||
|| !(a.fill.color || a.stroke.color)
|
||||
|| (a.fill.color && !super::paint::part_takes(&fill))
|
||||
|| (a.stroke.color && !super::paint::part_takes(&stroke))
|
||||
{
|
||||
if !vectorcraft_doc::symbol_overrides::takes_part_paint(&src) || !(a.fill.color || a.stroke.color) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| {
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assets",
|
||||
[],
|
||||
None,
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
|
||||
"{} → {assets: [{id, name, nodes: [id…], bounds: [x, y, width, height] | null (the crop: the bounds the renderer measures for what its art draws, effects included, with the clips of the groups and layers that hold it), format3D: usda|usdz|gltf|obj | null (a 3D asset's mesh format; null for art exported as pictures)}]} the Asset Export panel's assets, in order",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
|
||||
@@ -272,7 +272,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Symbol Instance Part",
|
||||
[],
|
||||
None,
|
||||
"{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke with a solid color or none, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom with a solid fill and stroke (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused) change that object's fill or stroke for this instance only; gradients and patterns are refused, and so are the commands that change the selected objects without ids (transparency.set, the gradient commands, object.group, edit.cut and edit.clear among them); edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}",
|
||||
"{id, path: [i…] (as symbol.instance.setAppearance)} select one path, compound path or type object of a dynamic symbol instance's art, as a Direct Selection click on it does: the instance is selected alone, and until the selection changes paint.setFill and paint.setStroke (solid, none, gradient or pattern), transparency.set with opacity and/or blend, paint.invert and paint.complement on a solid color (without ids, id or item; type whose characters differ in color is refused) and appearance.copyFrom (the Eyedropper, without ids, reverse or append; options that pick up neither color are refused; a gradient or pattern fill or stroke is taken) change that object for this instance only; the gradient annotator commands, isolate/knockout on transparency.set, object.group, edit.cut and edit.clear among the commands that change the selected objects without ids are refused; edit.copy copies the instance whole, and selection exports, artboard.fitToSelection, object.liquify, object.isolate, library.add and select.save use the instance (docs/mcp.md); selectPart itself is refused for a static symbol, a path naming no object, a group, image or other kind of object, a hidden, locked or template object or one inside such a group, and a hidden or locked instance → {id, path}",
|
||||
has_doc,
|
||||
symbol_instance_select_part
|
||||
),
|
||||
|
||||
@@ -510,7 +510,7 @@ pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_param(p, "brush").map(str::to_string).filter(|n| s.doc().is_ok_and(|st| brush::find(&st.doc, n).is_some()));
|
||||
let spec = find_command("path.freehand").ok_or_else(|| EngineError::UnknownCommand("path.freehand".into()))?;
|
||||
let r = (spec.run)(s, p)?;
|
||||
let r = crate::cmd::run_checked(s, spec, p)?;
|
||||
let (Some(name), Some(id)) = (name, id_param(&r, "id")) else { return Ok(r) };
|
||||
s.edit("Paintbrush", |d, _| {
|
||||
if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) {
|
||||
|
||||
@@ -90,10 +90,11 @@ pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str,
|
||||
})
|
||||
}
|
||||
|
||||
/// The refusal of anything but a solid color fill or stroke change while an object of a symbol
|
||||
/// instance's art is selected ([`selected_part`]), and of selecting any other object of the art.
|
||||
/// The refusal of a change that is not the fill, stroke, opacity or blend of a path, compound path
|
||||
/// or type while an object of a symbol instance's art is selected ([`selected_part`]), and of
|
||||
/// selecting any other object of the art.
|
||||
pub(crate) fn part_only() -> EngineError {
|
||||
EngineError::Other("Only the solid color fill and stroke of a path, compound path or type selected in a symbol instance can change".into())
|
||||
EngineError::Other("Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change".into())
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -115,7 +115,8 @@ pub(crate) fn subpath_selected_segments(
|
||||
let n = sp.anchors.len();
|
||||
let mut selected_segs = BTreeSet::new();
|
||||
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| segments.iter().any(|&(s, _)| s == si));
|
||||
// Segments picked anywhere on the path leave anchors out of it, as Clear does.
|
||||
let has_explicit_segs = seg_refs.is_some_and(|segments| !segments.is_empty());
|
||||
if has_explicit_segs {
|
||||
if let Some(segments) = seg_refs {
|
||||
for &(s, seg) in segments {
|
||||
|
||||
@@ -48,9 +48,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert to Grayscale",
|
||||
["Edit", "Edit Colors"],
|
||||
None,
|
||||
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert) → {changed, notChanged, warning?}",
|
||||
"{fill?, stroke?, includeImages?, includePatterns?, ids?} (as edit.colors.invert; an embedded image is stored with one gray channel) → {changed, notChanged, warning?}",
|
||||
has_selection,
|
||||
|s, p| recolor(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|
||||
|s, p| recolor_gray(s, p, "edit.colors.toGrayscale", "Convert to Grayscale", &to_gray)
|
||||
),
|
||||
cmd!(
|
||||
"edit.colors.toRGB",
|
||||
@@ -187,6 +187,8 @@ pub(crate) struct Recolor<'a> {
|
||||
/// Maps solid colours and gradient stops with their link and tint in place of `f`.
|
||||
links: Option<&'a LinkMap<'a>>,
|
||||
scope: Scope,
|
||||
/// Recolored images are stored with one gray channel ([`ImageBlob::map_gray`]).
|
||||
gray_images: bool,
|
||||
/// Image key → the key of its recoloured copy (`None`: unchanged).
|
||||
images: HashMap<String, Option<String>>,
|
||||
/// Pattern name → the name of its recoloured copy (`None`: unchanged, or being recoloured).
|
||||
@@ -198,7 +200,17 @@ pub(crate) struct Recolor<'a> {
|
||||
|
||||
impl<'a> Recolor<'a> {
|
||||
pub(crate) fn new(scope: Scope, f: &'a dyn Fn(Color) -> Color) -> Self {
|
||||
Self { f, links: None, scope, images: HashMap::new(), patterns: HashMap::new(), new_images: vec![], new_patterns: vec![], changed: 0 }
|
||||
Self {
|
||||
f,
|
||||
links: None,
|
||||
scope,
|
||||
gray_images: false,
|
||||
images: HashMap::new(),
|
||||
patterns: HashMap::new(),
|
||||
new_images: vec![],
|
||||
new_patterns: vec![],
|
||||
changed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass that maps only solid colours and gradient stops, with their swatch link and tint
|
||||
@@ -215,7 +227,7 @@ impl<'a> Recolor<'a> {
|
||||
|
||||
/// A pass that maps colors as this one does, with nothing recolored yet.
|
||||
fn again(&self) -> Self {
|
||||
Self { links: self.links, ..Self::new(self.scope, self.f) }
|
||||
Self { links: self.links, gray_images: self.gray_images, ..Self::new(self.scope, self.f) }
|
||||
}
|
||||
|
||||
/// The entries of `objects` (ids, each with a flag) whose object this pass would change, other
|
||||
@@ -313,10 +325,15 @@ impl<'a> Recolor<'a> {
|
||||
return done.clone();
|
||||
}
|
||||
let f = self.f;
|
||||
let new = d.images.get(key)?.map_rgb(|[r, g, b]| {
|
||||
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
});
|
||||
let blob = d.images.get(key)?;
|
||||
let new = if self.gray_images {
|
||||
blob.map_gray(|[r, g, b]| f(Color::rgb8(r, g, b)).to_rgba8(1.0)[0])
|
||||
} else {
|
||||
blob.map_rgb(|[r, g, b]| {
|
||||
let [r, g, b, _] = f(Color::rgb8(r, g, b)).to_rgba8(1.0);
|
||||
[r, g, b]
|
||||
})
|
||||
};
|
||||
let new = new.map(|blob| {
|
||||
let k = blob.content_key();
|
||||
self.new_images.push((k.clone(), blob));
|
||||
@@ -400,6 +417,11 @@ pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dy
|
||||
run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
|
||||
}
|
||||
|
||||
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
|
||||
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) })
|
||||
}
|
||||
|
||||
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
|
||||
/// link and tint.
|
||||
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result<Value> {
|
||||
@@ -575,10 +597,11 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
|
||||
};
|
||||
let convert = bool_or(p, "convert", false);
|
||||
recolor(s, p, C, "Adjust Colors", &move |c| {
|
||||
let f = move |c| {
|
||||
let out = adjust(c);
|
||||
if convert { out } else { keep_model(c, out) }
|
||||
})
|
||||
};
|
||||
if convert && mode == "gray" { recolor_gray(s, p, C, "Adjust Colors", &f) } else { recolor(s, p, C, "Adjust Colors", &f) }
|
||||
}
|
||||
|
||||
enum BlendOrder {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export CSS",
|
||||
[],
|
||||
None,
|
||||
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of the object's visual bounds, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
|
||||
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
|
||||
@@ -183,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Lock Guides",
|
||||
["View", "Guides"],
|
||||
Some("Cmd+Alt+;"),
|
||||
"{locked?: bool} toggle (or set) the session's guide lock; locking deselects the ruler guides and guide paths in every open document → {locked}",
|
||||
"{locked?: bool} toggle (or set) the session's guide lock, leaving the lockGuidesByDefault preference as it is; locking deselects the ruler guides and guide paths in every open document; guide.add and a guide dragged out of a ruler still make new guides while locked → {locked}",
|
||||
has_doc,
|
||||
lock_guides
|
||||
),
|
||||
@@ -277,6 +277,27 @@ impl Session {
|
||||
pub fn guides_locked(&self) -> bool {
|
||||
self.menu.guides_locked
|
||||
}
|
||||
|
||||
/// Set View → Guides → Lock Guides. Locked guides can't stay selected, ruler guides or guide
|
||||
/// paths, in any open document ([`Session::select`] lets those go in the active one).
|
||||
pub(crate) fn set_guides_locked(&mut self, locked: bool) {
|
||||
self.menu.guides_locked = locked;
|
||||
if !locked {
|
||||
return;
|
||||
}
|
||||
let guides_selected =
|
||||
self.doc().is_ok_and(|st| !st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id)));
|
||||
// It fails only without a document, and then no guide is selected.
|
||||
if guides_selected {
|
||||
let _ = self.select(|_, sel| sel.guides.clear());
|
||||
}
|
||||
let active = self.active;
|
||||
for (i, st) in self.docs.iter_mut().enumerate() {
|
||||
if Some(i) != active && crate::deselect_hidden(&self.menu, &st.doc, &mut st.selection) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Select ----------
|
||||
@@ -717,21 +738,7 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn lock_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let v = switch_or(p, "locked", !s.menu.guides_locked, "view.guides.lock")?;
|
||||
s.menu.guides_locked = v;
|
||||
// Locked guides can't stay selected, ruler guides or guide paths, in any open document
|
||||
// ([`Session::select`] lets those go in the active one).
|
||||
let st = s.doc()?;
|
||||
if v && (!st.selection.guides.is_empty() || st.selection.objects.iter().any(|id| crate::is_guide_path(&st.doc, *id))) {
|
||||
s.select(|_, sel| sel.guides.clear())?;
|
||||
}
|
||||
if v {
|
||||
let active = s.active;
|
||||
for (i, st) in s.docs.iter_mut().enumerate() {
|
||||
if Some(i) != active && crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection) {
|
||||
st.revision += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.set_guides_locked(v);
|
||||
Ok(json!({ "locked": v }))
|
||||
}
|
||||
|
||||
|
||||
@@ -1063,8 +1063,12 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
|
||||
if cuts.is_empty() {
|
||||
subpaths.push(sp);
|
||||
} else {
|
||||
} else if seg_refs.is_some_and(|segments| !segments.is_empty()) {
|
||||
subpaths.extend(super::path::without_segments(sp, &cuts));
|
||||
} else {
|
||||
// Picked anchors leave the path with their connections, as Clear removes them.
|
||||
let gone: BTreeSet<usize> = anchor_refs.into_iter().flatten().filter_map(|&(s, a)| (s == si).then_some(a)).collect();
|
||||
subpaths.extend(super::path::without_anchors(sp, &gone));
|
||||
}
|
||||
}
|
||||
subpaths.retain(|sp| sp.anchors.len() >= 2);
|
||||
|
||||
@@ -280,9 +280,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let item = item_target(s, p, C)?;
|
||||
if effects::is_three_d(id) {
|
||||
for target in appearance_targets(s, p)? {
|
||||
let targets = appearance_targets(s, p)?;
|
||||
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
|
||||
let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?;
|
||||
effects::validate_three_d(n, id, &effect.params).map_err(|e| bad(C, e))?;
|
||||
// A new effect goes after the item's others.
|
||||
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
|
||||
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
|
||||
effects::validate_three_d_at(n, id, &effect.params, on).map_err(|e| bad(C, e))?;
|
||||
if id == effects::REVOLVE && effects::has_revolve(n) {
|
||||
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
|
||||
}
|
||||
@@ -589,7 +593,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cur.extend(new);
|
||||
}
|
||||
if visible != Some(false) {
|
||||
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d_at(n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
|
||||
} else {
|
||||
// Hidden, the effect draws nothing, so its object need not fit. The values given are
|
||||
// checked, and after a change of 3D type so is every value it keeps.
|
||||
@@ -865,8 +869,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
// keeps it as its only member).
|
||||
Some((image, false)) => Some(rasterfx::replace_with_image(v, image)),
|
||||
image => {
|
||||
let m = if container && effects::has_solid(&v) {
|
||||
// A group's or layer's 3D effect: the shaded faces of its members' solids.
|
||||
let m = if (container || matches!(n.kind, NodeKind::Text(_))) && (effects::has_solid(&v) || effects::has_revolve(&v)) {
|
||||
// A 3D effect on a group or layer, or on type: the shaded faces of its solids.
|
||||
effects::expand_leaf(d, &v, &mut stroke_art)
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
|
||||
@@ -193,6 +193,169 @@ fn type_extrudes_as_its_glyphs_and_stays_editable() {
|
||||
assert_ne!(effects::solid_art(&node(&s, id)).unwrap(), art, "the solid follows the edited text");
|
||||
}
|
||||
|
||||
/// #3617: Revolve takes live type and stays type, updating when the text changes, and saves,
|
||||
/// exports, expands and undoes as one step.
|
||||
#[test]
|
||||
fn type_revolves_as_its_glyphs_and_stays_editable() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": "O", "size": 72})).unwrap();
|
||||
let id = NodeId(t["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#cc2200"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null, "params": {"segments": 16}})).unwrap();
|
||||
let n = node(&s, id);
|
||||
assert!(matches!(n.kind, NodeKind::Text(_)), "still type");
|
||||
let art = effects::revolve_art(&n).expect("a surface of the glyphs");
|
||||
let mut tinted = false;
|
||||
art.walk(&mut |c| {
|
||||
if let Some([r, g, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
|
||||
tinted |= r > g && r > b;
|
||||
}
|
||||
});
|
||||
assert!(tinted, "shaded from the characters' red");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let restored = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(effects::revolve_art(restored.node(id).unwrap()).unwrap(), art, "the same art after a save");
|
||||
let meshes = effects::three_d_meshes(&n).unwrap();
|
||||
assert_eq!(meshes.len(), 1, "one mesh of every contour of the type");
|
||||
s.execute("text.setText", &json!({"ids": [id.0], "text": "OO"})).unwrap();
|
||||
assert_ne!(effects::revolve_art(&node(&s, id)).unwrap(), art, "the surface follows the edited text");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(!effects::has_revolve(&node(&s, id)), "expanded");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Text(_)));
|
||||
assert!(effects::has_revolve(&node(&s, id)));
|
||||
// Extrude & Bevel on type expands the same way.
|
||||
s.execute("effect.remove", &json!({"index": 0, "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(!effects::has_solid(&node(&s, id)), "expanded");
|
||||
}
|
||||
|
||||
/// Revolve refuses type with no outlines, and a group with no visible shape, without adding an
|
||||
/// effect. Extrude & Bevel gives the same reason for empty type.
|
||||
#[test]
|
||||
fn revolve_refuses_type_and_groups_without_a_shape() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
for text in ["", " "] {
|
||||
let t = s.execute("text.create", &json!({"x": 50, "y": 100, "text": text, "size": 72})).unwrap();
|
||||
let id = NodeId(t["id"].as_u64().unwrap());
|
||||
for effect in ["threeD.revolve", "threeD.extrude"] {
|
||||
let err = s.execute("effect.apply", &json!({"effect": effect, "ids": [id.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("at least two anchors"), "{effect}, {text:?}: {err}");
|
||||
assert!(node(&s, id).appearance.effects.is_empty());
|
||||
}
|
||||
}
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
for member in [a.0, b] {
|
||||
s.execute("select.set", &json!({"ids": [member]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
}
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("group holding a shape"), "{err}");
|
||||
assert!(node(&s, g).appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// A Revolve on one fill is checked in that fill's paint, and `effect.setParams` on it as well.
|
||||
#[test]
|
||||
fn revolve_on_a_fill_is_checked_in_that_fills_paint() {
|
||||
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer};
|
||||
let (mut s, id) = session_with_rect();
|
||||
// The paint copies of 100 faces reach the 256 MiB budget: 8 segments stay under, 64 pass it.
|
||||
let count = (256 << 20) / (4 * 100 * std::mem::size_of::<GradientStop>());
|
||||
let stops = (0..count).map(|i| GradientStop::new(i as f32 / count as f32, Color::rgb(1.0, 0.0, 0.0))).collect();
|
||||
let ramp = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
s.edit("fills", |d, _| {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.appearance.items =
|
||||
vec![AppearanceItem::Fill(FillLayer::new(ramp)), AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0))))];
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0})).unwrap_err().to_string();
|
||||
assert!(err.contains("simplify the gradient"), "{err}");
|
||||
assert!(node(&s, id).appearance.items[0].effects().is_empty());
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": 0, "params": {"segments": 8}})).unwrap();
|
||||
let err = s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": 0, "params": {"segments": 128}})).unwrap_err().to_string();
|
||||
assert!(err.contains("simplify the gradient"), "{err}");
|
||||
}
|
||||
|
||||
/// A hidden Revolve still counts as the object's one Revolve: a second one is refused, and the
|
||||
/// hidden one can be shown again over the geometry effects after it.
|
||||
#[test]
|
||||
fn a_second_revolve_is_refused_over_a_hidden_one() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": false})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.roughen", "ids": [id.0], "item": null})).unwrap();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [id.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("one Revolve effect"), "{err}");
|
||||
let ids: Vec<_> = node(&s, id).appearance.effects.iter().map(|e| e.id.clone()).collect();
|
||||
assert_eq!(ids, ["threeD.revolve", "distort.roughen"]);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "ids": [id.0], "item": null, "visible": true})).unwrap();
|
||||
assert!(node(&s, id).appearance.effects[0].visible);
|
||||
}
|
||||
|
||||
/// Revolve on a group sweeps every member about one axis on the left edge of their bounds, keeps
|
||||
/// each member's paint, follows an edited member, expands and undoes as one step.
|
||||
#[test]
|
||||
fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#cc2200"})).unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 250, "y": 100, "width": 50, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [b], "color": "#0022cc"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null, "params": {"segments": 16, "rotationX": 90}})).unwrap();
|
||||
assert_eq!(node(&s, g).children().unwrap().len(), 2, "the members stay as they were");
|
||||
let art = effects::revolve_art(&node(&s, g)).expect("a surface of the members");
|
||||
// The axis is the left edge of both members together (x = 100), so the right member's far
|
||||
// wall sweeps out to 200 pt from it on either side: x = 300 and x = -100.
|
||||
let bounds = art.visual_bounds().unwrap();
|
||||
assert!((bounds.x1 - 300.0).abs() < 2.0 && (bounds.x0 + 100.0).abs() < 2.0, "{bounds:?}");
|
||||
let (mut red, mut blue) = (false, false);
|
||||
art.walk(&mut |c| {
|
||||
if let Some([r, _, b, _]) = c.appearance.fill_paint().color().map(|c| c.to_rgba8(1.0)) {
|
||||
red |= r > b;
|
||||
blue |= b > r;
|
||||
}
|
||||
});
|
||||
assert!(red && blue, "each member keeps its own paint");
|
||||
assert_eq!(effects::three_d_meshes(&node(&s, g)).unwrap().len(), 2, "a mesh for each member");
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
|
||||
assert!(vectorcraft_testkit::svg_shapes(&svg) >= 4, "both members exported as vector faces");
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"dx": -40, "dy": 0})).unwrap();
|
||||
assert_ne!(effects::revolve_art(&node(&s, g)).unwrap(), art, "a moved member reshapes the surface");
|
||||
s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap();
|
||||
assert!(!effects::has_revolve(&node(&s, g)), "expanded");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(effects::has_revolve(&node(&s, g)));
|
||||
}
|
||||
|
||||
/// A group holding what can't be swept is refused as a whole, and a clipping group is named.
|
||||
#[test]
|
||||
fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() {
|
||||
let (mut s, a) = session_with_rect();
|
||||
let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap();
|
||||
let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone();
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [clip.as_u64().unwrap()], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("path, compound path, type or group"), "{err}");
|
||||
let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [clip, c]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string();
|
||||
assert!(err.contains("Revolve on a group") && err.contains("clipping groups"), "{err}");
|
||||
assert!(node(&s, g).appearance.effects.is_empty());
|
||||
}
|
||||
|
||||
/// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is
|
||||
/// stored as the angle that shows the same view, and a later angle replaces an earlier strength.
|
||||
#[test]
|
||||
@@ -581,7 +744,7 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
let copies = n.children().unwrap();
|
||||
assert_eq!(copies.len(), 3, "the path and its two copies");
|
||||
let xs: Vec<f64> = copies.iter().map(|c| c.geometric_bounds().unwrap().x0).collect();
|
||||
assert_eq!(xs, vec![100.0, 250.0, 400.0]);
|
||||
assert_eq!(xs, vec![400.0, 250.0, 100.0], "the original on top");
|
||||
for c in copies {
|
||||
assert!(matches!(c.kind, NodeKind::Path { .. }), "{}", c.kind_label());
|
||||
assert_eq!(fill(c), Some(Color::rgb(1.0, 0.0, 0.0)));
|
||||
@@ -600,10 +763,10 @@ fn expand_appearance_makes_each_copy_of_a_transform_an_object() {
|
||||
s.execute("effect.expandAppearance", &json!({"ids":[id.0]})).unwrap();
|
||||
let columns = node(&s, id).children().unwrap().to_vec();
|
||||
assert_eq!(columns.len(), 3);
|
||||
for (col, x) in columns.iter().zip([100.0, 250.0, 400.0]) {
|
||||
for (col, x) in columns.iter().zip([400.0, 250.0, 100.0]) {
|
||||
let cells = col.children().unwrap_or_else(|| panic!("a column is a group: {}", col.kind_label()));
|
||||
let ys: Vec<(f64, f64)> = cells.iter().map(|c| (c.geometric_bounds().unwrap().x0, c.geometric_bounds().unwrap().y0)).collect();
|
||||
assert_eq!(ys, vec![(x, 100.0), (x, 250.0)]);
|
||||
assert_eq!(ys, vec![(x, 250.0), (x, 100.0)]);
|
||||
assert!(cells.iter().all(|c| matches!(c.appearance.fill_paint(), Paint::Solid { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +184,8 @@ mod tests_batch;
|
||||
#[cfg(test)]
|
||||
mod tests_screens;
|
||||
#[cfg(test)]
|
||||
mod tests_selexport;
|
||||
#[cfg(test)]
|
||||
mod tests_text;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in their layers)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored. Never changes the document's path",
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects cropped to their bounds (template layers left out) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is ignored",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -94,27 +94,63 @@ pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document
|
||||
return Err(bad("document.export", "select something to export (or turn off selectedOnly)"));
|
||||
}
|
||||
let mut d = Document::clone(&st.doc);
|
||||
d.layers = st.doc.layers.iter().filter_map(|l| selected_part(l, &keep)).map(Arc::new).collect();
|
||||
d.layers = enclosed(&st.doc, &keep, false);
|
||||
Ok(Cow::Owned(d))
|
||||
}
|
||||
|
||||
/// `n` with only the parts in `keep` (whole, with everything inside them), `None` when none is.
|
||||
fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
|
||||
/// The layers of `doc` with only the objects in `keep` (whole, with everything inside them), each
|
||||
/// in the layers, groups and compound paths that hold it. Those keep what they apply to the object
|
||||
/// on the canvas: their clipping paths, opacity masks, effects, opacity and blend modes. An object
|
||||
/// of a blend, envelope, repeat or intertwine goes in on its own, without the art made from it. With
|
||||
/// `shown`, the layers and groups that hold the objects are visible, and those layers print and are
|
||||
/// not template layers.
|
||||
fn enclosed(doc: &Document, keep: &HashSet<NodeId>, shown: bool) -> Vec<Arc<Node>> {
|
||||
let holders: HashSet<NodeId> = keep.iter().filter_map(|id| doc.ancestry(*id)).flatten().filter(|id| !keep.contains(id)).collect();
|
||||
let mut out = vec![];
|
||||
for l in &doc.layers {
|
||||
selected_part(l, keep, &holders, shown, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The parts of `n` in `keep` (whole, with everything inside them), added to `out`: `n` itself, or
|
||||
/// `n` with only those parts when it is one of their `holders`, made visible, printable and not a
|
||||
/// template with `shown`.
|
||||
fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId>, shown: bool, out: &mut Vec<Arc<Node>>) {
|
||||
if keep.contains(&n.id) {
|
||||
return Some(n.clone());
|
||||
out.push(n.clone());
|
||||
return;
|
||||
}
|
||||
let Some(children) = n.children().filter(|_| holders.contains(&n.id)) else { return };
|
||||
let mut kept = vec![];
|
||||
for c in children {
|
||||
selected_part(c, keep, holders, shown, &mut kept);
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }) {
|
||||
out.extend(kept);
|
||||
return;
|
||||
}
|
||||
let children = n.children()?;
|
||||
let mut kept: Vec<Arc<Node>> = children.iter().filter_map(|c| selected_part(c, keep).map(Arc::new)).collect();
|
||||
if kept.is_empty() {
|
||||
return None;
|
||||
return;
|
||||
}
|
||||
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
if let Some(first) = children.first().filter(|f| clip && kept.first().is_none_or(|k| k.id != f.id)) {
|
||||
// A clipping group or layer keeps its clipping path; a Shaper group its source art, which
|
||||
// draws nothing.
|
||||
let first_stays = n.clips() || n.extras().shaper.is_some();
|
||||
if let Some(first) = children.first().filter(|f| first_stays && kept.first().is_none_or(|k| k.id != f.id)) {
|
||||
kept.insert(0, first.clone());
|
||||
}
|
||||
let mut out = n.clone();
|
||||
*out.children_mut()? = kept;
|
||||
Some(out)
|
||||
let mut part = Node::clone(n);
|
||||
if let Some(ch) = part.children_mut() {
|
||||
*ch = kept;
|
||||
}
|
||||
if shown {
|
||||
part.visible = true;
|
||||
if let NodeKind::Layer { template, printable, .. } = &mut part.kind {
|
||||
*template = false;
|
||||
*printable = true;
|
||||
}
|
||||
}
|
||||
out.push(Arc::new(part));
|
||||
}
|
||||
|
||||
/// `doc` with only the art over `rect` (an artboard): objects whose visual bounds miss it are left
|
||||
@@ -126,13 +162,20 @@ fn selected_part(n: &Node, keep: &HashSet<NodeId>) -> Option<Node> {
|
||||
/// holds a symbol instance also stays when what the canvas paints for it reaches `rect`
|
||||
/// ([`vectorcraft_render::painted_bounds`]: the effects in the symbols' art and its own effects). A
|
||||
/// clipping layer keeps every object, its clipping path among them. An artboard's file then holds
|
||||
/// its own art, not a whole document of artboards.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document {
|
||||
fn kept(n: &Arc<Node>, doc: &Document, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect) -> Option<Arc<Node>> {
|
||||
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
|
||||
/// the next artboard of the same document.
|
||||
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
|
||||
fn kept(
|
||||
n: &Arc<Node>,
|
||||
doc: &Document,
|
||||
symbols: &SymbolBoxes,
|
||||
rect: vectorcraft_geom::Rect,
|
||||
renderer: &mut vectorcraft_render::Renderer,
|
||||
) -> Option<Arc<Node>> {
|
||||
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
|
||||
let mut layer = Node::clone(n);
|
||||
let children = layer.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
return Some(Arc::new(layer));
|
||||
}
|
||||
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
|
||||
@@ -141,19 +184,18 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect) -> Document
|
||||
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
|
||||
let mut group = Node::clone(n);
|
||||
let children = group.children_mut()?;
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect)).collect();
|
||||
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
|
||||
return (!children.is_empty()).then(|| Arc::new(group));
|
||||
}
|
||||
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
|
||||
let mut holds_instance = false;
|
||||
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
|
||||
let drawn = || vectorcraft_render::effect_bounds(symbols, n).is_some_and(over);
|
||||
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || drawn() || painted()).then(|| n.clone())
|
||||
(n.visual_bounds_with(symbols).is_none_or(over) || renderer.effect_bounds(symbols, n).is_some_and(over) || painted()).then(|| n.clone())
|
||||
}
|
||||
let symbols = doc.symbol_boxes().with_brush_art();
|
||||
let mut d = doc.clone();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect)).collect();
|
||||
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
|
||||
d
|
||||
}
|
||||
|
||||
@@ -196,7 +238,7 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
/// with `selectionOnly` the selected objects alone.
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
|
||||
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
|
||||
let doc = selection(s, cmd)?.0;
|
||||
let doc = selection(s, cmd, true)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
}
|
||||
@@ -206,11 +248,21 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
|
||||
/// The selected objects (not on template layers) alone on one layer, with one artboard: their
|
||||
/// visual bounds.
|
||||
fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
/// The selected objects (not on template layers) in the layers and groups that hold them
|
||||
/// ([`isolated`]), with one artboard: their crop. With `text`, the objects alone on one layer, so a
|
||||
/// text export holds the type of the selected objects and not that of a clipping path around them.
|
||||
fn selection(s: &mut Session, cmd: &str, text: bool) -> Result<(Document, vectorcraft_geom::Rect)> {
|
||||
let ids = selected_artwork(s)?;
|
||||
isolated(&s.doc()?.doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))
|
||||
let doc = &s.doc()?.doc;
|
||||
let (mut d, bounds) = isolated(doc, &ids, "Selection").ok_or_else(|| bad(cmd, "select something to export"))?;
|
||||
if text {
|
||||
let mut layer = Node::layer(d.alloc_id(), "Selection", vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
|
||||
}
|
||||
d.layers = vec![Arc::new(layer)];
|
||||
}
|
||||
Ok((d, bounds))
|
||||
}
|
||||
|
||||
/// The selected objects (their top-most selected ancestors) that are artwork: those on template
|
||||
@@ -225,25 +277,30 @@ pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
|
||||
Ok(ids.into_iter().filter(|id| !on_template(*id)).collect())
|
||||
}
|
||||
|
||||
/// The crop of an export of objects `ids` of `doc` alone: the bounds the renderer measures for what
|
||||
/// it draws for them, their effects included ([`vectorcraft_render::effect_bounds`]; symbol
|
||||
/// instances are measured by their art), `None` when they have none.
|
||||
/// The crop of an export of objects `ids` of `doc` alone ([`isolated`]): the bounds the renderer
|
||||
/// measures for what it draws for them, their effects included ([`vectorcraft_render::effect_bounds`];
|
||||
/// symbol instances are measured by their art), with what the layers and groups that hold them
|
||||
/// apply (a clipping group or layer is measured by its clip), `None` when they have none.
|
||||
pub(crate) fn export_crop(doc: &Document, ids: &[NodeId]) -> Option<vectorcraft_geom::Rect> {
|
||||
let symbols = doc.symbol_boxes();
|
||||
ids.iter().filter_map(|id| vectorcraft_render::effect_bounds(&symbols, doc.node(*id)?)).reduce(|a, b| a.union(b))
|
||||
isolated_art(doc, ids).1
|
||||
}
|
||||
|
||||
/// Objects `ids` of `doc` alone on one layer (in that order, back to front), with one artboard
|
||||
/// named `name`: their [`export_crop`] (`None` when they have none).
|
||||
/// The layers of [`isolated`] and their crop.
|
||||
fn isolated_art(doc: &Document, ids: &[NodeId]) -> (Vec<Arc<Node>>, Option<vectorcraft_geom::Rect>) {
|
||||
let keep: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let layers = enclosed(doc, &keep, true);
|
||||
let symbols = doc.symbol_boxes();
|
||||
let bounds = layers.iter().filter_map(|l| vectorcraft_render::effect_bounds(&symbols, l)).reduce(|a, b| a.union(b));
|
||||
(layers, bounds)
|
||||
}
|
||||
|
||||
/// Objects `ids` of `doc` alone, each in the layers and groups that hold it ([`enclosed`], made
|
||||
/// visible), with one artboard named `name`: their [`export_crop`] (`None` when they have none).
|
||||
pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Document, vectorcraft_geom::Rect)> {
|
||||
let bounds = export_crop(doc, ids)?;
|
||||
let nodes: Vec<Arc<Node>> = ids.iter().filter_map(|id| doc.node(*id).cloned().map(Arc::new)).collect();
|
||||
let (layers, bounds) = isolated_art(doc, ids);
|
||||
let bounds = bounds?;
|
||||
let mut d = single_artboard(doc, bounds, name);
|
||||
let mut layer = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let Some(ch) = layer.children_mut() {
|
||||
*ch = nodes;
|
||||
}
|
||||
d.layers = vec![Arc::new(layer)];
|
||||
d.layers = layers;
|
||||
Some((d, bounds))
|
||||
}
|
||||
|
||||
@@ -259,7 +316,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable(C, str_param(p, "format"), path)?;
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C)?;
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
@@ -125,7 +125,7 @@ const BACKGROUND: FormatOption = FormatOption {
|
||||
name: "background",
|
||||
ty: "string",
|
||||
default: "\"transparent\"",
|
||||
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent)",
|
||||
description: "transparent, white, black or a colour such as \"#ff8800\" (JPEG: white when transparent); drawn under the finished art, so blend modes do not read it",
|
||||
};
|
||||
|
||||
const ANTI_ALIAS: FormatOption = FormatOption {
|
||||
|
||||
@@ -180,9 +180,11 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects_for(doc, opts.profile != vectorcraft_svg::Profile::Tiny12);
|
||||
let doc = flat.as_ref().unwrap_or(doc);
|
||||
let mut enc = Encoded { warnings, ..Encoded::default() };
|
||||
// One renderer measures the art over every artboard: each 3D solid is built once.
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for artboard in boards {
|
||||
// A chosen artboard's file holds the art over it (#550) and is named after it (#3544).
|
||||
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect));
|
||||
let over = artboard.filter(|_| chosen).and_then(|b| doc.artboards.get(b)).map(|a| super::export::art_over(doc, a.rect, &mut renderer));
|
||||
let file = ExportOptions { artboard, artboard_title: chosen, ..opts.clone() };
|
||||
let mut out = vectorcraft_svg::export_full(over.as_ref().unwrap_or(doc), &file, native.as_deref());
|
||||
let bytes = out.take_bytes();
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
//! Exports of objects alone (Export Selection, Export for Screens by selection or by layer, Asset
|
||||
//! Export, a CSS rule's picture and `selectedOnly`) draw the objects as the canvas draws them: with
|
||||
//! the clipping paths, opacity masks, effects, opacity and blend modes of the layers and groups that
|
||||
//! hold them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> u64 {
|
||||
v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))
|
||||
}
|
||||
|
||||
/// A red 300 pt square at (100, 100) clipped by a 200 pt circle at (150, 150): (square, clip group).
|
||||
fn clipped(s: &mut Session) -> (u64, u64) {
|
||||
let square = id(&run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let circle = id(&run(s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
|
||||
let group = id(&run(s, "object.clippingMask.make", json!({"ids": [circle, square]})));
|
||||
(square, group)
|
||||
}
|
||||
|
||||
fn b64(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap_or_else(|| panic!("no dataBase64 in {v}"))).unwrap()
|
||||
}
|
||||
|
||||
fn rect_of(v: &Value) -> Rect {
|
||||
let n = |i: usize| v[i].as_f64().unwrap_or_else(|| panic!("bad bounds {v}"));
|
||||
Rect::new(n(0), n(1), n(0) + n(2), n(1) + n(3))
|
||||
}
|
||||
|
||||
/// What the canvas draws of the whole document over `r`, at 1 px per point.
|
||||
fn canvas(s: &Session, r: Rect) -> image::RgbaImage {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, r, 1.0, false);
|
||||
image::load_from_memory(&img.to_png().unwrap()).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
/// The pixels of `png` that differ from `want` by more than 64 in a channel (anti-aliased edges
|
||||
/// differ by less), and every pixel when the sizes differ.
|
||||
fn differing(png: &[u8], want: &image::RgbaImage) -> usize {
|
||||
let got = image::load_from_memory(png).unwrap().to_rgba8();
|
||||
if got.dimensions() != want.dimensions() {
|
||||
return (want.width() * want.height()) as usize;
|
||||
}
|
||||
got.pixels().zip(want.pixels()).filter(|(a, b)| a.0.iter().zip(b.0.iter()).any(|(x, y)| x.abs_diff(*y) > 64)).count()
|
||||
}
|
||||
|
||||
/// Export Selection of what is selected, as a PNG, matches the canvas over its crop: fewer than 200
|
||||
/// pixels differ (anti-aliased edges), or 200 times `edges` with [`selection_png_matches_canvas_with`].
|
||||
fn selection_png_matches_canvas(s: &mut Session, want: Rect, what: &str) {
|
||||
selection_png_matches_canvas_with(s, want, what, 1);
|
||||
}
|
||||
|
||||
fn selection_png_matches_canvas_with(s: &mut Session, want: Rect, what: &str, edges: usize) {
|
||||
let r = run(s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!((got.x0 - want.x0).abs() < 1.5 && (got.y0 - want.y0).abs() < 1.5, "{what}: crop {got:?}, want {want:?}");
|
||||
assert!((got.width() - want.width()).abs() < 3.0 && (got.height() - want.height()).abs() < 3.0, "{what}: crop {got:?}, want {want:?}");
|
||||
let off = differing(&b64(&r), &canvas(s, got));
|
||||
assert!(off < 200 * edges, "{what}: {off} pixels differ from the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_of_a_clipped_object_keeps_its_clip() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "the square alone");
|
||||
let svg = b64(&run(&mut s, "document.exportSelection", json!({"format": "svg"})));
|
||||
let text = String::from_utf8_lossy(&svg);
|
||||
assert!(text.contains("<clipPath") && text.contains("clip-path"), "the SVG clips the square: {text}");
|
||||
// Opened again, the SVG draws what the canvas draws.
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "sel.svg", "dataBase64": vectorcraft_format::base64_encode(&svg)}));
|
||||
let board = t.doc().unwrap().doc.artboards[0].rect;
|
||||
let reopened = canvas(&t, board);
|
||||
let mut png = vec![];
|
||||
reopened.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let off = differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0)));
|
||||
assert!(off < 200, "the reopened SVG: {off} pixels differ from the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_of_a_clipping_layer_keeps_the_layer_clip() {
|
||||
let mut s = session();
|
||||
let layer = id(&run(&mut s, "layer.new", json!({"name": "L"})));
|
||||
run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200}));
|
||||
run(&mut s, "layer.clippingMask.toggle", json!({"id": layer}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a clipping layer's objects");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_keeps_the_opacity_effects_and_mask_of_the_groups_around_it() {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let other = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})));
|
||||
let outer = id(&run(&mut s, "object.group", json!({"ids": [group, other]})));
|
||||
run(&mut s, "transparency.set", json!({"ids": [outer], "opacity": 50}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "inside a group at 50%");
|
||||
// A drop shadow on the clip group reaches past its clip.
|
||||
run(&mut s, "effect.apply", json!({"ids": [group], "effect": "stylize.dropShadow"}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(got.x1 > 352.0 && got.y1 > 352.0, "the crop takes in the clip group's shadow: {got:?}");
|
||||
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with the shadow");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// An opacity mask on the clip group.
|
||||
let mask = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]}}),
|
||||
);
|
||||
run(&mut s, "transparency.makeOpacityMask", json!({"ids": [mask, group]}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(differing(&b64(&r), &canvas(&s, got)) < 200, "with an opacity mask on the clip group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_selection_across_clip_groups_and_of_whole_ones() {
|
||||
let mut s = session();
|
||||
let (a, ga) = clipped(&mut s);
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 90, "height": 90})));
|
||||
let c = id(&run(&mut s, "shape.rectangle", json!({"x": 420, "y": 420, "width": 50, "height": 50})));
|
||||
let gb = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [c, b]})));
|
||||
// A member of each clip group: each keeps its own clip.
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "a member of each of two clip groups");
|
||||
// The clip groups themselves.
|
||||
run(&mut s, "select.set", json!({"ids": [ga, gb]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 470.0, 470.0), "two clip groups");
|
||||
// Nested clip groups: the inner group's member is clipped by both, cropped to the outer clip.
|
||||
let strip = id(&run(&mut s, "shape.rectangle", json!({"x": 0, "y": 200, "width": 500, "height": 100})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [strip, ga]}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(0.0, 200.0, 500.0, 300.0), "a member of nested clip groups");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_clipping_path_and_a_blend_object_export_on_their_own() {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let circle = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap()[0].id.0;
|
||||
assert_ne!(circle, square);
|
||||
// The clipping path alone: the clip group's other art stays out.
|
||||
run(&mut s, "select.set", json!({"ids": [circle]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (200, 200), "cropped to the clipping path");
|
||||
assert!(!img.pixels().any(|p| p[0] > 200 && p[1] < 80 && p[3] > 0), "the clipped square is left out");
|
||||
// An object of a blend goes in on its own, without the blend's steps.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
run(&mut s, "object.blend.make", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let r = run(&mut s, "document.exportSelection", json!({"format": "png", "scale": 1}));
|
||||
let got = rect_of(&r["bounds"]);
|
||||
assert!(got.x1 < 90.0 && got.y1 < 90.0, "the blend object's own bounds: {got:?}");
|
||||
let img = image::load_from_memory(&b64(&r)).unwrap().to_rgba8();
|
||||
let centre = img.get_pixel(img.width() / 2, img.height() / 2);
|
||||
assert!(centre[0] > 200 && centre[3] > 200, "the object is drawn: {centre:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_css_picture_of_a_clipped_object_is_clipped() {
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let star = id(&run(&mut s, "shape.star", json!({"cx": 250, "cy": 250, "radius1": 150, "radius2": 70, "points": 5})));
|
||||
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 100, "height": 100})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, star]}));
|
||||
let r = run(&mut s, "css.export", json!({"ids": [star], "rasterize": true, "unnamed": true}));
|
||||
let image = r["images"].as_array().and_then(|i| i.first()).unwrap_or_else(|| panic!("no picture: {r}"));
|
||||
let png = b64(image);
|
||||
let size = image::load_from_memory(&png).unwrap().to_rgba8().dimensions();
|
||||
assert_eq!(size, (100, 100), "the picture is cropped to the clip");
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(200.0, 200.0, 300.0, 300.0))) < 100, "the picture matches the canvas");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_asset_on_a_hidden_layer_is_drawn_clipped() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let (square, _) = clipped(&mut s);
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "visible": false}));
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
let img = image::load_from_memory(&b64(&r["files"][0])).unwrap().to_rgba8();
|
||||
assert_eq!(img.dimensions(), (200, 200), "cropped to the clip");
|
||||
let (centre, corner) = (img.get_pixel(100, 100), img.get_pixel(3, 3));
|
||||
assert!(centre[0] > 200 && centre[3] > 200, "the square is drawn: {centre:?}");
|
||||
assert_eq!(corner[3], 0, "outside the circle stays clear: {corner:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_and_assets_by_selection_keep_the_clip() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"selection": "one", "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
|
||||
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
|
||||
let png = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".png"))).unwrap();
|
||||
assert!(differing(&b64(png), &want) < 200, "Export for Screens by selection: {}", png["name"]);
|
||||
let svg = r["files"].as_array().unwrap().iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(".svg"))).unwrap();
|
||||
let text = String::from_utf8(b64(svg)).unwrap();
|
||||
assert!(text.contains("<clipPath"), "the SVG clips the square: {text}");
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
let list = run(&mut s, "assets.list", json!({}));
|
||||
let bounds = rect_of(&list["assets"][0]["bounds"]);
|
||||
assert!((bounds.width() - 200.0).abs() < 3.0, "the asset's crop is its clip: {bounds:?}");
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
assert!(differing(&b64(&r["files"][0]), &want) < 200, "Asset Export: {}", r["files"][0]["name"]);
|
||||
}
|
||||
|
||||
/// The red pixels of `png`.
|
||||
fn red(png: &[u8]) -> usize {
|
||||
image::load_from_memory(png).unwrap().to_rgba8().pixels().filter(|p| p[0] > 200 && p[1] < 80 && p[3] > 200).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_on_a_non_printing_layer_exports_to_pdf() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "printable": false}));
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let pdf = b64(&run(&mut s, "document.exportSelection", json!({"format": "pdf", "createLayers": false, "preserveEditing": false})));
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "sel.pdf", "dataBase64": vectorcraft_format::base64_encode(&pdf)}));
|
||||
let page = t.doc().unwrap().doc.artboards[0].rect;
|
||||
let mut png = vec![];
|
||||
canvas(&t, page).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
assert!(red(&png) > 20_000, "the PDF draws the square: {} red pixels", red(&png));
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 300, "the PDF draws what the canvas draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_of_layers_draws_them_as_the_canvas_does() {
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id.0;
|
||||
clipped(&mut s);
|
||||
// A layer at 50% opacity: its art is drawn at 50%.
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 50}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}]}));
|
||||
let png = b64(&r["files"][0]);
|
||||
assert!(differing(&png, &canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0))) < 200, "the layer's opacity applies");
|
||||
// A template layer's art is still drawn.
|
||||
run(&mut s, "transparency.set", json!({"ids": [layer], "opacity": 100}));
|
||||
run(&mut s, "layer.setProps", json!({"id": layer, "template": true}));
|
||||
let r = run(&mut s, "document.exportForScreens", json!({"layers": [layer], "formats": [{"format": "png", "scale": 1}, {"format": "svg"}]}));
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let file = |ext: &str| b64(files.iter().find(|f| f["name"].as_str().is_some_and(|n| n.ends_with(ext))).unwrap());
|
||||
assert!(red(&file(".png")) > 20_000, "the template layer's art is drawn: {} red pixels", red(&file(".png")));
|
||||
assert!(String::from_utf8(file(".svg")).unwrap().contains("<clipPath"), "the SVG holds the clipped art");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_export_of_the_selection_leaves_out_a_type_clipping_path() {
|
||||
let mut s = session();
|
||||
// The front object, the type "Clip", becomes the clipping path.
|
||||
let inner = id(&run(&mut s, "text.create", json!({"x": 100, "y": 110, "text": "Inner"})));
|
||||
let clip = id(&run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "Clip"})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [clip, inner]}));
|
||||
let mut first = None;
|
||||
s.doc().unwrap().doc.layers[0].walk(&mut |n| {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. }) {
|
||||
first = n.children().and_then(|c| c.first()).map(|c| c.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(first, Some(clip), "the type is the clipping path");
|
||||
run(&mut s, "select.set", json!({"ids": [inner]}));
|
||||
let txt = b64(&run(&mut s, "document.export", json!({"format": "txt", "selectionOnly": true})));
|
||||
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
|
||||
let txt = b64(&run(&mut s, "document.exportSelection", json!({"format": "txt"})));
|
||||
assert_eq!(String::from_utf8(txt).unwrap(), "Inner\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_clip_groups_symbols_and_large_selections_keep_their_clips() {
|
||||
// Five clip groups inside each other, each clip a little smaller.
|
||||
let mut s = session();
|
||||
let (square, mut group) = clipped(&mut s);
|
||||
for i in 1..5 {
|
||||
let inset = 10.0 * f64::from(i);
|
||||
let clip = id(&run(&mut s, "shape.rectangle", json!({"x": 150.0 + inset, "y": 150.0 + inset, "width": 200.0 - 2.0 * inset, "height": 400})));
|
||||
group = id(&run(&mut s, "object.clippingMask.make", json!({"ids": [clip, group]})));
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(190.0, 190.0, 310.0, 590.0), "a member of five nested clip groups");
|
||||
|
||||
// A symbol instance in a clip group.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let art = id(&run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 300, "height": 300})));
|
||||
run(&mut s, "select.set", json!({"ids": [art]}));
|
||||
let instance = id(&run(&mut s, "symbol.new", json!({"name": "Red"})));
|
||||
let circle = id(&run(&mut s, "shape.ellipse", json!({"x": 150, "y": 150, "width": 200, "height": 200})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [circle, instance]}));
|
||||
run(&mut s, "select.set", json!({"ids": [instance]}));
|
||||
selection_png_matches_canvas(&mut s, Rect::new(150.0, 150.0, 350.0, 350.0), "a symbol instance in a clip group");
|
||||
|
||||
// 200 clip groups, a member of each selected.
|
||||
let mut s = session();
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let mut members = vec![];
|
||||
for i in 0..200 {
|
||||
let (x, y) = (f64::from(i % 20) * 25.0, f64::from(i / 20) * 25.0);
|
||||
let m = id(&run(&mut s, "shape.rectangle", json!({"x": x, "y": y, "width": 20, "height": 20})));
|
||||
let c = id(&run(&mut s, "shape.ellipse", json!({"x": x, "y": y, "width": 20, "height": 20})));
|
||||
run(&mut s, "object.clippingMask.make", json!({"ids": [c, m]}));
|
||||
members.push(m);
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": members}));
|
||||
// The circles' anti-aliased edges differ by up to about 30 pixels each; without their clips the
|
||||
// squares' corners differ by 86 pixels each.
|
||||
selection_png_matches_canvas_with(&mut s, Rect::new(0.0, 0.0, 495.0, 245.0), "members of 200 clip groups", 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_asset_in_a_hidden_or_locked_clip_group_is_drawn_clipped() {
|
||||
for change in ["object.hide", "object.lock"] {
|
||||
let mut s = session();
|
||||
let (square, group) = clipped(&mut s);
|
||||
let asset = run(&mut s, "assets.add", json!({"ids": [square]}))["assets"][0].as_u64().unwrap();
|
||||
let want = canvas(&s, Rect::new(150.0, 150.0, 350.0, 350.0));
|
||||
run(&mut s, "select.set", json!({"ids": [group]}));
|
||||
run(&mut s, change, json!({}));
|
||||
let r = run(&mut s, "assets.export", json!({"assets": [asset], "formats": [{"format": "png", "scale": 1}]}));
|
||||
assert!(differing(&b64(&r["files"][0]), &want) < 200, "{change}: the asset draws as the canvas did");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_only_keeps_holders_and_takes_a_blend_object_alone() {
|
||||
let mut s = session();
|
||||
let (square, _) = clipped(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [square]}));
|
||||
let r = run(&mut s, "document.export", json!({"format": "png", "scale": 1, "selectedOnly": true}));
|
||||
let board = s.doc().unwrap().doc.artboards[0].rect;
|
||||
assert!(differing(&b64(&r), &canvas(&s, board)) < 200, "selectedOnly keeps the clip");
|
||||
// An object of a blend is written on its own.
|
||||
let mut s = session();
|
||||
let a = id(&run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 60})));
|
||||
let b = id(&run(&mut s, "shape.rectangle", json!({"x": 400, "y": 400, "width": 60, "height": 60})));
|
||||
run(&mut s, "select.set", json!({"ids": [a, b]}));
|
||||
run(&mut s, "object.blend.make", json!({}));
|
||||
run(&mut s, "select.set", json!({"ids": [a]}));
|
||||
let svg = run(&mut s, "document.serialize", json!({"format": "svg", "selectedOnly": true}))["text"].as_str().unwrap().to_string();
|
||||
let mut t = Session::new();
|
||||
run(&mut t, "document.open", json!({"name": "a.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())}));
|
||||
let mut paths = 0;
|
||||
for l in &t.doc().unwrap().doc.layers {
|
||||
l.walk(&mut |n| paths += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Path { .. })));
|
||||
}
|
||||
assert_eq!(paths, 1, "the blend object alone, without the steps: {svg}");
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! cut into atomic regions: the faces of the planar arrangement of every fill, outlined stroke and
|
||||
//! clipping path in them ([`po::regions`]). The same paints cover each whole region, so its colour
|
||||
//! is exact: those paints composited as the renderer composites them ([`Composer`], blend modes by
|
||||
//! [`composite`]), over white (or over nothing with Preserve Alpha); in CMYK documents their inks
|
||||
//! [`composite`]), with white under the finished art (or nothing with Preserve Alpha); in CMYK documents their inks
|
||||
//! composite, plane by plane ([`cmyk_planes`]), and the colour is CMYK. Each region becomes a path
|
||||
//! filled with that flat colour. Where gradients, patterns, images, opacity masks or raster
|
||||
//! effects reach there is no single colour: those regions are rendered into one image per group,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::analysis::{Scratch, outlined_text, overlapping, reach};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, WHITE};
|
||||
use super::compose::{Builder, CLEAR, Composer, Elem, Fill, Kind, Px, WHITE};
|
||||
use super::options::FlattenOptions;
|
||||
use super::{
|
||||
Affine, Appearance, AppearanceItem, Arc, BlendMode, Color, ColorMode, Document, EngineError, FillLayer, FillRule, ImageBlob, ImageObject, Inks,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, effects, isolated_doc, outline_strokes_under, planes_cmyk, po, separate,
|
||||
shape_node, shapes, unique_key,
|
||||
MAX_PIXELS, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, composite, effects, isolated_doc, outline_strokes_under, planes_cmyk, po,
|
||||
separate, shape_node, shapes, unique_key,
|
||||
};
|
||||
|
||||
// ---------- plan ----------
|
||||
@@ -235,18 +235,14 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
|
||||
if alone[3] < 0.5 / 255.0 {
|
||||
return None;
|
||||
}
|
||||
let start = if o.preserve_alpha { CLEAR } else { WHITE };
|
||||
let px = if o.preserve_alpha {
|
||||
alone
|
||||
} else {
|
||||
c.top = None;
|
||||
c.eval(elems, start)
|
||||
};
|
||||
// The white goes under the finished art, as under the renderer's: blend modes read only the art.
|
||||
let on_page = |p: Px| if o.preserve_alpha { p } else { composite(BlendMode::Normal, WHITE, p) };
|
||||
let px = on_page(alone);
|
||||
let rgb = [px[0], px[1], px[2]];
|
||||
// The K plane composites the same way.
|
||||
let k = cmyk.then(|| {
|
||||
c.plane = 1;
|
||||
c.eval(elems, start)[0]
|
||||
on_page(c.eval(elems, CLEAR))[0]
|
||||
});
|
||||
// A paint showing as it is keeps its colour (spot, process, swatch) and overprint.
|
||||
let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3);
|
||||
@@ -266,7 +262,7 @@ fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool
|
||||
}
|
||||
|
||||
/// `art` rendered over `rect` at `ppi`: over white with the white the art doesn't cover taken out
|
||||
/// again (so blend modes see the white page), or over nothing with Preserve Alpha. The image and
|
||||
/// again, or over nothing with Preserve Alpha. The image and
|
||||
/// its `clip` reach a pixel further. An opaque image in a CMYK document holds the art's ink
|
||||
/// amounts (a CMYK TIFF), so its CMYK colours keep their numbers (#2160); other images are PNGs.
|
||||
/// Fails when the image can't be encoded.
|
||||
|
||||
@@ -43,6 +43,7 @@ fn cell(c: &str) -> Cell {
|
||||
}
|
||||
|
||||
pub(super) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv);
|
||||
// Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes.
|
||||
let rows: Vec<Vec<Cell>> = split_unquoted(csv, '\n')
|
||||
.into_iter()
|
||||
@@ -169,7 +170,9 @@ pub(super) fn fmt_value(v: f64) -> String {
|
||||
// `{:.0}` prints its exact digits.
|
||||
if v.abs() < 9e18 { format!("{}", v.round() as i64) } else { format!("{v:.0}") }
|
||||
} else {
|
||||
format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
let s = format!("{:.2}", v).trim_end_matches('0').trim_end_matches('.').to_string();
|
||||
// A tiny negative rounds to "-0.00"; show it as plain zero like -0.0.
|
||||
if s == "-0" { "0".to_string() } else { s }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ fn fmt_value_does_not_saturate_beyond_i64() {
|
||||
assert_eq!(super::fmt_value(2.5), "2.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fmt_value_tiny_negative_is_zero() {
|
||||
assert_eq!(super::fmt_value(-0.004), "0");
|
||||
assert_eq!(super::fmt_value(-0.0049), "0");
|
||||
assert_eq!(super::fmt_value(-0.006), "-0.01");
|
||||
}
|
||||
|
||||
fn graph(s: &mut Session, ty: &str) -> NodeId {
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6";
|
||||
NodeId(
|
||||
@@ -4198,3 +4205,8 @@ fn character_formats_are_kept_and_bigger_labels_space_out() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_leading_byte_order_mark_is_ignored() {
|
||||
assert_eq!(super::parse_csv("\u{feff}1,2\n3,4"), super::parse_csv("1,2\n3,4"));
|
||||
}
|
||||
|
||||
@@ -1167,9 +1167,11 @@ fn artboard_fit_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::panelcmds::refuse_locked(d, &indices)?;
|
||||
}
|
||||
let mut fits = vec![];
|
||||
// One renderer measures every artboard: each 3D solid is built once.
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
for i in unlocked {
|
||||
let was = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
if let Some(b) = vectorcraft_render::encode::art_bounds_on(d, was) {
|
||||
if let Some(b) = renderer.art_bounds_on(d, was) {
|
||||
// At least 1 pt a side, as `rect_from` makes Artboard Options' sizes.
|
||||
fits.push((i, was, Rect::new(b.x0, b.y0, b.x0 + b.width().max(1.0), b.y0 + b.height().max(1.0))));
|
||||
}
|
||||
|
||||
@@ -203,10 +203,11 @@ pub(crate) fn whole_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a command's implementation without the enablement check or journaling.
|
||||
/// Run a command's implementation without the enablement check or journaling. A command with a
|
||||
/// parameter schema runs with its params checked ([`super::run_checked`]).
|
||||
pub(crate) fn run_raw(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
let c = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
super::run_spec(s, c, p)
|
||||
super::run_checked(s, c, p)
|
||||
}
|
||||
|
||||
/// Merge the undo entries pushed since the history had `from` entries into one labelled step.
|
||||
|
||||
@@ -217,13 +217,15 @@ impl Session {
|
||||
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
|
||||
/// stroke proxies and the weight take what the selection shows in them, so new art looks like
|
||||
/// it. A paint the selected objects don't share (a "?" proxy) stays as it was, and art without
|
||||
/// paint (a placed image, whose None would make new art invisible) changes nothing. The
|
||||
/// template is left alone, and without a stroke to show the weight stays too.
|
||||
/// paint (a placed image that isn't colorized, whose None would make new art invisible) changes
|
||||
/// nothing. The template is left alone, and without a stroke to show the weight stays too.
|
||||
pub(crate) fn load_selection_paints(&mut self) {
|
||||
if !self.prefs.new_art_basic {
|
||||
return;
|
||||
}
|
||||
let has_paint = self.proxy_source(false).is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty());
|
||||
let has_paint = self
|
||||
.proxy_source(false)
|
||||
.is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some());
|
||||
if !has_paint {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6,16 +6,23 @@ use super::{
|
||||
use vectorcraft_doc::{NodeKind, TextKind};
|
||||
|
||||
impl Session {
|
||||
/// The bounds of `ids` the Transform panel, the bounding box, Align and Distribute measure:
|
||||
/// with Use Preview Bounds on, visual bounds as drawn (strokes and geometry effects included,
|
||||
/// see [`effects::preview`]), else geometric bounds.
|
||||
/// The bounds of `ids` the Transform panel and the bounding box measure: with Use Preview
|
||||
/// Bounds on, visual bounds as drawn (strokes and geometry effects included, see
|
||||
/// [`effects::preview`]), else geometric bounds; with Measure Type by Glyph Bounds on, point
|
||||
/// type by the ink of its glyphs ([`Session::bounds_measure`]).
|
||||
pub fn transform_bounds(&self, ids: &[NodeId]) -> Option<Rect> {
|
||||
effects::preview::bounds_of(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
|
||||
effects::preview::bounds_of_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
|
||||
}
|
||||
/// [`Session::transform_bounds`] square to the objects' own angle (their rotated bounding
|
||||
/// box, see [`Document::oriented_bounds`]).
|
||||
pub fn transform_box(&self, ids: &[NodeId]) -> Option<OrientedBox> {
|
||||
effects::preview::oriented_bounds(&self.doc().ok()?.doc, ids, self.prefs.use_preview_bounds)
|
||||
effects::preview::oriented_bounds_with(&self.doc().ok()?.doc, ids, self.bounds_measure())
|
||||
}
|
||||
/// How the bounding box, the Transform panel and `object.setBounds` measure objects: Use
|
||||
/// Preview Bounds, and point type by its glyphs with Measure Type by Glyph Bounds
|
||||
/// (`typeGlyphBounds`).
|
||||
pub fn bounds_measure(&self) -> effects::preview::Measure {
|
||||
effects::preview::Measure { preview: self.prefs.use_preview_bounds, glyphs: self.prefs.type_glyph_bounds }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,24 +59,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
let how = s.bounds_measure();
|
||||
if anchors
|
||||
&& transforms_objects(p)
|
||||
&& !bool_or(p, "copy", false)
|
||||
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
|
||||
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, how)
|
||||
{
|
||||
return Ok(Bounds::Anchors(ids, b));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// Sizes are measured square to the bounding box, which a rotation turns with the objects:
|
||||
// the math below runs in its frame.
|
||||
let frame = d.oriented_bounds(&ids, false).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
// the math below runs in its frame. With Measure Type by Glyph Bounds, point type is measured
|
||||
// by its glyphs' ink, which a transform of the type moves and scales with it.
|
||||
let geometric = effects::preview::Measure { preview: false, ..how };
|
||||
let frame = effects::preview::oriented_bounds_with(d, &ids, geometric).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
let g = frame.rect;
|
||||
let symbols = d.symbol_boxes();
|
||||
let by_glyphs = how.glyphs && ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::by_glyphs(&symbols, n, how));
|
||||
// With Use Preview Bounds the values measure the visual box as drawn, whose margins around the
|
||||
// geometric box (left, top, right, bottom) scale with the strokes or stay. The margins of
|
||||
// `vs`, the visual box without the strokes in symbols' art, scale; those strokes keep their
|
||||
// weight when an instance scales, so the rest of the margins stay.
|
||||
// weight when an instance scales, so the rest of the margins stay. Type measured by its glyphs
|
||||
// is measured as drawn after each scale tried instead (below).
|
||||
let (v, vs) = if s.prefs.use_preview_bounds {
|
||||
(effects::preview::oriented_bounds(d, &ids, true).map_or(g, |b| b.rect), scaling_box(d, &ids, &frame).unwrap_or(g))
|
||||
let v = effects::preview::oriented_bounds_with(d, &ids, how).map_or(g, |b| b.rect);
|
||||
(v, if by_glyphs { v } else { scaling_box(d, &ids, &frame).unwrap_or(g) })
|
||||
} else {
|
||||
(g, g)
|
||||
};
|
||||
@@ -125,22 +132,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
// The scales and the point above can miss the size or the reference point when the margins of
|
||||
// the objects differ, the members of groups and the objects in symbols' art included, and with
|
||||
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
|
||||
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects are
|
||||
// measured as drawn after each scale tried instead ([`refit_drawn`]).
|
||||
let symbols = d.symbol_boxes();
|
||||
let drawn = || ids.iter().filter_map(|id| d.node(*id)).any(|n| effects::preview::draws_geometry(&symbols, n));
|
||||
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects,
|
||||
// objects with a butt-capped stroke along a segment at a slant, whose margins change with the
|
||||
// segment's direction, and type measured by its glyphs, are measured as drawn after each scale
|
||||
// tried instead ([`refit_drawn`]).
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let drawn = || {
|
||||
by_glyphs
|
||||
|| ids
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local))
|
||||
};
|
||||
// Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink
|
||||
// included), so the scales above are exact and nothing is refitted.
|
||||
let solved = if !(s.prefs.use_preview_bounds && w >= 0.0 && h >= 0.0) {
|
||||
None
|
||||
} else if transforms_objects(p) && !bool_or(p, "typeAreas", false) && drawn() {
|
||||
let options = scaling_options(s, p);
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let measure = |sx: f64, sy: f64| {
|
||||
let xf = frame.conjugate(about(rp, Affine::scale_non_uniform(sx, sy)));
|
||||
let sc = if Scaling::factor(xf).is_some() { options } else { Scaling::default() };
|
||||
ids.iter().filter_map(|id| d.node(*id)).fold(None, |acc, n| {
|
||||
let mut n = n.clone();
|
||||
n.transform(xf, sc);
|
||||
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in(&symbols, &n, to_local))
|
||||
vectorcraft_geom::union_opt(acc, effects::preview::bounds_in_with(&symbols, &n, to_local, how))
|
||||
})
|
||||
};
|
||||
// The scales above keep the effects' reach as a margin that stays, and give 0 for a size
|
||||
|
||||
@@ -287,7 +287,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result<Point> {
|
||||
// Direct-selected anchors transform alone (see [`apply_transform`]), about their own centre.
|
||||
let st = s.doc()?;
|
||||
if !bool_or(p, "copy", false)
|
||||
&& let Some(b) = effects::preview::anchor_bounds(&st.selection, &st.doc, s.prefs.use_preview_bounds)
|
||||
&& let Some(b) = effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure())
|
||||
{
|
||||
return Ok(b.center());
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, a solid color or `none` changes that object for this instance only, and a gradient or pattern is refused",
|
||||
"{…as paint.setFill, item?: the stroke item to set} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern)",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transparency",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
transparency
|
||||
),
|
||||
@@ -487,12 +487,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
s.remember_paint(&paint);
|
||||
return Ok(json!({"objects": ids.len()}));
|
||||
}
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: a solid color or
|
||||
// none changes that object for this instance only, and anything else is refused.
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: that object's
|
||||
// fill or stroke changes for this instance only (solid, none, gradient or pattern).
|
||||
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
|
||||
if !part_takes(&paint) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| {
|
||||
if fill {
|
||||
o.fill = Some(paint.clone());
|
||||
@@ -620,8 +617,9 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Nod
|
||||
Ok(part)
|
||||
}
|
||||
|
||||
/// Can an object of a dynamic symbol instance's art selected with Direct Selection take `paint`? A
|
||||
/// solid color or none can; a gradient or pattern cannot.
|
||||
/// Can Invert / Complement recolour `paint` on an object of a dynamic symbol instance's art selected
|
||||
/// with Direct Selection? A solid color or none can; a gradient or pattern cannot (one override
|
||||
/// holds one paint, and those commands recolour solid colours only).
|
||||
pub(crate) fn part_takes(paint: &Paint) -> bool {
|
||||
matches!(paint, Paint::Solid { .. } | Paint::None)
|
||||
}
|
||||
@@ -962,6 +960,46 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
|
||||
|
||||
fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "transparency.set";
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: opacity and
|
||||
// blend change that object for this instance only. Isolate, knockout and Appearance `item` /
|
||||
// `target` stay refused here (they act on the instance or a stack row).
|
||||
if p.get("ids").is_none()
|
||||
&& p.get("id").is_none()
|
||||
&& p.get("item").is_none()
|
||||
&& let Some((id, path)) = super::brushsym::selected_part(s)?
|
||||
{
|
||||
for key in ["isolate", "knockout", "knockoutShape", "aligned", "target"] {
|
||||
if p.get(key).is_some() {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
}
|
||||
if p.get("opacity").is_none() && p.get("blend").is_none() {
|
||||
return Err(bad(C, "give opacity or blend"));
|
||||
}
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(v) => Some(Some(v.as_f64().map(super::opacitymask::percent).ok_or_else(|| bad(C, "opacity must be a number"))?)),
|
||||
};
|
||||
let blend = match p.get("blend") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(b) => {
|
||||
let name = b.as_str().ok_or_else(|| bad(C, "blend must be a mode name"))?;
|
||||
Some(Some(BlendMode::parse(name).ok_or_else(|| bad(C, format!("unknown blend mode {b}")))?))
|
||||
}
|
||||
};
|
||||
super::brushsym::edit_part(s, id, &path, "Transparency", |o| {
|
||||
if let Some(op) = opacity {
|
||||
o.opacity = op;
|
||||
}
|
||||
if let Some(b) = blend {
|
||||
o.blend = b;
|
||||
}
|
||||
})?;
|
||||
return ok();
|
||||
}
|
||||
super::opacitymask::refuse_symbol_part_unnamed(s, p)?;
|
||||
let ids = super::opacitymask::transparency_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
|
||||
@@ -18,13 +18,24 @@
|
||||
//! `effect.setParams` answer a key the effect doesn't take, or a value of another type than its
|
||||
//! default, with a parameter error ([`check_effect_params`]).
|
||||
//!
|
||||
//! A command with a parameter schema (`CommandSpec::schema`) is also checked against the schema
|
||||
//! before it runs ([`crate::schemas::check`]): the schema refuses a value of the wrong type or out
|
||||
//! of range, a missing required parameter and an unknown key at any depth, and fills in declared
|
||||
//! defaults, so the command runs with the filled-in params. The check here still runs first for
|
||||
//! such a command, so a misspelled top-level key gets the same error from either, and a
|
||||
//! `command.batch` or an `action.batch` checks each step's schema before the first step runs. The
|
||||
//! keys of commands without a schema, and the options of exports and effects, are checked only as
|
||||
//! this module describes.
|
||||
//!
|
||||
//! Saved steps play through [`Session::replay`] instead: a journal or an action recorded by an older
|
||||
//! version, with a key a command no longer reads or an effect parameter it no longer takes, still
|
||||
//! plays. Even there, an effect's `color` that the effect can't read and a Levels or Curves
|
||||
//! plays. A key a schema doesn't name passes there too, and the values of the parameters it names
|
||||
//! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves
|
||||
//! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams`
|
||||
//! themselves ([`check_effect_color`], [`check_effect_channel`]).
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_apischema::shown_key;
|
||||
|
||||
use super::{bad, command_specs, find_command};
|
||||
use crate::Result;
|
||||
@@ -239,9 +250,11 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> {
|
||||
/// The parameter error of command `id` for `key`, which isn't one of `keys`: with the nearest of
|
||||
/// them, or all of them.
|
||||
pub(crate) fn unknown(id: &str, key: &str, keys: &[&str]) -> crate::EngineError {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
bad(
|
||||
id,
|
||||
match nearest(key, keys) {
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{key}`; did you mean `{near}`?"),
|
||||
None if keys.is_empty() => format!("unknown parameter `{key}`; the command takes no parameters"),
|
||||
None => format!("unknown parameter `{key}`; the command takes: {}", keys.join(", ")),
|
||||
@@ -522,6 +535,7 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
Some(near) => format!("did you mean `{within}{near}`?"),
|
||||
None => format!("`{}` takes: {}", within.trim_end_matches('.'), keys.join(", ")),
|
||||
};
|
||||
let key = shown_key(key);
|
||||
return Err(bad(id, format!("unknown parameter `{within}{key}`; {why}")));
|
||||
}
|
||||
(Some(Value::Object(inner)), Value::Object(value)) => check_option_tree(id, &format!("{within}{key}."), value, inner)?,
|
||||
@@ -538,9 +552,11 @@ fn check_option_tree(id: &str, within: &str, given: &serde_json::Map<String, Val
|
||||
fn check_option_keys(id: &str, within: &str, given: &serde_json::Map<String, Value>, keys: &[&str], why_not: &str, trees: &Value) -> Result<()> {
|
||||
for (key, value) in given {
|
||||
if !keys.contains(&key.as_str()) {
|
||||
let near = nearest(key, keys);
|
||||
let key = shown_key(key);
|
||||
return Err(bad(
|
||||
id,
|
||||
match nearest(key, keys) {
|
||||
match near {
|
||||
Some(near) => format!("unknown parameter `{within}{key}`; did you mean `{within}{near}`?"),
|
||||
None => format!("unknown parameter `{within}{key}`; {why_not}"),
|
||||
},
|
||||
@@ -647,6 +663,7 @@ fn check_screen_rows(id: &str, within: &str, p: &serde_json::Map<String, Value>)
|
||||
Some(near) => format!("did you mean `{within}settings.{near}`?"),
|
||||
None => format!("`{within}settings` takes: {}", formats.join(", ")),
|
||||
};
|
||||
let format = shown_key(format);
|
||||
return Err(bad(id, format!("unknown parameter `{within}settings.{format}`; {why}")));
|
||||
}
|
||||
if let Value::Object(options) = options {
|
||||
@@ -758,10 +775,13 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
check_keys(id, spec.params, params)?;
|
||||
if in_batch {
|
||||
crate::schemas::check(spec, params, false)?;
|
||||
}
|
||||
if matches!(id, "command.batch" | "action.batch") && !in_batch {
|
||||
for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() {
|
||||
if let (Some(step_id), Some(step_params)) = (step.get("command").and_then(Value::as_str), step.get("params")) {
|
||||
check_params_in(step_id, step_params, true)?;
|
||||
if let Some(step_id) = step.get("command").and_then(Value::as_str) {
|
||||
check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -778,8 +798,8 @@ pub(crate) fn nearest_command(id: &str) -> Option<&'static str> {
|
||||
/// The error for `id`, which names no command: with the nearest command id, when one is near.
|
||||
pub(crate) fn unknown_command(id: &str) -> crate::EngineError {
|
||||
match nearest_command(id) {
|
||||
Some(near) => crate::EngineError::UnknownCommandNear(id.to_string(), near.to_string()),
|
||||
None => crate::EngineError::UnknownCommand(id.to_string()),
|
||||
Some(near) => crate::EngineError::UnknownCommandNear(shown_key(id), near.to_string()),
|
||||
None => crate::EngineError::UnknownCommand(shown_key(id)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1329,7 +1329,7 @@ pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, orig
|
||||
|
||||
/// Remove anchors and their incident segments, keeping each surviving stretch as an open path.
|
||||
/// Only a closed path can have a surviving stretch that wraps past the last anchor.
|
||||
fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
|
||||
pub(super) fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let gone: BTreeSet<usize> = removed.iter().copied().filter(|&i| i < n).collect();
|
||||
if gone.is_empty() {
|
||||
|
||||
+116
-35
@@ -11,15 +11,18 @@
|
||||
//! `document.open` reads (`fileio::plugin_formats`).
|
||||
//!
|
||||
//! A filter may ask for a heavy budget (`Budget::Heavy`: minutes rather than a minute, for routing,
|
||||
//! packing or simulation). It installs only once the user agrees (`plugin.install {allowHeavy}`),
|
||||
//! which loading a folder doesn't ask, so folders skip it; the app runs it in the background with
|
||||
//! Cancel ([`FilterRun`]).
|
||||
//! packing or simulation). It installs only once a person agrees, which loading a folder doesn't
|
||||
//! ask, so folders skip it; the app runs it in the background with Cancel ([`FilterRun`]).
|
||||
//!
|
||||
//! A plug-in whose manifest lists permissions installs once the user grants them
|
||||
//! (`plugin.install {grant}`, recorded with the module's hash and kept in the plug-in store), and
|
||||
//! a filter does only what they allow: without `doc.read` it is given no objects, without
|
||||
//! `doc.write` an output that changes the document is refused, and without `state` it neither
|
||||
//! reads nor writes the data it keeps with the document.
|
||||
//! A plug-in whose manifest lists permissions installs once a person grants them (recorded with
|
||||
//! the module's hash and kept in the plug-in store), and a filter does only what they allow:
|
||||
//! without `doc.read` it is given no objects, without `doc.write` an output that changes the
|
||||
//! document is refused, and without `state` it neither reads nor writes the data it keeps with
|
||||
//! the document.
|
||||
//!
|
||||
//! `plugin.install {grant, allowHeavy}` takes effect only with an [`InstallApproval`], which no
|
||||
//! command can set, or in a session started to accept them from requests
|
||||
//! ([`Session::allow_plugin_grants_from_requests`]).
|
||||
//!
|
||||
//! A filter or a live effect may add menu commands of its own (its manifest's `commands`). Each
|
||||
//! is the command `plugin.<plug-in id>.<command id>` while the plug-in is installed
|
||||
@@ -41,7 +44,6 @@
|
||||
//! images or symbol instances of those kinds, to read only: its output must return each of them
|
||||
//! unchanged ([`objects::decode_output_with`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -134,9 +136,9 @@ pub struct FilterRun {
|
||||
params: Vec<u8>,
|
||||
/// The objects the plug-in is given, and the container new objects go in.
|
||||
inputs: Vec<NodeId>,
|
||||
/// The type, images and symbol instances among them (a filter that asks for them), as given:
|
||||
/// its output must return each one unchanged.
|
||||
read_only: HashMap<NodeId, Value>,
|
||||
/// The type, images and symbol instances among them (a filter that asks for them): its output
|
||||
/// must return each one as `input` gives it. These are their places in `input`.
|
||||
read_only: objects::ReadOnlySpans,
|
||||
parent: Option<NodeId>,
|
||||
/// The document it was made from, and that document's revision then.
|
||||
document: (u64, u64),
|
||||
@@ -270,7 +272,7 @@ impl FilterRun {
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output_with(output, &self.read_only).map_err(err)?;
|
||||
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
@@ -431,6 +433,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
|
||||
enabled: has_doc,
|
||||
run: unrouted,
|
||||
journal: true,
|
||||
schema: None,
|
||||
}));
|
||||
made.push(spec);
|
||||
spec
|
||||
@@ -556,6 +559,45 @@ fn grant_param(c: &str, p: &Value) -> Result<Option<Vec<Permission>>> {
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// What a person approved for one install: the module they were shown (its id, SHA-256 and the
|
||||
/// permissions it lists) and whether they agreed to its heavy budget. Only the code that asked the
|
||||
/// person sets it ([`Session::approve_plugin_install`]); no command can.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct InstallApproval {
|
||||
pub id: String,
|
||||
pub hash: String,
|
||||
pub permissions: Vec<String>,
|
||||
pub heavy: bool,
|
||||
}
|
||||
|
||||
impl InstallApproval {
|
||||
/// Is `plugin` the module this approval was given for?
|
||||
fn covers(&self, plugin: &Plugin) -> bool {
|
||||
let m = plugin.manifest();
|
||||
self.id == m.id && self.hash == plugin.hash() && self.permissions.iter().map(String::as_str).eq(permissions::names(&m.permissions()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Lets the next `plugin.install` take its `grant` and `allowHeavy`, for the module `approval`
|
||||
/// describes. Call it only with what a person approved, just before that install.
|
||||
pub fn approve_plugin_install(&mut self, approval: InstallApproval) {
|
||||
self.plugin_install_approval = Some(approval);
|
||||
}
|
||||
|
||||
/// Drops an approval that no install has spent.
|
||||
pub fn clear_plugin_install_approval(&mut self) {
|
||||
self.plugin_install_approval = None;
|
||||
}
|
||||
|
||||
/// Makes `plugin.install` accept `grant` and `allowHeavy` from any request in this session.
|
||||
/// For the person starting the process (`vectorcraft-cli --allow-plugin-grants`), never for
|
||||
/// a request.
|
||||
pub fn allow_plugin_grants_from_requests(&mut self) {
|
||||
self.plugin_grants_from_requests = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Would installing `plugin` take another module's place: one installed with its id and other
|
||||
/// bytes, or, with none installed, the settings and cache the plug-in store keeps for its id?
|
||||
fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
@@ -565,13 +607,17 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless
|
||||
/// `allowHeavy` says the user agreed, one that lists permissions the user hasn't granted this very
|
||||
/// module unless `grant` lists them all, one that would take another module's place ([`takes_over`])
|
||||
/// unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records the grant with
|
||||
/// the module's hash, keeps it for the next start and installs it → its `plugin.list` entry.
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
/// very module unless `grant` lists them all, one that would take another module's place
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records
|
||||
/// the grant with the module's hash, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
let approval = s.plugin_install_approval.take();
|
||||
let replace = match p.get("replace") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(switch_or(p, "replace", false, C)?),
|
||||
@@ -600,25 +646,38 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
),
|
||||
));
|
||||
}
|
||||
// A heavy plug-in is installed once the user agrees: whoever installs it asks them first.
|
||||
// `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that.
|
||||
let approval = approval.filter(|a| a.covers(&plugin));
|
||||
if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) {
|
||||
return Err(bad(
|
||||
C,
|
||||
"`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app",
|
||||
));
|
||||
}
|
||||
// A heavy plug-in is installed once a person agrees.
|
||||
if plugin.manifest().budget == Budget::Heavy && !allow_heavy {
|
||||
let (minutes, times) = vectorcraft_plugins::heavy_terms();
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): install it with `allowHeavy: true` once the user agrees",
|
||||
"“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants",
|
||||
plugin.manifest().name
|
||||
),
|
||||
));
|
||||
}
|
||||
// A plug-in that lists permissions installs once the user grants them: whoever installs it
|
||||
// asks them first, unless they already granted this very module all of them.
|
||||
// A plug-in that lists permissions installs once they are granted, unless a grant recorded for
|
||||
// this very module already covers all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(C, format!("“{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees")));
|
||||
return Err(bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
@@ -634,6 +693,22 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref());
|
||||
stored = false;
|
||||
}
|
||||
} else {
|
||||
// This module takes the id over, so nothing the user approved for the id applies any more.
|
||||
registry::revoke(&m.id);
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for this session. A
|
||||
// grants file that is too large or doesn't hold a list approves nothing, and the new module
|
||||
// stays; one that can't be opened or read may approve the old bytes once it reads again.
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
stored = !back;
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
@@ -844,19 +919,25 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// Its settings and cache go first: when they can't be moved aside, the plug-in stays installed,
|
||||
// as it was, and a second `plugin.remove` tries again.
|
||||
if (installed || stored)
|
||||
&& let Err(e) = s.remove_plugin_storage(id)
|
||||
{
|
||||
// Installed again, it asks again. A grant that can't be removed still approves the module, and
|
||||
// so may a grants file that can't be opened or read. One that is too large or doesn't hold a
|
||||
// list approves nothing and doesn't stop the removal.
|
||||
let forget = || s.store_grant(id, None) || !s.holds_plugin_grant(id);
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
};
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(id);
|
||||
}
|
||||
return Err(EngineError::Other(e.to_string()));
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
// Installed again, it asks again.
|
||||
registry::revoke(id);
|
||||
s.store_grant(id, None);
|
||||
s.unstore_plugin(id);
|
||||
if !stored && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
@@ -908,7 +989,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, with at most 16 MiB of pixels and 16 MiB of type runs per run (later ones come with pixelsOmitted or truncated); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
|
||||
has_doc,
|
||||
run
|
||||
),
|
||||
@@ -917,7 +998,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Install Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; with a plug-in store attached, only the grants kept there count), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -926,7 +1007,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Inspect Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted this very module, its bytes included: plugin.install then needs grant) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
@@ -935,7 +1016,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -227,6 +227,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
// Guides & Grid
|
||||
p!("guideColor", "Guides & Grid", "Guides", "Color", color),
|
||||
p!("guideStyle", "Guides & Grid", "Guides", "Style", choice(LINE_STYLE)),
|
||||
p!("lockGuidesByDefault", "Guides & Grid", "Guides", "Lock Guides by Default", bool),
|
||||
p!("gridColor", "Guides & Grid", "Grid", "Color", color),
|
||||
p!("gridStyle", "Guides & Grid", "Grid", "Style", choice(LINE_STYLE)),
|
||||
p!("gridlineEvery", "Guides & Grid", "Grid", "Gridline every", len(1.0, 16383.0, General)),
|
||||
@@ -437,6 +438,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
// The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink.
|
||||
p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool),
|
||||
p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool),
|
||||
// The bounding box and the Transform panel measure point type by its glyphs' ink (also in the Transform panel menu).
|
||||
p!("typeGlyphBounds", "Type", "Glyph Bounds", "Measure Type by Glyph Bounds", bool),
|
||||
// Artboard Options › Global: the canvas darkens the area outside the artboards while the Artboard tool is active.
|
||||
p!("fadeRegionOutsideArtboard", "General", "Artboard Options", "Fade Region Outside Artboard", bool),
|
||||
p!("artboardUpdateWhileDragging", "General", "Artboard Options", "Update While Dragging", bool),
|
||||
@@ -693,10 +696,16 @@ impl Session {
|
||||
let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder;
|
||||
let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions;
|
||||
let corner_radius_changed = p.corner_radius != self.prefs.corner_radius;
|
||||
let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default;
|
||||
if p.trace_presets != self.prefs.trace_presets {
|
||||
self.trace_preset_changes.replaced();
|
||||
}
|
||||
self.prefs = p;
|
||||
// Guides & Grid › Lock Guides by Default sets the lock when it changes, the saved value at
|
||||
// start included. Otherwise the lock stays as View › Guides › Lock Guides left it.
|
||||
if lock_guides_changed {
|
||||
self.set_guides_locked(self.prefs.lock_guides_by_default);
|
||||
}
|
||||
if corner_radius_changed {
|
||||
// General › Corner Radius is the Rounded Rectangle tool's radius (#394): a tool already
|
||||
// made (active, or lent a selection tool for a drag) takes the new value.
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
//! Edit → Spelling: the words of the document's type that its dictionaries don't know
|
||||
//! (`text.spelling.check`) and the words they suggest instead (`text.spelling.suggest`), checked
|
||||
//! by craft-proof in each run's language
|
||||
//! ([Check and correct spelling](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/check-and-correct-spelling.html)).
|
||||
//! A word is changed with `text.editRange` over the bytes the check gives. Add and Edit Custom
|
||||
//! Dictionary keep words in the custom dictionary (`text.spelling.dictionary`, `addWord`,
|
||||
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
|
||||
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
|
||||
use super::menucmds::whole_or;
|
||||
use super::typemenu::{all_texts, text_ids};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
|
||||
/// Most unknown words one check lists; past it the result says `more`.
|
||||
pub const MAX_WORDS: usize = 10_000;
|
||||
|
||||
/// Most suggestions one word gets.
|
||||
pub const MAX_SUGGESTIONS: u64 = 20;
|
||||
|
||||
/// Longest word suggestions are looked for, in bytes: the search costs more with the length.
|
||||
const MAX_WORD_LEN: usize = 128;
|
||||
|
||||
/// The Edit › Spelling commands.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "text.spelling.check",
|
||||
"Check Spelling",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.suggest",
|
||||
"Spelling Suggestions",
|
||||
[],
|
||||
None,
|
||||
"{word, max?: 1..20 (default 5), lang?: language tag (default English)} the words the dictionary of lang suggests instead of word, best first → {suggestions: [word…]}",
|
||||
has_doc,
|
||||
suggest
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.dictionary",
|
||||
"Edit Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{} the words of the custom dictionary, sorted (lower case, as they are kept) → {words: [word…]}",
|
||||
always,
|
||||
dictionary
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.addWord",
|
||||
"Add to Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word} adds word (one word, at most 64 characters; kept in lower case) to the custom dictionary, which every language's check takes as right, and saves it → {word, added: bool (false: it was there already)}",
|
||||
always,
|
||||
add_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.removeWord",
|
||||
"Delete from Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word} deletes word from the custom dictionary and saves it (an error when it isn't there) → {word}",
|
||||
always,
|
||||
remove_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.changeWord",
|
||||
"Change in Custom Dictionary",
|
||||
[],
|
||||
None,
|
||||
"{word, to} replaces word in the custom dictionary with to and saves it (an error when word isn't there) → {word: to}",
|
||||
always,
|
||||
change_word
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.ignoreAll",
|
||||
"Ignore All",
|
||||
[],
|
||||
None,
|
||||
"{word} the active document's spelling checks skip word from now on, until it closes (not saved, not undoable) → {word}",
|
||||
has_doc,
|
||||
ignore_all
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
|
||||
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.check";
|
||||
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
|
||||
// a check of the whole document.
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let mut words = vec![];
|
||||
let mut more = false;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = t.plain_text();
|
||||
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
|
||||
for m in found {
|
||||
let Some(word) = text.get(m.range.clone()) else { continue };
|
||||
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
|
||||
}
|
||||
if cut {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(json!({ "words": words, "more": more }))
|
||||
}
|
||||
|
||||
/// One word of a type object its dictionaries don't know ([`misspellings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Misspelling {
|
||||
/// The word's bytes in the object's [`TextObject::plain_text`].
|
||||
pub range: Range<usize>,
|
||||
/// The language it was checked in.
|
||||
pub lang: ProofLang,
|
||||
}
|
||||
|
||||
/// The words of `t` its dictionaries don't know, in text order: each run checked in its
|
||||
/// language, each paragraph on its own, leaving out the words in `ignored` (a document's Ignore
|
||||
/// All words). At most `max` of them; the flag says the list was cut short there. What
|
||||
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
|
||||
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
let text = t.plain_text();
|
||||
// Each run in its own language, at its bytes of the plain text.
|
||||
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
|
||||
let mut at = 0;
|
||||
for r in &t.runs {
|
||||
let end = at + r.text.len();
|
||||
spans.push((at..end, ProofLang::from_tag(r.style.language.as_deref())));
|
||||
at = end;
|
||||
}
|
||||
let opts = Options::default();
|
||||
let mut found = vec![];
|
||||
// craft-proof checks one paragraph at a time (its language detection reads the paragraph),
|
||||
// and the check stops at the paragraph where the list fills up rather than proofing the rest
|
||||
// of the text.
|
||||
let mut para_start = 0;
|
||||
for para in text.split('\n') {
|
||||
let para_end = para_start + para.len();
|
||||
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
|
||||
.iter()
|
||||
.filter_map(|(r, lang)| {
|
||||
let (a, b) = (r.start.max(para_start), r.end.min(para_end));
|
||||
(a < b).then(|| (a - para_start..b - para_start, *lang))
|
||||
})
|
||||
.collect();
|
||||
for issue in craft_proof::check_text_with(para, ¶_spans, &opts, false, false) {
|
||||
if issue.kind != IssueKind::Spelling {
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (para_start + issue.start, para_start + issue.end);
|
||||
let Some(word) = text.get(start..end) else { continue };
|
||||
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
|
||||
continue;
|
||||
}
|
||||
if found.len() == max {
|
||||
return (found, true);
|
||||
}
|
||||
found.push(Misspelling { range: start..end, lang: issue.lang });
|
||||
}
|
||||
// Past the paragraph and its `\n`.
|
||||
para_start = para_end + 1;
|
||||
}
|
||||
(found, false)
|
||||
}
|
||||
|
||||
/// Goes up each time the custom dictionary may have changed: an add, delete or change (saved or
|
||||
/// not, since a save takes in the words another window saved), and a dictionary file attached.
|
||||
static DICTIONARY_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The custom dictionary's generation: what [`misspellings`] found before it last changed may be
|
||||
/// out of date (Auto Spell Check checks the type again).
|
||||
pub fn dictionary_generation() -> u64 {
|
||||
DICTIONARY_GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn dictionary_changed() {
|
||||
DICTIONARY_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// `ids` sorted back to front, as the document paints them: by their index paths, which are in
|
||||
/// paint order.
|
||||
fn in_paint_order(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
|
||||
ids
|
||||
}
|
||||
|
||||
/// `text.spelling.suggest`: up to `max` of the words the dictionary of `lang` suggests for `word`.
|
||||
fn suggest(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.suggest";
|
||||
let word = str_param(p, "word").map(str::trim).filter(|w| !w.is_empty()).ok_or_else(|| bad(C, "missing `word`"))?;
|
||||
let max = whole_or(p, "max", 5, C)?;
|
||||
if !(1..=MAX_SUGGESTIONS).contains(&max) {
|
||||
return Err(bad(C, format!("`max` must be 1 to {MAX_SUGGESTIONS}")));
|
||||
}
|
||||
if word.len() > MAX_WORD_LEN {
|
||||
return Ok(json!({ "suggestions": [] }));
|
||||
}
|
||||
let lang = ProofLang::from_tag(str_param(p, "lang"));
|
||||
// `max` is at most MAX_SUGGESTIONS, so it fits.
|
||||
let suggestions = craft_proof::suggest_in(word, usize::try_from(max).unwrap_or(5), lang);
|
||||
Ok(json!({ "suggestions": suggestions }))
|
||||
}
|
||||
|
||||
/// `p`'s `key` as a custom-dictionary word (trimmed, lower case), or an error naming what it must be.
|
||||
fn word_param(p: &Value, key: &str, command: &str) -> Result<String> {
|
||||
let w = str_param(p, key).ok_or_else(|| bad(command, format!("missing `{key}`")))?;
|
||||
craft_proof::custom_word(w)
|
||||
.ok_or_else(|| bad(command, format!("`{key}` must be one word of at most {} characters", craft_proof::MAX_CUSTOM_WORD_CHARS)))
|
||||
}
|
||||
|
||||
/// Largest custom dictionary file taken in, in bytes: craft-proof reads no more of one (its
|
||||
/// `MAX_CUSTOM_FILE_BYTES`), so a larger file would lose its other words when written back.
|
||||
pub const MAX_DICTIONARY_FILE_BYTES: u64 = 1_000_000;
|
||||
|
||||
/// Whether the custom dictionary file at `path` can be written over without losing words: it is
|
||||
/// missing (a first save creates it), or a file that can be read whole. Otherwise why not.
|
||||
fn dictionary_file_readable(path: &std::path::Path) -> std::result::Result<(), String> {
|
||||
match std::fs::metadata(path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
Ok(m) if !m.is_file() => Err("it isn't a file".into()),
|
||||
Ok(m) if m.len() > MAX_DICTIONARY_FILE_BYTES => Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes")),
|
||||
Ok(_) => {
|
||||
// Read it whole, as craft-proof will: a file that opens but then can't be read would
|
||||
// read as no words there.
|
||||
use std::io::Read;
|
||||
let mut bytes = Vec::new();
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
file.take(MAX_DICTIONARY_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > MAX_DICTIONARY_FILE_BYTES {
|
||||
return Err(format!("it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After a failed save took a command's change back: take in the words the file holds again, so
|
||||
/// a word another window saved meanwhile, which the change had added too, stays.
|
||||
fn retake_file_words(s: &Session) {
|
||||
if let Some(path) = s.dictionary_file.as_deref().filter(|p| dictionary_file_readable(p).is_ok()) {
|
||||
craft_proof::load_user_dictionary(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the custom dictionary to its file when the session has one, leaving out `removed`. A file
|
||||
/// that is there but can't be read whole is left alone rather than written over with only the
|
||||
/// words read. On an error the caller takes its own change back, so memory and file agree.
|
||||
fn save_dictionary(s: &Session, removed: &[String], command: &str) -> Result<()> {
|
||||
let Some(path) = &s.dictionary_file else { return Ok(()) };
|
||||
if let Err(why) = dictionary_file_readable(path) {
|
||||
return Err(bad(command, format!("the custom dictionary {} can't be read ({why}), so it is left as it is", path.display())));
|
||||
}
|
||||
craft_proof::save_user_dictionary(path, removed)
|
||||
.map_err(|e| bad(command, format!("the custom dictionary couldn't be saved to {}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// `text.spelling.dictionary`: the custom dictionary's words.
|
||||
fn dictionary(_s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "words": craft_proof::user_dictionary() }))
|
||||
}
|
||||
|
||||
/// `text.spelling.addWord`: Add, and Edit Custom Dictionary's Add.
|
||||
fn add_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.addWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
let added = !craft_proof::user_dictionary().contains(&word);
|
||||
craft_proof::add_word(&word);
|
||||
let saved = save_dictionary(s, &[], C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| {
|
||||
// Only this command's word: words the save took in from the file stay.
|
||||
if added {
|
||||
craft_proof::remove_word(&word);
|
||||
retake_file_words(s);
|
||||
}
|
||||
})?;
|
||||
Ok(json!({ "word": word, "added": added }))
|
||||
}
|
||||
|
||||
/// `text.spelling.removeWord`: Edit Custom Dictionary's Delete.
|
||||
fn remove_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.removeWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
if !craft_proof::remove_word(&word) {
|
||||
return Err(bad(C, format!("`{word}` isn't in the custom dictionary")));
|
||||
}
|
||||
let saved = save_dictionary(s, std::slice::from_ref(&word), C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| craft_proof::add_word(&word))?;
|
||||
Ok(json!({ "word": word }))
|
||||
}
|
||||
|
||||
/// `text.spelling.changeWord`: Edit Custom Dictionary's Change.
|
||||
fn change_word(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.changeWord";
|
||||
let word = word_param(p, "word", C)?;
|
||||
let to = word_param(p, "to", C)?;
|
||||
if !craft_proof::user_dictionary().contains(&word) {
|
||||
return Err(bad(C, format!("`{word}` isn't in the custom dictionary")));
|
||||
}
|
||||
if word == to {
|
||||
let saved = save_dictionary(s, &[], C);
|
||||
dictionary_changed();
|
||||
saved?;
|
||||
return Ok(json!({ "word": to }));
|
||||
}
|
||||
let to_is_new = !craft_proof::user_dictionary().contains(&to);
|
||||
craft_proof::remove_word(&word);
|
||||
craft_proof::add_word(&to);
|
||||
let saved = save_dictionary(s, std::slice::from_ref(&word), C);
|
||||
dictionary_changed();
|
||||
saved.inspect_err(|_| {
|
||||
if to_is_new {
|
||||
craft_proof::remove_word(&to);
|
||||
retake_file_words(s);
|
||||
}
|
||||
craft_proof::add_word(&word);
|
||||
})?;
|
||||
Ok(json!({ "word": to }))
|
||||
}
|
||||
|
||||
/// `text.spelling.ignoreAll`: Ignore All, for the active document.
|
||||
fn ignore_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.ignoreAll";
|
||||
let word = word_param(p, "word", C)?;
|
||||
// Not a change to the document, so its revision stays: a tool edit computed meanwhile still
|
||||
// applies (`command_sweep`'s check of commands that don't wait for one).
|
||||
s.doc_mut()?.spelling_ignored.insert(word.clone());
|
||||
Ok(json!({ "word": word }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Keep the custom dictionary in the file at `path` (the desktop app's, beside its
|
||||
/// preferences), and take in the words already there. A missing file reads as no words and is
|
||||
/// created by the first save. A file that is there but can't be read whole is logged and left
|
||||
/// as it is: changes to the dictionary are refused rather than written over it.
|
||||
pub fn attach_custom_dictionary(&mut self, path: std::path::PathBuf) {
|
||||
match dictionary_file_readable(&path) {
|
||||
Ok(()) => {
|
||||
craft_proof::load_user_dictionary(&path);
|
||||
}
|
||||
Err(why) => log::warn!("not reading the custom dictionary {}: {why}; it is left as it is", path.display()),
|
||||
}
|
||||
self.dictionary_file = Some(path);
|
||||
dictionary_changed();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! of symbols the library panel shows. A library is a document holding the symbols with the
|
||||
//! resources they use (nested symbols, patterns, swatches, brushes, graphic styles, images) and
|
||||
//! their Symbol Options; saved, it is a native `.vectorcraft` file, which File › Open also opens.
|
||||
//! The built-in library is generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft`
|
||||
//! The built-in libraries are generated here ([`BUILTIN`]); User Defined ones are the `.vectorcraft`
|
||||
//! files in the user library folder ([`Libraries`]), and Other Library… loads the symbols of any
|
||||
//! document VectorCraft opens. `symbol.addFromLibrary` copies symbols into the document;
|
||||
//! `symbol.saveLibrary` writes the document's.
|
||||
@@ -12,7 +12,7 @@ use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
|
||||
use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size};
|
||||
@@ -154,7 +154,10 @@ pub struct BuiltinSymbolLibrary {
|
||||
}
|
||||
|
||||
/// The built-in symbol libraries, in menu order: original art generated in code.
|
||||
pub const BUILTIN: &[BuiltinSymbolLibrary] = &[BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes }];
|
||||
pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
|
||||
BuiltinSymbolLibrary { id: "basic-shapes", name: "Basic Shapes", make: basic_shapes },
|
||||
BuiltinSymbolLibrary { id: "ui-frames", name: "UI Frames", make: ui_frames },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
fn builtin_library(id: &str) -> Option<Arc<SymbolLibrary>> {
|
||||
@@ -194,6 +197,30 @@ fn basic_shapes() -> SymbolLibrary {
|
||||
SymbolLibrary { name: "Basic Shapes".into(), doc }
|
||||
}
|
||||
|
||||
/// UI Frames: panel, button and bar HUD chrome with default 9-slice guides (original art).
|
||||
fn ui_frames() -> SymbolLibrary {
|
||||
// Heights keep default 9-slice (0.25) past each corner radius so a vertical resize
|
||||
// stretches only the flat middle, not the curves.
|
||||
let frames = [
|
||||
("Panel", Rect::new(-48.0, -36.0, 48.0, 36.0), 10.0, "#2b3340", "#8aa0b8"),
|
||||
("Button", Rect::new(-36.0, -18.0, 36.0, 18.0), 8.0, "#3a6ea5", "#d7e6f5"),
|
||||
("Bar", Rect::new(-56.0, -24.0, 56.0, 24.0), 10.0, "#1f6b4a", "#b7e0c9"),
|
||||
];
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (name, rect, radius, fill_hex, edge_hex) in frames {
|
||||
let fill = Color::from_hex(fill_hex).unwrap_or(Color::BLACK);
|
||||
let edge = Color::from_hex(edge_hex).unwrap_or(Color::BLACK);
|
||||
let id = doc.alloc_id();
|
||||
let art = Node::path(id, shapes::rounded_rectangle(rect, radius), Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.5));
|
||||
let Ok((art, size, _)) = normalize(art) else { continue };
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
set_natural_size(&mut doc, name, Some(size));
|
||||
doc.set_symbol_nine_slice(name, Some(SymbolNineSlice::default()));
|
||||
}
|
||||
doc.title = "UI Frames".into();
|
||||
SymbolLibrary { name: "UI Frames".into(), doc }
|
||||
}
|
||||
|
||||
/// An instance of symbol `name` (what the resource gathering follows).
|
||||
fn instance(name: &str) -> Node {
|
||||
Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })
|
||||
|
||||
@@ -1611,6 +1611,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
cached_ink: None,
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
@@ -1901,6 +1902,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
cached_ink: None,
|
||||
};
|
||||
for r in &mut h.runs {
|
||||
r.style.tracking = tr;
|
||||
|
||||
@@ -48,7 +48,7 @@ impl Kind {
|
||||
|
||||
/// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`).
|
||||
const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec {
|
||||
CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal }
|
||||
CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None }
|
||||
}
|
||||
|
||||
macro_rules! style_cmds {
|
||||
|
||||
@@ -304,6 +304,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
|
||||
}
|
||||
|
||||
/// [`refresh_bounds`] for a document that is opening: the first frame takes the layout
|
||||
@@ -315,6 +316,7 @@ pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t)));
|
||||
vectorcraft_text::keep_layout(t, stamp, lay);
|
||||
}
|
||||
|
||||
|
||||
@@ -718,7 +718,9 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool,
|
||||
|
||||
/// The text objects Find and Replace and Find Next reach: on visible, unlocked layers, and not
|
||||
/// inside a hidden or locked group, which hides or locks what it holds as a layer does (#5900).
|
||||
fn all_texts(d: &Document) -> Vec<NodeId> {
|
||||
/// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint
|
||||
/// order: the text Find and Replace and Check Spelling go through.
|
||||
pub(crate) fn all_texts(d: &Document) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec<NodeId>) {
|
||||
if !n.visible || n.locked {
|
||||
return;
|
||||
|
||||
@@ -2,33 +2,106 @@
|
||||
//! toggles (Show Transparency Grid); the Character panel's Snap to Glyph options.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_apischema::{Bound, Param, ParamSchema, Type, Writes};
|
||||
use vectorcraft_doc::SavedView;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_req, finite_numbers, has_doc, str_param, switch_or};
|
||||
|
||||
// The parameter schemas. Each command's params text is the text its schema writes
|
||||
// (`ParamSchema::params_text`), which a test in `crate::schemas` checks.
|
||||
|
||||
static CAPS_LOCK: ParamSchema = ParamSchema::new(
|
||||
&[Param::new("on", Type::Boolean).optional()],
|
||||
"set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value",
|
||||
)
|
||||
.returns("{on}")
|
||||
.writes(Writes::Session);
|
||||
|
||||
static NEW_VIEW: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("name", Type::String).default_note("the first free \"View N\"").null_omitted(),
|
||||
Param::new("center", Type::Point),
|
||||
Param::new("zoom", Type::Number { min: Some(Bound::Exclusive(0.0)), max: None, unit: None }).doc("1 = 100%"),
|
||||
Param::new("rotation", Type::Number { min: None, max: None, unit: Some("deg") }).defaults_to("0"),
|
||||
],
|
||||
"save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once)",
|
||||
)
|
||||
.returns("{name, index}");
|
||||
|
||||
/// One rename or delete of Edit Views….
|
||||
const VIEW_EDIT: &[Param] = &[
|
||||
Param::new("name", Type::String),
|
||||
Param::new("newName", Type::String).optional().null_omitted(),
|
||||
Param::new("delete", Type::Boolean).optional().null_omitted(),
|
||||
];
|
||||
|
||||
static EDIT_VIEWS: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("name", Type::String).optional().null_omitted(),
|
||||
Param::new("newName", Type::String).optional().null_omitted().doc("rename"),
|
||||
Param::new("delete", Type::Boolean).optional().null_omitted(),
|
||||
Param::new("edits", Type::Array(&Type::Object(VIEW_EDIT))).optional().null_omitted().doc("instead of name"),
|
||||
],
|
||||
"rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
);
|
||||
|
||||
static LIST_VIEWS: ParamSchema = ParamSchema::new(&[], "").returns("{views: [{name, center, zoom, rotation}]}").writes(Writes::Nothing);
|
||||
|
||||
static TRANSPARENCY_GRID: ParamSchema = ParamSchema::new(
|
||||
&[Param::new("on", Type::Boolean).default_note("toggle").null_omitted()],
|
||||
"show the transparency grid behind the active document's artboards (each document has its own setting)",
|
||||
)
|
||||
.returns("{on}")
|
||||
.writes(Writes::Session);
|
||||
|
||||
static GLYPH_SNAP: ParamSchema = ParamSchema::new(
|
||||
&[
|
||||
Param::new("baseline", Type::Boolean).optional(),
|
||||
Param::new("xHeight", Type::Boolean).optional(),
|
||||
Param::new("bounds", Type::Boolean).optional(),
|
||||
Param::new("proximity", Type::Boolean).optional(),
|
||||
Param::new("angular", Type::Boolean).optional(),
|
||||
Param::new("anchors", Type::Boolean).optional(),
|
||||
],
|
||||
"the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them",
|
||||
)
|
||||
.returns("the options")
|
||||
.writes(Writes::Preferences);
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "view.capsLock", "Caps Lock Cursor State", [], None, "{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}", always, caps_lock),
|
||||
cmd!(
|
||||
query "view.capsLock",
|
||||
"Caps Lock Cursor State",
|
||||
[],
|
||||
None,
|
||||
"{on?: bool} set or read the Caps Lock state the desktop app reports; while it is on, the drawing tools show the precise crosshair, and Use Precise Cursors keeps its saved value → {on}",
|
||||
always,
|
||||
caps_lock,
|
||||
schema: &CAPS_LOCK
|
||||
),
|
||||
cmd!(
|
||||
"view.saved.new",
|
||||
"New View…",
|
||||
["View"],
|
||||
None,
|
||||
"{name?, center: [x, y], zoom: (1 = 100%), rotation?: deg} save a view in the document (the app fills in the current one; default \"View N\"; at most 25, names up to 255 characters, each name once) → {name, index}",
|
||||
"{name?: string (default: the first free \"View N\"), center: [x, y], zoom: number > 0 (1 = 100%), rotation?: number deg (default: 0)} save a view in the document (the app fills in the current one; at most 25, names up to 255 characters, each name once) → {name, index}",
|
||||
has_doc,
|
||||
new_view
|
||||
new_view,
|
||||
schema: &NEW_VIEW
|
||||
),
|
||||
cmd!(
|
||||
"view.saved.edit",
|
||||
"Edit Views…",
|
||||
["View"],
|
||||
None,
|
||||
"{name, newName?: rename, delete?: bool} | {edits: [{name, newName?, delete?}…]} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
"{name?: string, newName?: string (rename), delete?: bool, edits?: [{name: string, newName?: string, delete?: bool}…] (instead of name)} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
has_views,
|
||||
edit_views
|
||||
edit_views,
|
||||
schema: &EDIT_VIEWS
|
||||
),
|
||||
cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views),
|
||||
cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views, schema: &LIST_VIEWS),
|
||||
cmd!(
|
||||
query "view.transparencyGrid",
|
||||
"Show Transparency Grid",
|
||||
@@ -36,16 +109,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("Cmd+Shift+D"),
|
||||
"{on?: bool (default: toggle)} show the transparency grid behind the active document's artboards (each document has its own setting) → {on}",
|
||||
has_doc,
|
||||
transparency_grid
|
||||
transparency_grid,
|
||||
schema: &TRANSPARENCY_GRID
|
||||
),
|
||||
cmd!(
|
||||
query "view.snapToGlyph.options",
|
||||
"Snap to Glyph Options",
|
||||
[],
|
||||
None,
|
||||
"{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives — the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options",
|
||||
"{baseline?: bool, xHeight?: bool, bounds?: bool, proximity?: bool, angular?: bool, anchors?: bool} the Character panel's Snap to Glyph options, kept in the preferences (the glyphSnap group, all on by default): which guides View › Snap to Glyph gives: the baseline and x-height of a single line of type, Glyph Bounds (each glyph's edges), Proximity Guides (both edges of each character's width), Angular Guides (a glyph's slanted strokes, and every guide of rotated type) and the glyphs' anchor points; {} reads them → the options",
|
||||
always,
|
||||
glyph_snap_options
|
||||
glyph_snap_options,
|
||||
schema: &GLYPH_SNAP
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -280,6 +355,92 @@ mod tests {
|
||||
assert_eq!(s.execute("view.saved.new", &json!({"name": long, "center": [0, 0], "zoom": 1})).unwrap()["name"], "x".repeat(255));
|
||||
}
|
||||
|
||||
/// Each command refuses a value its schema doesn't take with an error naming the parameter, and
|
||||
/// leaves the document, its views, its undo history and the settings as they were.
|
||||
#[test]
|
||||
fn each_view_command_refuses_a_bad_value_naming_the_parameter() {
|
||||
let mut s = session_with_views(&["A"]);
|
||||
for (id, params, named) in [
|
||||
("view.capsLock", json!({"on": "yes"}), "`on`"),
|
||||
("view.capsLock", json!({"of": true}), "`of`"),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 0}), "`zoom`"),
|
||||
("view.saved.new", json!({"center": [0, "0"], "zoom": 1}), "`center`"),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": "15"}), "`rotation`"),
|
||||
("view.saved.new", json!({"name": 5, "center": [0, 0], "zoom": 1}), "`name`"),
|
||||
("view.saved.new", json!({"zoom": 1}), "`center`"),
|
||||
("view.saved.edit", json!({"name": "A", "delete": "yes"}), "`delete`"),
|
||||
("view.saved.edit", json!({"name": "A", "newName": 7}), "`newName`"),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]}), "`edits[0].delete`"),
|
||||
("view.saved.edit", json!({"edits": [{"newName": "B"}]}), "`edits[0].name`"),
|
||||
("view.saved.edit", json!({"edits": "A"}), "`edits`"),
|
||||
("view.saved.list", json!({"all": true}), "`all`"),
|
||||
("view.transparencyGrid", json!({"on": 1}), "`on`"),
|
||||
("view.snapToGlyph.options", json!({"bounds": "off"}), "`bounds`"),
|
||||
] {
|
||||
let st = s.doc().unwrap();
|
||||
let doc = (st.doc.views.clone(), st.history.undo.len(), st.is_dirty());
|
||||
let (grid, caps, snap) = (st.transparency_grid, s.caps_lock, s.prefs.glyph_snap);
|
||||
let e = s.execute(id, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(id) && e.contains(named), "{id} {params}: {e}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!((&st.doc.views, st.history.undo.len(), st.is_dirty()), (&doc.0, doc.1, doc.2), "{id} {params}");
|
||||
assert_eq!((st.transparency_grid, s.caps_lock, s.prefs.glyph_snap), (grid, caps, snap), "{id} {params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command run by another command's implementation has its params checked against its schema
|
||||
/// too, with nothing changed when they are refused.
|
||||
#[test]
|
||||
fn a_raw_run_is_checked_against_the_schema() {
|
||||
let mut s = session_with_views(&[]);
|
||||
let e = super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
super::super::menucmds::run_raw(&mut s, "view.saved.new", &json!({"center": [0, 0], "zoom": 1})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views.len(), 1);
|
||||
}
|
||||
|
||||
/// An edit list with nothing in it and an edit that leaves a view as it is add no undo step;
|
||||
/// names with path characters are only names; a key with one is refused and named.
|
||||
#[test]
|
||||
fn edit_views_edges() {
|
||||
let mut s = session_with_views(&["a.b[0]", "plain"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("view.saved.edit", &json!({"edits": []})).unwrap()["views"].as_array().map(Vec::len), Some(2));
|
||||
s.execute("view.saved.edit", &json!({"name": "plain", "newName": "plain"})).unwrap();
|
||||
s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "plain"}]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
s.execute("view.saved.edit", &json!({"name": "a.b[0]", "newName": "c[1].d"})).unwrap();
|
||||
assert_eq!(names(&mut s), ["c[1].d", "plain"]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let e = s.execute("view.saved.edit", &json!({"a.b": 1})).unwrap_err().to_string();
|
||||
assert!(e.contains("`a.b`"), "{e}");
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "a.b": 1}]})).unwrap_err().to_string();
|
||||
assert!(e.contains("`edits[0].a.b`; it takes: name, newName, delete"), "{e}");
|
||||
// Repeated and unknown names keep the command's own errors.
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "plain", "newName": "c[1].d"}]})).unwrap_err().to_string();
|
||||
assert!(e.contains("exists"), "{e}");
|
||||
let e = s.execute("view.saved.edit", &json!({"name": "", "delete": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("no view named"), "{e}");
|
||||
}
|
||||
|
||||
/// A refused call during a drag leaves the drag running and adds no undo step; canceling the
|
||||
/// drag then leaves the history as it was.
|
||||
#[test]
|
||||
fn a_refused_call_leaves_an_interaction_alone() {
|
||||
let mut s = session_with_views(&["A"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.begin_interaction("Move").unwrap();
|
||||
assert!(s.execute("view.saved.new", &json!({"name": 5, "center": [0, 0], "zoom": 1})).is_err());
|
||||
assert!(s.doc().unwrap().interaction.is_some());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
s.cancel_interaction().unwrap();
|
||||
assert!(s.doc().unwrap().interaction.is_none());
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
assert_eq!(names(&mut s), ["A"]);
|
||||
}
|
||||
|
||||
/// Edit Views… is off until the document has a view.
|
||||
#[test]
|
||||
fn edit_views_needs_a_saved_view() {
|
||||
|
||||
@@ -368,7 +368,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
q["ids"] = ids.clone();
|
||||
}
|
||||
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
let result = (spec.run)(s, &q)?;
|
||||
let result = super::run_checked(s, spec, &q)?;
|
||||
if clear_stroke {
|
||||
s.paint.stroke = Paint::None;
|
||||
}
|
||||
|
||||
@@ -58,6 +58,9 @@ pub struct DocState {
|
||||
/// View Opacity Mask (Alt-click the mask thumbnail): the masked object whose mask the canvas
|
||||
/// shows alone, in greyscale, while that mask is edited (see [`DocState::shown_mask`]).
|
||||
pub mask_view: Option<NodeId>,
|
||||
/// Check Spelling's Ignore All: the words (as craft-proof keys them, lower case) a spelling
|
||||
/// check of this document skips. Kept while the document is open: not saved, not undoable.
|
||||
pub spelling_ignored: std::collections::BTreeSet<String>,
|
||||
/// View → Show Transparency Grid, per document (saved view state, not undoable).
|
||||
pub transparency_grid: bool,
|
||||
/// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened
|
||||
@@ -109,6 +112,8 @@ pub struct DocState {
|
||||
pub opened_by: Option<Arc<file_access::AutomationRoots>>,
|
||||
/// What [`DocState::any_empty_artboards`] last measured. Not saved.
|
||||
empty_artboards: std::cell::RefCell<EmptyArtboards>,
|
||||
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
|
||||
art_to_fit: std::cell::RefCell<Option<ArtToFit>>,
|
||||
}
|
||||
|
||||
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
|
||||
@@ -121,10 +126,25 @@ struct EmptyArtboards {
|
||||
any: bool,
|
||||
}
|
||||
|
||||
/// Whether an unlocked artboard of those asked about has art that Fit to Artwork Bounds fits it
|
||||
/// to, with what was measured: the document (held as [`EmptyArtboards::doc`] holds it), the
|
||||
/// artboards, and the generations of what the measure reads outside the document. One is kept for
|
||||
/// each open document, and its weak reference keeps the measured document's allocation (not its
|
||||
/// contents) until the next measure or until the document closes.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ArtToFit {
|
||||
doc: std::sync::Weak<Document>,
|
||||
indices: Vec<usize>,
|
||||
outside: (u64, u64),
|
||||
any: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many times [`DocState::any_empty_artboards`] measured a document on this thread.
|
||||
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
|
||||
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
@@ -288,6 +308,7 @@ impl DocState {
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
opened_as_tab: true,
|
||||
mask_view: None,
|
||||
spelling_ignored: Default::default(),
|
||||
transparency_grid,
|
||||
format: "vectorcraft",
|
||||
save_options: Default::default(),
|
||||
@@ -305,6 +326,7 @@ impl DocState {
|
||||
last_perspective: None,
|
||||
opened_by: file_access::current(),
|
||||
empty_artboards: Default::default(),
|
||||
art_to_fit: Default::default(),
|
||||
}
|
||||
}
|
||||
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
|
||||
@@ -319,6 +341,38 @@ impl DocState {
|
||||
}
|
||||
last.any
|
||||
}
|
||||
/// Whether an unlocked artboard of `indices` has art that Fit to Artwork Bounds fits it to. A
|
||||
/// menu asks on every frame it is open, and measuring builds the solids of 3D effects, so the
|
||||
/// answer is kept for this version of the document and those artboards, and a change of the
|
||||
/// selection or the view keeps it. It is measured again when what the measure reads outside the
|
||||
/// document changes: the installed plug-ins, whose effects draw art, and the installed fonts,
|
||||
/// which set the bounds of all type.
|
||||
pub fn any_art_to_fit(&self, indices: &[usize]) -> bool {
|
||||
self.any_art_to_fit_with(indices, (vectorcraft_plugins::registry::revision(), vectorcraft_text::FontDb::global().generation()))
|
||||
}
|
||||
/// [`Self::any_art_to_fit`], with `outside` the generations of the plug-ins and the fonts.
|
||||
pub(crate) fn any_art_to_fit_with(&self, indices: &[usize], outside: (u64, u64)) -> bool {
|
||||
// Measuring runs renderer and plug-in code; should it ever ask again while measuring, it
|
||||
// is measured without being kept rather than borrowed twice.
|
||||
let Ok(mut last) = self.art_to_fit.try_borrow_mut() else {
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
return indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some());
|
||||
};
|
||||
if let Some(k) = last.as_ref()
|
||||
&& std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc))
|
||||
&& k.indices == indices
|
||||
&& k.outside == outside
|
||||
{
|
||||
return k.any;
|
||||
}
|
||||
#[cfg(test)]
|
||||
ART_TO_FIT_MEASURES.with(|c| c.set(c.get() + 1));
|
||||
// One renderer measures every artboard: each object once.
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
let any = indices.iter().filter_map(|i| self.doc.artboards.get(*i)).any(|a| !a.locked && r.art_bounds_on(&self.doc, a.rect).is_some());
|
||||
*last = Some(ArtToFit { doc: Arc::downgrade(&self.doc), indices: indices.to_vec(), outside, any });
|
||||
any
|
||||
}
|
||||
/// Unsaved changes: the document differs from the saved one (selection changes and changes that
|
||||
/// are not edits to save don't count, [`DocState::same_content`]).
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod guard;
|
||||
pub mod inspect;
|
||||
pub mod journal;
|
||||
pub mod link_watch;
|
||||
pub mod schemas;
|
||||
pub mod steps;
|
||||
pub mod store;
|
||||
mod tooling;
|
||||
@@ -148,15 +149,28 @@ pub struct Session {
|
||||
/// Where the saved PDF presets are kept, one file each; `None`: only for the session
|
||||
/// ([`Session::attach_pdf_preset_store`]).
|
||||
pdf_preset_dir: Option<std::path::PathBuf>,
|
||||
/// The custom dictionary file Edit › Spelling › Add and Edit Custom Dictionary save to; `None`:
|
||||
/// the words are kept only for the process ([`Session::attach_custom_dictionary`]).
|
||||
dictionary_file: Option<std::path::PathBuf>,
|
||||
/// Where the ICC profiles `color.loadProfile` loads are kept; `None`: only for the process
|
||||
/// ([`Session::attach_profile_store`]).
|
||||
profile_dir: Option<std::path::PathBuf>,
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
|
||||
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
|
||||
/// [`Session::store_grant`] for the id takes it out.
|
||||
ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>,
|
||||
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
|
||||
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
|
||||
plugin_output: Option<cmd::plugin::HandedIn>,
|
||||
/// What a person approved for the next `plugin.install` ([`Session::approve_plugin_install`]);
|
||||
/// that install spends it, whatever it does.
|
||||
plugin_install_approval: Option<cmd::plugin::InstallApproval>,
|
||||
/// `plugin.install` takes `grant` and `allowHeavy` from any request
|
||||
/// ([`Session::allow_plugin_grants_from_requests`]).
|
||||
plugin_grants_from_requests: bool,
|
||||
/// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved.
|
||||
pub recent_urls: Vec<String>,
|
||||
/// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]).
|
||||
|
||||
@@ -41,6 +41,12 @@ pub struct Prefs {
|
||||
/// Align panel menu › Align to Glyph Bounds › Area Text: the same for area type, instead of
|
||||
/// its frame.
|
||||
pub align_glyph_bounds_area: bool,
|
||||
/// Preferences › Type › Glyph Bounds › Measure Type by Glyph Bounds (also in the Transform
|
||||
/// panel menu): the bounding box, the Transform panel's, Control bar's and Properties panel's X,
|
||||
/// Y, W and H, and `object.setBounds` measure each point type object selected as an object (not
|
||||
/// inside a selected group) by the ink of its glyphs instead of its em box
|
||||
/// ([`crate::Session::bounds_measure`]).
|
||||
pub type_glyph_bounds: bool,
|
||||
/// Artboard Options › Fade Region Outside Artboard: while the Artboard tool is active, the
|
||||
/// canvas draws everything outside the artboards darker, the pasteboard and the art on it.
|
||||
pub fade_region_outside_artboard: bool,
|
||||
@@ -114,6 +120,8 @@ pub struct Prefs {
|
||||
// Guides & Grid
|
||||
pub guide_color: String,
|
||||
pub guide_style: String,
|
||||
/// Lock Guides by Default: the app starts with View › Guides › Lock Guides on.
|
||||
pub lock_guides_by_default: bool,
|
||||
pub grid_color: String,
|
||||
pub grid_style: String,
|
||||
pub gridline_every: f64,
|
||||
@@ -370,6 +378,7 @@ impl Default for Prefs {
|
||||
use_preview_bounds: false,
|
||||
align_glyph_bounds_point: false,
|
||||
align_glyph_bounds_area: false,
|
||||
type_glyph_bounds: false,
|
||||
fade_region_outside_artboard: true,
|
||||
artboard_update_while_dragging: true,
|
||||
display_print_size: false,
|
||||
@@ -421,6 +430,7 @@ impl Default for Prefs {
|
||||
identify_objects_by: s("objectName"),
|
||||
guide_color: s("#4affff"),
|
||||
guide_style: s("lines"),
|
||||
lock_guides_by_default: false,
|
||||
grid_color: s("#c8c8c8"),
|
||||
grid_style: s("lines"),
|
||||
gridline_every: 72.0,
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
//! The commands' parameter schemas ([`vectorcraft_apischema::ParamSchema`]) and the API level they
|
||||
//! belong to.
|
||||
//!
|
||||
//! A command with a schema (`CommandSpec::schema`) has its params checked against it by
|
||||
//! [`crate::Session::execute`] before it runs ([`check`]), and by the steps that run a command's
|
||||
//! implementation directly ([`crate::cmd::run_checked`]): a value of the wrong type, out of range
|
||||
//! or not in its list, a missing required parameter or an unknown key is refused with a parameter
|
||||
//! error naming the parameter, and the command does not run, so the document and its undo history
|
||||
//! stay as they were. An omitted value with a default takes it. The steps of a `command.batch` or
|
||||
//! an `action.batch` are checked before the first one runs. Saved steps
|
||||
//! ([`crate::Session::replay`]) keep their keys a schema doesn't name, and their values are checked.
|
||||
//! The command's `params` text is the text its schema writes, and `engine.commands` lists the schema
|
||||
//! of each command that has one.
|
||||
//!
|
||||
//! [`API_VERSION`] goes up by one whenever a schema of a built-in command changes, and
|
||||
//! [`SCHEMA_HASHES`] gains a row with the new level and [`schema_hash`]: a test fails while the
|
||||
//! newest row does not match the schemas. Commands that plug-ins add have no schema.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_apischema::{ParamError, Problem};
|
||||
|
||||
use crate::cmd::params::unknown;
|
||||
use crate::cmd::{CommandSpec, bad, command_specs};
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// The API level of the commands' parameters.
|
||||
pub const API_VERSION: u32 = 2;
|
||||
|
||||
/// [`schema_hash`] at each API level, oldest first; the last row is [`API_VERSION`]'s.
|
||||
pub const SCHEMA_HASHES: &[(u32, u64)] = &[(1, 0x9cdb_1087_7074_855c), (2, 0x0e31_5d96_7bc9_2653)];
|
||||
|
||||
/// The hash of every built-in command's schema ([`vectorcraft_apischema::hash`]).
|
||||
pub fn schema_hash() -> u64 {
|
||||
vectorcraft_apischema::hash(command_specs().iter().filter_map(|c| Some((c.id, c.schema?))))
|
||||
}
|
||||
|
||||
/// Each built-in schema that is wrong in itself, with why ([`vectorcraft_apischema::ParamSchema::definition_problem`]).
|
||||
/// Worked out once, the first time a command with a schema runs.
|
||||
fn definition_problems() -> &'static [(&'static str, String)] {
|
||||
static PROBLEMS: OnceLock<Vec<(&'static str, String)>> = OnceLock::new();
|
||||
PROBLEMS.get_or_init(|| command_specs().iter().filter_map(|c| Some((c.id, c.schema?.definition_problem()?))).collect())
|
||||
}
|
||||
|
||||
/// `params` checked against the schema of `spec`: a parameter error under the command's id for the
|
||||
/// first problem, or the params with the defaults of omitted values filled in (`None` when the
|
||||
/// command has no schema or nothing was filled in, so `params` is used as it is). A command with no
|
||||
/// schema costs one branch. `saved`: the params of a saved step, whose keys the schema doesn't name
|
||||
/// pass. A schema that is wrong in itself is an internal error, and its command does not run.
|
||||
pub(crate) fn check(spec: &CommandSpec, params: &Value, saved: bool) -> Result<Option<Value>> {
|
||||
let Some(schema) = spec.schema else { return Ok(None) };
|
||||
if let Some((_, why)) = definition_problems().iter().find(|(id, _)| *id == spec.id) {
|
||||
return Err(EngineError::Internal { cmd: spec.id.into(), msg: why.clone() });
|
||||
}
|
||||
let checked = if saved { schema.validate_saved(params) } else { schema.validate(params) };
|
||||
checked.map_err(|e| param_error(spec.id, &e))
|
||||
}
|
||||
|
||||
/// The parameter error of command `id` for `e`, in the words the message catalogs translate. An
|
||||
/// unknown top-level key is reported as the commands without a schema report it, with the nearest
|
||||
/// key.
|
||||
fn param_error(id: &str, e: &ParamError) -> EngineError {
|
||||
let path = &e.path;
|
||||
match &e.problem {
|
||||
Problem::NotAnObject { got } => bad(id, format!("the params must be an object, not {got}")),
|
||||
Problem::Unknown { keys } if !path.contains(['.', '[']) => unknown(id, path, keys),
|
||||
Problem::Unknown { keys } if keys.is_empty() => bad(id, format!("unknown parameter `{path}`; the object takes no keys")),
|
||||
Problem::Unknown { keys } => bad(id, format!("unknown parameter `{path}`; it takes: {keys}", keys = keys.join(", "))),
|
||||
Problem::Missing => bad(id, format!("missing `{path}`")),
|
||||
Problem::WrongType { expected, got } => bad(id, format!("`{path}` must be {expected}, not {got}")),
|
||||
Problem::TooDeep => EngineError::Internal { cmd: id.into(), msg: e.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../../apischema/src/conformance.rs"]
|
||||
mod conformance;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use proptest::prelude::*;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_apischema::{Bound, Omitted, Param, ParamSchema, Type};
|
||||
|
||||
use super::conformance::{check_schema, instance_valid};
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
fn schemas() -> Vec<(&'static str, &'static ParamSchema)> {
|
||||
command_specs().iter().filter_map(|c| Some((c.id, c.schema?))).collect()
|
||||
}
|
||||
|
||||
/// The params text of a command with a schema is the text the schema writes.
|
||||
#[test]
|
||||
fn params_text_is_the_text_the_schema_writes() {
|
||||
assert!(!schemas().is_empty());
|
||||
for c in command_specs() {
|
||||
if let Some(schema) = c.schema {
|
||||
assert_eq!(c.params, schema.params_text(), "{}", c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A schema changed without a new API level (and a new row of hashes) fails here: add the row
|
||||
/// `(API_VERSION + 1, <the hash below>)` and raise [`API_VERSION`].
|
||||
#[test]
|
||||
fn schema_hash_matches_the_api_version() {
|
||||
let last = SCHEMA_HASHES.last().copied();
|
||||
assert_eq!(last.map(|(level, _)| level), Some(API_VERSION), "the last row of SCHEMA_HASHES is not API_VERSION's");
|
||||
assert_eq!(last.map(|(_, hash)| hash), Some(schema_hash()), "the schemas changed: {:#x}", schema_hash());
|
||||
assert!(SCHEMA_HASHES.windows(2).all(|w| w[0].0 < w[1].0), "the API levels go up");
|
||||
}
|
||||
|
||||
/// Every schema is sound in itself ([`ParamSchema::definition_problem`]), so no command is
|
||||
/// refused for its schema, and no parameter or command is newer than the API level.
|
||||
#[test]
|
||||
fn schemas_are_sound_and_levels_are_known() {
|
||||
fn walk(id: &str, params: &[Param]) {
|
||||
for p in params {
|
||||
assert!(p.since >= 1 && p.since <= API_VERSION, "{id}.{}", p.name);
|
||||
if let Type::Object(inner) | Type::Array(&Type::Object(inner)) = p.ty {
|
||||
walk(id, inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(definition_problems(), &[]);
|
||||
for (id, schema) in schemas() {
|
||||
assert!(schema.since >= 1 && schema.since <= API_VERSION, "{id}");
|
||||
walk(id, schema.params);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each command's defaults are of its parameter's type (an omitted value takes them), with
|
||||
/// which ones are filled in.
|
||||
#[test]
|
||||
fn declared_defaults_are_filled_in() {
|
||||
let new_view = command_specs().iter().find(|c| c.id == "view.saved.new").and_then(|c| c.schema).unwrap();
|
||||
let filled = new_view.validate(&json!({"center": [1, 2], "zoom": 1})).unwrap().unwrap();
|
||||
assert_eq!(filled["rotation"], json!(0));
|
||||
assert!(filled.get("name").is_none(), "the command works out the name");
|
||||
assert!(new_view.param("rotation").is_some_and(|p| matches!(p.omitted, Omitted::Value("0"))));
|
||||
}
|
||||
|
||||
/// A refusal from the schema names the parameter, and the command does not run.
|
||||
#[test]
|
||||
fn a_refused_value_names_the_parameter_under_the_command() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("`zoom` must be a number > 0, not -1"), "{e}");
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 1, "rotaton": 5})).unwrap_err().to_string();
|
||||
assert!(e.contains("unknown parameter `rotaton`; did you mean `rotation`?"), "{e}");
|
||||
let e = s.execute("view.saved.new", &Value::Null).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains("missing `center`"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
/// The key check runs before the schema, so a misspelled key is the error even when a value is
|
||||
/// bad too, and the schema reports the value when the keys are right.
|
||||
#[test]
|
||||
fn a_misspelled_key_is_reported_before_a_bad_value() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": -1, "rotaton": 5})).unwrap_err().to_string();
|
||||
assert!(e.contains("did you mean `rotation`?"), "{e}");
|
||||
let e = s.execute("view.saved.new", &json!({"center": "here", "zoom": -1})).unwrap_err().to_string();
|
||||
assert!(e.contains("`center` must be [x, y] (two numbers), not \"here\""), "{e}");
|
||||
}
|
||||
|
||||
/// Saved steps keep a retired key, at the top level and inside `edits`, and a bad value is
|
||||
/// still refused, with no undo step; the journal keeps the params as given.
|
||||
#[test]
|
||||
fn saved_steps_keep_retired_keys_and_check_values() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let retired = json!({"name": "A", "center": [1, 2], "zoom": 2, "fitArt": true});
|
||||
assert!(s.execute("view.saved.new", &retired).is_err());
|
||||
s.replay("view.saved.new", &retired).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views[0].name, "A");
|
||||
let last = s.journal.last().unwrap();
|
||||
assert_eq!(last.1, retired, "the journal has the params as given, with no default filled in");
|
||||
s.replay("view.saved.edit", &json!({"edits": [{"name": "A", "newName": "B", "was": 1}]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.views[0].name, "B");
|
||||
assert!(s.execute("view.saved.edit", &json!({"edits": [{"name": "B", "newName": "C", "was": 1}]})).is_err());
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.replay("view.saved.new", &json!({"center": [1, 2], "zoom": 0, "fitArt": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// A frontend that replays through its own path sets the flag, and gets the same rule.
|
||||
let outer = s.set_replaying(true);
|
||||
s.execute("view.saved.new", &json!({"name": "C", "center": [1, 2], "zoom": 2, "fitArt": true})).unwrap();
|
||||
s.set_replaying(outer);
|
||||
}
|
||||
|
||||
/// A batch step a schema refuses stops the batch before its first step runs.
|
||||
#[test]
|
||||
fn a_batch_is_checked_against_the_schemas_before_its_first_step() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let step = |p: Value| json!({"command": "view.saved.new", "params": p});
|
||||
for (last, named) in [
|
||||
(step(json!({"center": [0, 0], "zoom": 0})), "`zoom`"),
|
||||
(step(json!({"center": [0, 0]})), "`zoom`"),
|
||||
(json!({"command": "view.saved.new"}), "`center`"),
|
||||
] {
|
||||
let batch = json!({"commands": [step(json!({"name": "First", "center": [0, 0], "zoom": 1})), last]});
|
||||
let e = s.execute("command.batch", &batch).unwrap_err().to_string();
|
||||
assert!(e.contains("view.saved.new") && e.contains(named), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty(), "the first step did not run: {e}");
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// Values and keys far larger than any a command takes are refused with a short error and no
|
||||
/// panic. Nested values are leaked because dropping one recurses per level.
|
||||
#[test]
|
||||
fn hostile_values_are_refused_with_a_short_error() {
|
||||
fn deep(levels: usize) -> Value {
|
||||
(0..levels).fold(json!(1), |inner, _| Value::Array(vec![inner]))
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let huge = "z".repeat(2_000_000);
|
||||
for params in [
|
||||
json!({ huge.as_str(): 1, "center": [0, 0], "zoom": 1 }),
|
||||
json!({"center": [0, 0], "zoom": huge}),
|
||||
json!({"center": huge, "zoom": 1}),
|
||||
json!({"center": [0, 0], "zoom": 1, "name": [huge]}),
|
||||
json!({"center": [0, 0], "zoom": f64::MAX, "rotation": f64::INFINITY}),
|
||||
] {
|
||||
let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.chars().count() < 400, "{} chars", e.chars().count());
|
||||
}
|
||||
let e = s.execute("view.saved.edit", &json!({"edits": [{"name": "A", huge.as_str(): 1}]})).unwrap_err().to_string();
|
||||
assert!(e.chars().count() < 400, "{} chars", e.chars().count());
|
||||
let nested = json!({"center": [0, 0]});
|
||||
let Value::Object(mut map) = nested else { panic!() };
|
||||
map.insert("zoom".into(), deep(500_000));
|
||||
let params = Value::Object(map);
|
||||
let e = s.execute("view.saved.new", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`") && e.chars().count() < 400, "{e}");
|
||||
std::mem::forget(params);
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert!(s.doc().unwrap().history.undo.is_empty());
|
||||
}
|
||||
|
||||
/// Each command's JSON schema follows the 2020-12 rules, and a validator of those rules, which
|
||||
/// shares no code with the writer, gives the same answer as the schema check. None of these
|
||||
/// schemas has a lenient parameter.
|
||||
#[test]
|
||||
fn the_listed_schemas_follow_2020_12_and_agree_with_the_check() {
|
||||
let cases: &[(&str, Value)] = &[
|
||||
("view.capsLock", json!({})),
|
||||
("view.capsLock", json!({"on": true})),
|
||||
("view.capsLock", json!({"on": "yes"})),
|
||||
("view.capsLock", json!({"on": null})),
|
||||
("view.capsLock", json!({"of": true})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0.5, -2], "zoom": 0.001, "rotation": -30, "name": "A"})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": null})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "rotation": null})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 0})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": -1})),
|
||||
("view.saved.new", json!({"center": [0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, 0, 0], "zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, "0"], "zoom": 1})),
|
||||
("view.saved.new", json!({"zoom": 1})),
|
||||
("view.saved.new", json!({"center": [0, 0]})),
|
||||
("view.saved.new", json!({"center": [0, 0], "zoom": 1, "name": 5})),
|
||||
("view.saved.edit", json!({})),
|
||||
("view.saved.edit", json!({"name": "A", "newName": "B"})),
|
||||
("view.saved.edit", json!({"name": null, "delete": null})),
|
||||
("view.saved.edit", json!({"edits": []})),
|
||||
("view.saved.edit", json!({"edits": null})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": true}, {"name": "B", "newName": null}]})),
|
||||
("view.saved.edit", json!({"edits": [{"newName": "B"}]})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "delete": 1}]})),
|
||||
("view.saved.edit", json!({"edits": [{"name": "A", "x": 1}]})),
|
||||
("view.saved.edit", json!({"edits": {"name": "A"}})),
|
||||
("view.saved.list", json!({})),
|
||||
("view.saved.list", json!({"all": true})),
|
||||
("view.transparencyGrid", json!({})),
|
||||
("view.transparencyGrid", json!({"on": null})),
|
||||
("view.transparencyGrid", json!({"on": false})),
|
||||
("view.transparencyGrid", json!({"on": 1})),
|
||||
("view.snapToGlyph.options", json!({"bounds": false, "angular": true})),
|
||||
("view.snapToGlyph.options", json!({"bounds": null})),
|
||||
("view.capsLock", json!(null)),
|
||||
("view.saved.new", json!(null)),
|
||||
("view.saved.edit", json!(null)),
|
||||
("view.saved.list", json!(null)),
|
||||
("view.transparencyGrid", json!(null)),
|
||||
("view.snapToGlyph.options", json!(null)),
|
||||
("view.capsLock", json!([])),
|
||||
("view.saved.new", json!(5)),
|
||||
("view.transparencyGrid", json!("on")),
|
||||
("engine.apiReference", json!({})),
|
||||
("engine.apiReference", json!(null)),
|
||||
("engine.apiReference", json!({"prefix": "view."})),
|
||||
("engine.apiReference", json!([])),
|
||||
];
|
||||
assert_eq!(schemas().len(), 7);
|
||||
for (id, schema) in schemas() {
|
||||
let written = schema.to_json();
|
||||
check_schema(&written, id).unwrap_or_else(|e| panic!("{e}\n{written:#}"));
|
||||
assert!(cases.iter().any(|(c, _)| *c == id), "{id} has no cases");
|
||||
}
|
||||
for (id, params) in cases {
|
||||
let schema = schemas().into_iter().find(|(c, _)| c == id).unwrap().1;
|
||||
assert_eq!(schema.validate(params).is_ok(), instance_valid(&schema.to_json(), params), "{id} {params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's own listing carries the schema of each command that has one.
|
||||
#[test]
|
||||
fn engine_commands_list_the_schemas() {
|
||||
let s = Session::new();
|
||||
let all = s.commands();
|
||||
let grid = all.iter().find(|c| c.id == "view.transparencyGrid").and_then(|c| c.schema.clone()).unwrap();
|
||||
assert_eq!(grid["$schema"], vectorcraft_apischema::DIALECT);
|
||||
assert_eq!(grid["properties"]["on"]["x-default"], "toggle");
|
||||
let listed = serde_json::to_value(all.iter().find(|c| c.id == "view.saved.new").unwrap()).unwrap();
|
||||
assert_eq!(listed["schema"]["required"], json!(["center", "zoom"]));
|
||||
let without = serde_json::to_value(all.iter().find(|c| c.id == "file.new").unwrap()).unwrap();
|
||||
assert!(without.get("schema").is_none());
|
||||
}
|
||||
|
||||
/// The listing gives each command with a schema an `inputSchema`, the form an MCP tool's input
|
||||
/// schema takes: the same schema with the root `type` `"object"`, and every other keyword kept,
|
||||
/// nested parameters, required names, defaults and VectorCraft's own fields included. A command
|
||||
/// with no schema lists neither.
|
||||
#[test]
|
||||
fn engine_commands_list_an_input_schema_with_an_object_root() {
|
||||
let s = Session::new();
|
||||
let listed: Vec<Value> = s.commands().iter().map(|c| serde_json::to_value(c).unwrap()).collect();
|
||||
let mut with_schema = 0;
|
||||
for c in &listed {
|
||||
let id = c["id"].as_str().unwrap();
|
||||
let Some(schema) = c.get("schema") else {
|
||||
assert!(c.get("inputSchema").is_none(), "{id}");
|
||||
continue;
|
||||
};
|
||||
with_schema += 1;
|
||||
let input = c.get("inputSchema").unwrap_or_else(|| panic!("{id} has no inputSchema"));
|
||||
assert_eq!(input["type"], "object", "{id}");
|
||||
assert_eq!(input["$schema"], vectorcraft_apischema::DIALECT, "{id}");
|
||||
check_schema(input, id).unwrap_or_else(|e| panic!("{e}\n{input:#}"));
|
||||
assert!(!instance_valid(input, &Value::Null), "{id}: the arguments are an object");
|
||||
let without_type = |v: &Value| {
|
||||
let mut v = v.clone();
|
||||
v.as_object_mut().map(|o| o.remove("type"));
|
||||
v
|
||||
};
|
||||
assert_eq!(without_type(schema), without_type(input), "{id}");
|
||||
}
|
||||
assert_eq!(with_schema, schemas().len());
|
||||
let get = |id: &str| listed.iter().find(|c| c["id"] == id).unwrap();
|
||||
// No required parameter: the schema also takes null, the input schema does not.
|
||||
let list = get("view.saved.list");
|
||||
assert_eq!(list["schema"]["type"], json!(["object", "null"]));
|
||||
assert_eq!(list["inputSchema"]["type"], "object");
|
||||
// Required parameters and their constraints are kept.
|
||||
let new_view = get("view.saved.new");
|
||||
assert_eq!(new_view["inputSchema"]["required"], json!(["center", "zoom"]));
|
||||
assert_eq!(new_view["inputSchema"]["properties"], new_view["schema"]["properties"]);
|
||||
// Nested objects in an array keep their keys.
|
||||
let edit = &get("view.saved.edit")["inputSchema"]["properties"]["edits"];
|
||||
assert!(edit.to_string().contains("newName"), "{edit}");
|
||||
assert!(get("file.new").get("inputSchema").is_none());
|
||||
}
|
||||
|
||||
/// A deprecated command and a deprecated parameter keep their deprecation in the input schema.
|
||||
#[test]
|
||||
fn an_input_schema_keeps_deprecation() {
|
||||
static PARAMS: [Param; 2] = [Param::new("old", Type::Boolean).optional().deprecated(1), Param::new("on", Type::Boolean).optional()];
|
||||
let schema = ParamSchema::new(&PARAMS, "Old command.").deprecated(1).to_json();
|
||||
let input = crate::cmd::input_schema(&schema);
|
||||
check_schema(&input, "synthetic").unwrap_or_else(|e| panic!("{e}\n{input:#}"));
|
||||
assert_eq!(schema["type"], json!(["object", "null"]));
|
||||
assert_eq!(input["type"], "object");
|
||||
assert_eq!(input["deprecated"], true);
|
||||
assert_eq!(input["x-deprecatedSince"], 1);
|
||||
assert_eq!(input["properties"]["old"], schema["properties"]["old"]);
|
||||
assert_eq!(input["properties"]["old"]["deprecated"], true);
|
||||
assert_eq!(input["description"], "Old command.");
|
||||
}
|
||||
|
||||
/// The listing says what each View command changes when it runs. Only the commands that make an
|
||||
/// undo step list `document`.
|
||||
#[test]
|
||||
fn each_view_command_lists_what_it_writes() {
|
||||
let listed: Vec<(&str, Value)> = schemas().into_iter().map(|(id, schema)| (id, schema.to_json()["x-writes"].clone())).collect();
|
||||
let expected = [
|
||||
("view.capsLock", "session"),
|
||||
("view.saved.new", "document"),
|
||||
("view.saved.edit", "document"),
|
||||
("view.saved.list", "nothing"),
|
||||
("view.transparencyGrid", "session"),
|
||||
("view.snapToGlyph.options", "preferences"),
|
||||
];
|
||||
for (id, writes) in expected {
|
||||
let got = listed.iter().find(|(c, _)| *c == id).map(|(_, w)| w.clone());
|
||||
assert_eq!(got, Some(json!(writes)), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Values of type `ty` that pass it.
|
||||
fn valid(ty: Type) -> BoxedStrategy<Value> {
|
||||
fn number(min: Option<Bound>, max: Option<Bound>) -> BoxedStrategy<Value> {
|
||||
let low = match min {
|
||||
Some(Bound::Inclusive(a)) => a,
|
||||
Some(Bound::Exclusive(a)) => a + 1e-6_f64.max(a.abs() * 1e-9),
|
||||
None => -1e6,
|
||||
};
|
||||
let high = match max {
|
||||
Some(Bound::Inclusive(b)) => b,
|
||||
Some(Bound::Exclusive(b)) => b - 1e-6_f64.max(b.abs() * 1e-9),
|
||||
None => low.max(0.0) + 1e6,
|
||||
};
|
||||
(low..=high).prop_map(|x| json!(x)).boxed()
|
||||
}
|
||||
match ty {
|
||||
Type::Number { min, max, .. } => number(min, max),
|
||||
Type::Integer { min, max } => (min.unwrap_or(-1_000_000)..=max.unwrap_or(1_000_000)).prop_map(|x| json!(x)).boxed(),
|
||||
Type::Boolean => any::<bool>().prop_map(Value::from).boxed(),
|
||||
Type::String => "[ -~]{0,12}".prop_map(Value::from).boxed(),
|
||||
Type::Enum(names) => prop::sample::select(names.to_vec()).prop_map(Value::from).boxed(),
|
||||
Type::Id => (0u64..10_000).prop_map(Value::from).boxed(),
|
||||
Type::Ids => prop::collection::vec(0u64..10_000, 0..4).prop_map(Value::from).boxed(),
|
||||
Type::Color => Just(json!("#336699")).boxed(),
|
||||
Type::Point => (-1e6..1e6f64, -1e6..1e6f64).prop_map(|(x, y)| json!([x, y])).boxed(),
|
||||
Type::Object(params) => valid_object(params),
|
||||
Type::Array(item) => prop::collection::vec(valid(*item), 0..3).prop_map(Value::from).boxed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects that pass `params`: each required parameter, and each optional one or not.
|
||||
fn valid_object(params: &'static [Param]) -> BoxedStrategy<Value> {
|
||||
let parts: Vec<BoxedStrategy<Option<(String, Value)>>> = params
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let entry = valid(p.ty).prop_map(move |v| Some((p.name.to_string(), v)));
|
||||
if p.required { entry.boxed() } else { prop_oneof![Just(None), entry].boxed() }
|
||||
})
|
||||
.collect();
|
||||
parts.prop_map(|entries| Value::Object(entries.into_iter().flatten().collect::<Map<String, Value>>())).boxed()
|
||||
}
|
||||
|
||||
/// Commands with a schema and params for them that pass it.
|
||||
fn valid_calls() -> BoxedStrategy<(&'static str, Value)> {
|
||||
let calls: Vec<BoxedStrategy<(&'static str, Value)>> =
|
||||
schemas().into_iter().map(|(id, schema)| valid_object(schema.params).prop_map(move |p| (id, p)).boxed()).collect();
|
||||
prop::strategy::Union::new(calls).boxed()
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Params that pass a command's schema never get a parameter error about a value's type or
|
||||
/// range from the command itself: the schema refuses whatever the command's own checks would.
|
||||
#[test]
|
||||
fn schema_valid_params_get_no_type_error_from_the_command((id, params) in valid_calls(), views in 0usize..3) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for i in 0..views {
|
||||
s.execute("view.saved.new", &json!({"name": format!("V{i}"), "center": [0, 0], "zoom": 1})).unwrap();
|
||||
}
|
||||
match s.execute(id, ¶ms) {
|
||||
Err(EngineError::BadParams { msg, .. }) => {
|
||||
prop_assert!(!msg.contains(" must be ") && !msg.contains("missing") && !msg.contains("unknown parameter"), "{id} {params}: {msg}");
|
||||
}
|
||||
Err(EngineError::Internal { msg, .. }) => prop_assert!(false, "{id} {params} panicked: {msg}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,9 +80,13 @@ impl Session {
|
||||
brush_libraries: Default::default(),
|
||||
libraries: Default::default(),
|
||||
pdf_preset_dir: None,
|
||||
dictionary_file: None,
|
||||
profile_dir: None,
|
||||
plugin_dir: None,
|
||||
ignored_plugin_grants: Default::default(),
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
plugin_grants_from_requests: false,
|
||||
recent_urls: vec![],
|
||||
trace_preset_changes: Default::default(),
|
||||
ui_language: None,
|
||||
|
||||
@@ -60,6 +60,11 @@ impl Session {
|
||||
if !self.replaying {
|
||||
self.check_params(id, params)?;
|
||||
}
|
||||
// A command with a parameter schema runs only with params that pass it, and with the
|
||||
// defaults of omitted values filled in; the journal keeps the params as given. Saved steps
|
||||
// keep their keys the schema doesn't name, as above.
|
||||
let checked = crate::schemas::check(spec, params, self.replaying)?;
|
||||
let run_params = checked.as_ref().unwrap_or(params);
|
||||
// Objects given as `id` (where it stands for `ids` of one) or as `ids` beside it are checked
|
||||
// before anything else: a malformed one, or one naming no object, is an error under this
|
||||
// command's id, never the selection in its place. `effect.apply {id: "stylize.dropShadow"}`
|
||||
@@ -126,7 +131,7 @@ impl Session {
|
||||
if let Some(ids) = &select_first {
|
||||
s.execute("select.set", &serde_json::json!({ "ids": ids }))?;
|
||||
}
|
||||
let r = cmd::run_spec(s, spec, params);
|
||||
let r = cmd::run_spec(s, spec, run_params);
|
||||
if r.is_err()
|
||||
&& let Some((uid, selection, layer)) = selected_before
|
||||
&& let Some(st) = s.docs.iter_mut().find(|d| d.uid == uid)
|
||||
|
||||
+145
-37
@@ -28,7 +28,7 @@
|
||||
//! The files are untrusted input like any other: sizes and counts are capped, a file that does not
|
||||
//! parse is skipped with a log record, and every write is atomic.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -62,6 +62,8 @@ pub const DISABLED_FILE: &str = "disabled.json";
|
||||
pub const DISABLED_LOCK: &str = "disabled.lock";
|
||||
/// The file in the plug-in store that holds the permissions the user granted.
|
||||
const GRANTS_FILE: &str = "grants.json";
|
||||
/// The error of a `plugin.remove` that can't remove the plug-in's grant from [`GRANTS_FILE`].
|
||||
pub(crate) const GRANT_NOT_REMOVED: &str = "the plug-in's grant can't be removed from the plug-in store";
|
||||
/// The largest grants file read.
|
||||
const MAX_GRANTS_FILE: u64 = 1 << 20;
|
||||
/// The folder in the plug-in store that holds each plug-in's settings and cache.
|
||||
@@ -110,15 +112,21 @@ fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
|
||||
|
||||
/// The content of `path` when it is at most `max` bytes; the file is never read past `max`.
|
||||
pub(crate) fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||
let mut bytes = vec![];
|
||||
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
let bytes = read_past_cap(path, max).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err(too_large(max));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The first `max + 1` bytes of `path` at most, so that a result longer than `max` shows the file is
|
||||
/// over its cap.
|
||||
fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
let mut bytes = vec![];
|
||||
std::fs::File::open(path)?.take(max + 1).read_to_end(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// What a file over its cap is told (a detail after the file's name, in the log or an error).
|
||||
fn too_large(max: u64) -> String {
|
||||
format!("larger than {max} bytes")
|
||||
@@ -168,13 +176,21 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Remove `dir/file`; a file that isn't there is what was wanted.
|
||||
fn take(dir: &Path, file: &str) {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume.
|
||||
pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
|
||||
fn take(dir: &Path, file: &str) -> bool {
|
||||
let path = dir.join(file);
|
||||
if let Err(e) = std::fs::remove_file(&path)
|
||||
&& e.kind() != std::io::ErrorKind::NotFound
|
||||
{
|
||||
log::warn!("can't remove {}: {e}", path.display());
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
|
||||
log::warn!("can't remove {}: {e}", path.display());
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +299,9 @@ impl Session {
|
||||
let disabled =
|
||||
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
|
||||
safe_mode::set_disabled(disabled);
|
||||
if self.plugin_dir.as_ref() != Some(&dir) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
}
|
||||
self.plugin_dir = Some(dir);
|
||||
self.load_stored_plugins();
|
||||
}
|
||||
@@ -291,15 +310,18 @@ impl Session {
|
||||
/// disabled (matched by file name, which is made from the id). The launch marker names each
|
||||
/// file while it loads. A module that doesn't load, and one that lists permissions the grants
|
||||
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
|
||||
/// stays in the folder with its grant.
|
||||
/// stays in the folder with its grant. A grant for an id whose stored module lists no
|
||||
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
|
||||
/// the rest of the session ([`Session::plugin_approver`]).
|
||||
pub fn load_stored_plugins(&mut self) {
|
||||
let Some(dir) = self.plugin_dir.clone() else { return };
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let grants = stored_grants(&dir);
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
let mut asks_nothing = BTreeSet::new();
|
||||
for path in list_files(&dir, PLUGIN_EXT) {
|
||||
if left == 0 {
|
||||
log::warn!("skipping the other stored plug-ins: they hold more than {MAX_PLUGIN_STORE} bytes together");
|
||||
@@ -325,6 +347,7 @@ impl Session {
|
||||
let m = plugin.manifest();
|
||||
match grants.get(&m.id).filter(|g| grant_covers(g, &plugin)) {
|
||||
Some(g) => {
|
||||
asks_nothing.remove(&m.id);
|
||||
vectorcraft_plugins::registry::grant(g.clone());
|
||||
vectorcraft_plugins::registry::set_storage(&m.id, plugin_storage(Some(&dir), &m.id));
|
||||
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
|
||||
@@ -335,12 +358,24 @@ impl Session {
|
||||
}
|
||||
}
|
||||
Ok(plugin) => {
|
||||
asks_nothing.insert(plugin.id().to_string());
|
||||
vectorcraft_plugins::registry::set_storage(plugin.id(), plugin_storage(Some(&dir), plugin.id()));
|
||||
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
|
||||
}
|
||||
Err(e) => log::warn!("skipping the stored plug-in {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let kept = read_grants(&dir);
|
||||
for id in &asks_nothing {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
let named = match &kept {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
};
|
||||
if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) {
|
||||
self.ignore_stored_grant(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the disabled plug-ins saved for the next launch to the plug-in folder → whether they
|
||||
@@ -379,7 +414,8 @@ impl Session {
|
||||
|
||||
/// Whether `plugin` installs without asking the user: it lists no permissions, or this very
|
||||
/// module (its id and SHA-256) was granted every one it lists, in the grants of the attached
|
||||
/// plug-in store when there is one ([`grant_covers`]), else in this process's
|
||||
/// plug-in store when there is one ([`grant_covers`]), not counting a grant that should be gone
|
||||
/// and could not be removed ([`Session::ignore_stored_grant`]), else in this process's
|
||||
/// ([`vectorcraft_plugins::registry::approved`]).
|
||||
pub(crate) fn plugin_approved(&self, plugin: &vectorcraft_plugins::Plugin) -> bool {
|
||||
self.plugin_approver()(plugin)
|
||||
@@ -388,7 +424,7 @@ impl Session {
|
||||
/// [`Session::plugin_approved`] for many plug-ins: reads the store's grants once, when it is
|
||||
/// made, and checks each plug-in against them.
|
||||
pub(crate) fn plugin_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> {
|
||||
let grants = self.plugin_dir.as_deref().map(stored_grants);
|
||||
let grants = self.plugin_dir.as_deref().map(|dir| self.counted_grants(dir));
|
||||
move |plugin| {
|
||||
let m = plugin.manifest();
|
||||
match &grants {
|
||||
@@ -398,6 +434,15 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
|
||||
/// doesn't count ([`Session::ignore_stored_grant`]).
|
||||
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
|
||||
let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut grants = stored_grants(dir);
|
||||
grants.retain(|id, _| !ignored.contains(id));
|
||||
grants
|
||||
}
|
||||
|
||||
/// Write the module `bytes` of the plug-in `id` to the store → whether they went there (`false`
|
||||
/// without a folder).
|
||||
pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) -> bool {
|
||||
@@ -417,12 +462,15 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Return the store's module for the plug-in `id` to `previous`, the bytes it held before a
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) {
|
||||
/// write ([`Session::stored_plugin_bytes`]): with `None`, the file is removed. → whether the
|
||||
/// store now holds `previous`.
|
||||
pub(crate) fn put_back_plugin(&self, id: &str, previous: Option<&[u8]>) -> bool {
|
||||
#[cfg(test)]
|
||||
if PUT_BACK_FAILS.get() {
|
||||
return false;
|
||||
}
|
||||
match previous {
|
||||
Some(bytes) => {
|
||||
self.store_plugin(id, bytes);
|
||||
}
|
||||
Some(bytes) => self.store_plugin(id, bytes),
|
||||
None => self.unstore_plugin(id),
|
||||
}
|
||||
}
|
||||
@@ -438,13 +486,29 @@ impl Session {
|
||||
/// are written back as they were, except one for `id`. A grants file that is too large, can't
|
||||
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
|
||||
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
|
||||
/// holds what was asked (`false` without a folder).
|
||||
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
|
||||
/// again ([`Session::ignore_stored_grant`]).
|
||||
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let done = self.write_grant(id, grant);
|
||||
if done {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
|
||||
}
|
||||
done
|
||||
}
|
||||
|
||||
/// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next
|
||||
/// succeeds for it or another store is attached: for a grant that should be gone and could not
|
||||
/// be removed, which would otherwise approve the bytes it covers.
|
||||
pub(crate) fn ignore_stored_grant(&self, id: &str) {
|
||||
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string());
|
||||
}
|
||||
|
||||
fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
|
||||
let Some(dir) = &self.plugin_dir else { return false };
|
||||
let mut file = match read_grants(dir) {
|
||||
Ok(file) => file,
|
||||
Err(e) => {
|
||||
log::warn!("not updating the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -460,8 +524,7 @@ impl Session {
|
||||
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
|
||||
entries.extend(file.other);
|
||||
if entries.is_empty() {
|
||||
take(dir, GRANTS_FILE);
|
||||
return true;
|
||||
return take(dir, GRANTS_FILE);
|
||||
}
|
||||
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
|
||||
// and not at all when that is too.
|
||||
@@ -475,11 +538,20 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store.
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) {
|
||||
if let Some(dir) = &self.plugin_dir {
|
||||
take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id)));
|
||||
}
|
||||
/// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this
|
||||
/// version can't use ([`GrantsFile::names`]). `true` when the grants file can't be opened or
|
||||
/// read, because it may name `id` once it reads again; `false` without a folder, and when the
|
||||
/// file is too large or doesn't hold a list.
|
||||
pub(crate) fn holds_plugin_grant(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| match read_grants(dir) {
|
||||
Ok(file) => file.names(id),
|
||||
Err(e) => e.unread,
|
||||
})
|
||||
}
|
||||
|
||||
/// Remove the plug-in `id` from the store → whether its file is gone (`false` without a folder).
|
||||
pub(crate) fn unstore_plugin(&self, id: &str) -> bool {
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| take(dir, &format!("{}.{PLUGIN_EXT}", file_stem(id))))
|
||||
}
|
||||
|
||||
/// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without
|
||||
@@ -500,10 +572,15 @@ impl Session {
|
||||
/// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it.
|
||||
/// The folder is first renamed out of the way (`<folder>.removed`), and that fails, leaving it
|
||||
/// as it was, when the rename does; what the deletion then leaves stays under that name, with a
|
||||
/// log record. A later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str) -> Result<(), StorageError> {
|
||||
/// log record. A later call for the id tries to delete it again. `forget` runs once the folder is
|
||||
/// out of the way, before anything is deleted: when it returns `false`, the folder is renamed
|
||||
/// back and this fails.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string());
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
let Some(dir) = &self.plugin_dir else { return Ok(()) };
|
||||
let Some(dir) = &self.plugin_dir else {
|
||||
return if forget() { Ok(()) } else { Err(not_forgotten()) };
|
||||
};
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let path = plugin_data_dir(dir, id);
|
||||
// Every storage handed out for the folder, including those runs still hold, is closed once
|
||||
@@ -518,6 +595,9 @@ impl Session {
|
||||
let data = dir.join(PLUGIN_DATA_DIR);
|
||||
if is_link(&data) {
|
||||
log::warn!("{} is a link: the plug-in settings and cache it leads to are left", data.display());
|
||||
if !forget() {
|
||||
return Err(not_forgotten());
|
||||
}
|
||||
close();
|
||||
return Ok(());
|
||||
}
|
||||
@@ -530,6 +610,14 @@ impl Session {
|
||||
Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))),
|
||||
Ok(()) => {}
|
||||
}
|
||||
if !forget() {
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::rename(&aside, &path)
|
||||
{
|
||||
log::warn!("can't move {} back: {e}", aside.display());
|
||||
}
|
||||
return Err(not_forgotten());
|
||||
}
|
||||
close();
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::remove_dir_all(&aside)
|
||||
@@ -960,16 +1048,36 @@ struct GrantsFile {
|
||||
other: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl GrantsFile {
|
||||
/// Whether the file has an entry for the plug-in `id`, usable by this version or not.
|
||||
fn names(&self, id: &str) -> bool {
|
||||
self.grants.contains_key(id) || self.other.iter().any(|e| e.get("id").and_then(serde_json::Value::as_str) == Some(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the grants file of a plug-in store gave no grants.
|
||||
struct GrantsError {
|
||||
/// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is
|
||||
/// too large or doesn't hold a list, and approves nothing.
|
||||
unread: bool,
|
||||
/// The detail for a log record.
|
||||
why: String,
|
||||
}
|
||||
|
||||
/// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too
|
||||
/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an
|
||||
/// invalid id, is kept in [`GrantsFile::other`] with a log record.
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, String> {
|
||||
fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
|
||||
let path = dir.join(GRANTS_FILE);
|
||||
if !path.exists() {
|
||||
return Ok(GrantsFile::default());
|
||||
let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(GrantsFile::default()),
|
||||
Err(e) => return Err(GrantsError { unread: true, why: e.to_string() }),
|
||||
};
|
||||
if bytes.len() as u64 > MAX_GRANTS_FILE {
|
||||
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
|
||||
}
|
||||
let entries =
|
||||
read_capped(&path, MAX_GRANTS_FILE).and_then(|bytes| serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| e.to_string()))?;
|
||||
let entries = serde_json::from_slice::<Vec<serde_json::Value>>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?;
|
||||
let mut file = GrantsFile::default();
|
||||
let mut first_error = None;
|
||||
for entry in entries {
|
||||
@@ -997,7 +1105,7 @@ fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permission
|
||||
match read_grants(dir) {
|
||||
Ok(file) => file.grants,
|
||||
Err(e) => {
|
||||
log::warn!("skipping the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
|
||||
log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why);
|
||||
BTreeMap::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +158,7 @@ mod simplify_part;
|
||||
mod slices;
|
||||
mod smartguides;
|
||||
mod smooth_path;
|
||||
mod spelling;
|
||||
mod store;
|
||||
mod strokegeom;
|
||||
mod strokegradient;
|
||||
@@ -185,6 +186,7 @@ mod transformfx;
|
||||
mod transparencygrid;
|
||||
mod trap;
|
||||
mod typearea;
|
||||
mod typeglyphbounds;
|
||||
mod typescale;
|
||||
mod typeundo;
|
||||
mod units;
|
||||
|
||||
@@ -823,6 +823,13 @@ fn shape_builder_applies_a_merge_before_what_comes_next() {
|
||||
// No files: the command fails after the merge.
|
||||
assert!(s.execute("text.addFontFiles", &json!({"files": []})).is_err());
|
||||
}),
|
||||
("a call its schema refuses", |s, _, _| {
|
||||
// The refused call adds no undo step of its own: the merge's is the last one.
|
||||
let e = s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("`zoom`"), "{e}");
|
||||
assert!(s.doc().unwrap().doc.views.is_empty());
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Shape Builder"));
|
||||
}),
|
||||
];
|
||||
let _proof = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dir = vectorcraft_testkit::temp_dir("shape-builder-merge-first");
|
||||
|
||||
@@ -173,6 +173,22 @@ fn blend_recolors_a_colorized_gray_image_without_alpha() {
|
||||
assert_eq!(colorize(&s, middle), Some(Paint::solid(Color::rgb(0.5, 0.5, 0.5))));
|
||||
}
|
||||
|
||||
/// A colorized image shows a fill and no stroke, so selecting it loads them for new art as any
|
||||
/// object without a stroke does (the weight stays).
|
||||
#[test]
|
||||
fn selecting_a_colorized_image_gives_new_art_its_fill_and_no_stroke() {
|
||||
let mut s = session();
|
||||
let id = image(&mut s, "gray", gray(false));
|
||||
s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 5.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(s.paint.fill.color().map(|c| c.to_hex()), Some("#336699".into()));
|
||||
assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, 5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_proxy_invert_recolors_a_colorized_gray_image_and_undo_restores_it() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -2698,19 +2698,15 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
|
||||
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into());
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
assert_eq!(pasted(&mut s), [2]);
|
||||
// Cut takes the segment between them. The two surviving runs of an ordinary path
|
||||
// become independent objects, and this path keeps the first run (#3380).
|
||||
// Cut takes the two anchors out of the path, as Clear does (#6361): each side keeps one
|
||||
// anchor, which makes no path, so nothing is left.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let original = path(&s, id);
|
||||
let picked = s.doc().unwrap().selection.clone();
|
||||
s.execute("edit.cut", &json!({})).unwrap();
|
||||
let left = paths(&s);
|
||||
assert_eq!(left.len(), 2);
|
||||
assert_eq!(left[0].0, id);
|
||||
assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed));
|
||||
assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]);
|
||||
assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::<Vec<_>>());
|
||||
assert!(left.is_empty());
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty());
|
||||
assert_eq!(s.clipboard.nodes.len(), 1);
|
||||
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Dynamic symbols (#4938): an instance changes the appearance of objects in its symbol's art and
|
||||
//! stays linked; editing the symbol keeps those changes, Reset and Break Link handle them. Direct
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and a solid color
|
||||
//! Fill or Stroke changes it.
|
||||
//! Selection picks one path, compound path or type object of an instance's art, and Fill, Stroke,
|
||||
//! opacity and blend change it for that instance.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
@@ -51,8 +51,9 @@ fn pixel(s: &Session, x: u32, y: u32) -> [u8; 4] {
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
/// The refusal of anything but a solid fill or stroke on a picked object says so.
|
||||
const REFUSED: &str = "solid color fill and stroke";
|
||||
/// The refusal of a change that is not fill, stroke, opacity or blend on a picked path, compound
|
||||
/// path or type (or of selecting any other kind of object) says so.
|
||||
const REFUSED: &str = "fill, stroke, opacity and blend";
|
||||
|
||||
#[test]
|
||||
fn a_dynamic_instance_paints_one_object_its_own_way_and_stays_linked() {
|
||||
@@ -655,8 +656,7 @@ fn commands_on_the_selection_leave_a_picked_objects_instance_alone() {
|
||||
("object.repeat.release", json!({})),
|
||||
("object.intertwine.release", json!({})),
|
||||
("object.objectsOnPath.expand", json!({})),
|
||||
("transparency.set", json!({"opacity": 50})),
|
||||
("transparency.set", json!({"blend": "multiply"})),
|
||||
("transparency.set", json!({"opacity": 50, "isolate": true})),
|
||||
("transparency.releaseOpacityMask", json!({})),
|
||||
("transparency.setOpacityMask", json!({"invert": true, "clip": false})),
|
||||
("transparency.disableOpacityMask", json!({})),
|
||||
@@ -858,38 +858,30 @@ fn a_press_on_an_image_of_the_art_is_refused_and_moves_nothing() {
|
||||
assert_eq!(overrides(&s, inst), 0);
|
||||
}
|
||||
|
||||
/// A gradient or pattern for a picked object is refused and changes nothing, new art's paint
|
||||
/// included. An object that shows a gradient takes a solid color.
|
||||
/// A gradient or pattern for a picked object is stored on the instance; Invert, Complement and the
|
||||
/// gradient annotator stay refused. An object that shows a gradient takes a solid color.
|
||||
#[test]
|
||||
fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
fn gradients_and_patterns_on_a_picked_object_are_taken() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("swatch.new", &json!({"name": "Ramp", "gradient": g})).unwrap();
|
||||
let tile = square(&mut s, 150.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Dots", "edit": false})).unwrap();
|
||||
// An object to sample a gradient from.
|
||||
let far = square(&mut s, 150.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [far.0], "gradient": g})).unwrap();
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
let undo = undo_steps(&s);
|
||||
let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone());
|
||||
for (cmd, p) in [
|
||||
("paint.setFill", json!({"gradient": g})),
|
||||
("paint.setStroke", json!({"gradient": g})),
|
||||
("paint.setFill", json!({"gradient": g, "span": "selection"})),
|
||||
("paint.setFill", json!({"swatch": "Ramp"})),
|
||||
("paint.setFill", json!({"swatch": "Dots"})),
|
||||
("appearance.copyFrom", json!({"source": far.0})),
|
||||
] {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd} {p}: {e}");
|
||||
}
|
||||
assert_eq!((overrides(&s, inst), undo_steps(&s)), (0, undo), "nothing changes");
|
||||
assert_eq!((&s.paint.fill, &s.paint.stroke), (&fill, &stroke), "new art keeps its paint");
|
||||
// An object whose art has a gradient takes a solid color; Invert, Complement and selecting one
|
||||
// of its stops are refused.
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst.0, "path": [1], "fill": {"gradient": g}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setStroke", &json!({"gradient": g})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].stroke, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Ramp"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Pattern { .. })));
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0})).unwrap();
|
||||
assert!(matches!(node(&s, inst).extras().symbol_overrides[0].fill, Some(Paint::Gradient(_))));
|
||||
// Invert, Complement and selecting a stop are refused on a gradient.
|
||||
for cmd in ["paint.invert", "paint.complement"] {
|
||||
let e = s.execute(cmd, &json!({"stroke": false})).unwrap_err().to_string();
|
||||
assert!(e.contains(REFUSED), "{cmd}: {e}");
|
||||
@@ -902,10 +894,8 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!(s.selected_stop(), None);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// The Eyedropper's options can leave the gradient out: the fill stays.
|
||||
s.execute("appearance.copyFrom", &json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}}}})).unwrap();
|
||||
assert_eq!(pixel(&s, 80, 30), RED);
|
||||
// Options that pick up neither color leave nothing to change, so the click is refused.
|
||||
let (undo, fill) = (undo_steps(&s), s.paint.fill.clone());
|
||||
let neither = json!({"source": far.0, "pickUp": {"appearance": {"fill": {"color": false}, "stroke": {"color": false}}}});
|
||||
let e = s.execute("appearance.copyFrom", &neither).unwrap_err().to_string();
|
||||
@@ -913,6 +903,26 @@ fn gradients_and_patterns_on_a_picked_object_are_refused() {
|
||||
assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
|
||||
assert_eq!(node(&s, inst).extras().symbol_overrides[0].opacity, Some(0.5));
|
||||
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
|
||||
let o = node(&s, inst).extras().symbol_overrides[0].clone();
|
||||
assert_eq!(o.opacity, Some(0.5));
|
||||
assert_eq!(o.blend, Some(vectorcraft_color::BlendMode::Multiply));
|
||||
// A static symbol's instance refuses selectPart, so transparency.set acts on the instance whole.
|
||||
let mut t = session();
|
||||
let static_inst = pair(&mut t, "static");
|
||||
t.execute("select.set", &json!({"ids": [static_inst.0]})).unwrap();
|
||||
t.execute("transparency.set", &json!({"opacity": 40})).unwrap();
|
||||
assert!(node(&t, static_inst).extras().symbol_overrides.is_empty());
|
||||
assert!((node(&t, static_inst).opacity - 0.4).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -342,7 +342,12 @@ fn pixels(s: &Session, id: NodeId) -> Vec<[u8; 4]> {
|
||||
|
||||
/// A selected embedded 2×2 image.
|
||||
fn image_node(s: &mut Session) -> NodeId {
|
||||
let bytes = png([[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]]);
|
||||
image_of(s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 128]])
|
||||
}
|
||||
|
||||
/// A selected embedded 2×2 image of the pixels `px`.
|
||||
fn image_of(s: &mut Session, px: [[u8; 4]; 4]) -> NodeId {
|
||||
let bytes = png(px);
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(bytes));
|
||||
let id = d.alloc_id();
|
||||
@@ -383,6 +388,85 @@ fn invert_recolours_an_embedded_image() {
|
||||
assert_eq!(pixels(&s, id)[..2], [[0, 0, 0, 255], [0, 255, 0, 255]]);
|
||||
}
|
||||
|
||||
/// The key of image object `id`'s blob.
|
||||
fn image_key(s: &Session, id: NodeId) -> String {
|
||||
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not an image") };
|
||||
im.key.clone()
|
||||
}
|
||||
|
||||
/// Convert to Grayscale stores an image with one color channel, alpha kept (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_an_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let key = image_key(&s, id);
|
||||
let source = s.doc().unwrap().doc.images[&key].gray_source();
|
||||
assert!(source.is_some_and(|g| g.alpha && !g.one_bit), "a grayscale file with alpha: {source:?}");
|
||||
let gray = |hex: &str| Color::from_hex(hex).unwrap().in_model(vectorcraft_color::cms::Model::Gray).to_rgba8(1.0)[0];
|
||||
let (r_, g_, b_, w) = (gray("#ff0000"), gray("#00ff00"), gray("#0000ff"), gray("#ffffff"));
|
||||
assert_eq!(pixels(&s, id), [[r_, r_, r_, 255], [g_, g_, g_, 255], [b_, b_, b_, 255], [w, w, w, 128]]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(pixels(&s, id)[0], [255, 0, 0, 255], "one undo step restores the color image");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// An image that is already grayscale has nothing to convert.
|
||||
let again = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(again["changed"], 0);
|
||||
assert_eq!(image_key(&s, id), key);
|
||||
}
|
||||
|
||||
/// An RGB image whose pixels are all neutral still becomes a one-channel image (#5632).
|
||||
#[test]
|
||||
fn convert_to_grayscale_stores_a_neutral_rgb_image_as_grayscale() {
|
||||
let mut s = session();
|
||||
let id = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["changed"], 1);
|
||||
let source = s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source();
|
||||
assert!(source.is_some_and(|g| !g.alpha), "an opaque image has no alpha channel: {source:?}");
|
||||
}
|
||||
|
||||
/// Select All leaves a hidden neutral RGB image out of Convert to Grayscale, which would change it.
|
||||
#[test]
|
||||
fn a_hidden_neutral_rgb_image_counts_as_not_converted() {
|
||||
let mut s = session();
|
||||
let hidden = image_of(&mut s, [[255, 255, 255, 255], [0, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]]);
|
||||
s.execute("layer.setProps", &json!({"ids": [hidden.0], "visible": false})).unwrap();
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let r = s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
assert_eq!(r["notChanged"], json!({"locked": 0, "hidden": 1}), "{r}");
|
||||
}
|
||||
|
||||
/// Adjust Colors converting to gray stores an image with one channel; without Convert it keeps
|
||||
/// the image's RGB (#5632).
|
||||
#[test]
|
||||
fn adjust_colors_converting_to_gray_stores_an_image_as_grayscale() {
|
||||
let source = |convert: bool| {
|
||||
let mut s = session();
|
||||
let id = image_node(&mut s);
|
||||
s.execute("edit.colors.adjustBalance", &json!({"mode": "gray", "gray": 10, "convert": convert})).unwrap();
|
||||
s.doc().unwrap().doc.images[&image_key(&s, id)].gray_source()
|
||||
};
|
||||
assert!(source(true).is_some(), "converted to gray");
|
||||
assert!(source(false).is_none(), "the colors keep their model");
|
||||
}
|
||||
|
||||
/// A PDF of a CMYK document writes an image Convert to Grayscale made with one channel (#5632).
|
||||
#[test]
|
||||
fn a_converted_image_is_written_to_pdf_as_gray_in_a_cmyk_document() {
|
||||
let mut s = session();
|
||||
s.execute("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap();
|
||||
image_of(&mut s, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [10, 200, 30, 255]]);
|
||||
s.execute("edit.colors.toGrayscale", &json!({})).unwrap();
|
||||
let opts = vectorcraft_pdf::PdfOptions { created: Some(0), ..vectorcraft_pdf::PdfOptions::uncompressed() };
|
||||
let pdf = String::from_utf8_lossy(&vectorcraft_pdf::export(&s.doc().unwrap().doc, &opts).unwrap()).into_owned();
|
||||
let image = pdf.split("/Subtype/Image").nth(1).or_else(|| pdf.split("/Subtype /Image").nth(1)).expect("an image in the PDF");
|
||||
let image = &image[..image.find("stream").unwrap_or(image.len())];
|
||||
assert!(image.contains("/DeviceGray") && !image.contains("/DeviceRGB"), "one color channel: {image}");
|
||||
}
|
||||
|
||||
/// "Dots": a red square tile; a selected rectangle filled with it.
|
||||
fn pattern_fill(s: &mut Session) -> NodeId {
|
||||
rect(s, json!("#ff0000"));
|
||||
|
||||
@@ -447,6 +447,27 @@ fn export_selection_keeps_the_effects_in_the_crop() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Outer Glow at its default Screen mode on the bare page is in a PNG on white and in a JPEG,
|
||||
/// and in a transparent PNG (#6125).
|
||||
#[test]
|
||||
fn a_screen_outer_glow_is_in_raster_exports() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.outerGlow"})).unwrap();
|
||||
let mut pixel = |p: serde_json::Value| {
|
||||
let v = s.execute("document.export", &p).unwrap();
|
||||
let img = image::load_from_memory(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap().to_rgba8();
|
||||
// 2 pt past the square's stroke, on the right.
|
||||
*img.get_pixel(122, 110)
|
||||
};
|
||||
for p in [json!({"format": "png", "background": "white"}), json!({"format": "jpg"})] {
|
||||
let px = pixel(p.clone());
|
||||
assert!(px[0] > 235 && px[1] > 235 && px[2] < 235, "{p}: yellow on white: {px:?}");
|
||||
}
|
||||
let px = pixel(json!({"format": "png", "background": "transparent"}));
|
||||
assert!(px[3] > 0 && px[0] > 235 && px[1] > 235 && px[2] < 40, "the glow is yellow in the transparent image: {px:?}");
|
||||
}
|
||||
|
||||
/// A group's own drop shadow is inside the crop of the group's selection export too.
|
||||
#[test]
|
||||
fn export_selection_keeps_a_groups_shadow_in_the_crop() {
|
||||
|
||||
@@ -3687,6 +3687,40 @@ fn ruler_guides_and_lock() {
|
||||
assert!(s.execute("guide.remove", &json!({"index": 0})).is_err());
|
||||
}
|
||||
|
||||
/// While guides are locked, a guide dragged out of a ruler and `guide.add` still make new guides,
|
||||
/// each in one undo step and not selected. The ruler guides and guide paths in the document, the
|
||||
/// new guides included, can't be selected, moved or deleted.
|
||||
#[test]
|
||||
fn new_guides_can_be_made_while_guides_are_locked() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let path = guide_path(&mut s, 300.0);
|
||||
s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
let n = undo_len(&s);
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Drag, 153.0, 30.0), true, v).unwrap();
|
||||
s.ruler_guide(true, &PointerEvent::new(PointerKind::Up, 153.0, 30.0), true, v).unwrap();
|
||||
assert_eq!(guides(&s), [(false, 50.0), (true, 153.0)]);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "New Guide");
|
||||
assert_eq!(s.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap()["index"], 2);
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
assert_eq!(selected_guides(&s), Vec::<usize>::new());
|
||||
for (id, params) in [
|
||||
("guide.select", json!({"indexes": [1]})),
|
||||
("guide.move", json!({"index": 1, "pos": 170})),
|
||||
("guide.remove", json!({"index": 1})),
|
||||
("guide.setLayer", json!({"index": 1, "layer": s.doc().unwrap().current_layer().unwrap().0})),
|
||||
] {
|
||||
assert!(matches!(s.execute(id, ¶ms), Err(EngineError::Disabled(..))), "{id}");
|
||||
}
|
||||
assert_eq!(guides(&s).len(), 3);
|
||||
sel(&mut s, &[path]);
|
||||
assert!(selected(&s).is_empty(), "a guide path can't be selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_guide_lock_parameters_keep_guides_selected() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1786,6 +1786,54 @@ fn delete_empty_artboards_check_measures_a_document_once() {
|
||||
assert_eq!(delete_empty_enabled_counted(&s), (true, 0), "after another change of the selection");
|
||||
}
|
||||
|
||||
/// Whether Fit to Artwork Bounds has art to fit on `indices`, as a menu asks for it, with the
|
||||
/// plug-ins' and fonts' generations `outside`, and how many times asking measured a document on
|
||||
/// this thread.
|
||||
fn art_to_fit_counted(s: &Session, indices: &[usize], outside: (u64, u64)) -> (bool, usize) {
|
||||
let measures = || crate::doc_state::ART_TO_FIT_MEASURES.with(std::cell::Cell::get);
|
||||
let before = measures();
|
||||
let any = s.doc().unwrap().any_art_to_fit_with(indices, outside);
|
||||
(any, measures() - before)
|
||||
}
|
||||
|
||||
/// A menu asks whether Fit to Artwork Bounds has art on every frame while it is open: the answer is
|
||||
/// measured once for a version of the document and the artboards asked about, kept through a change
|
||||
/// of the selection or the view, and measured again after an edit, for other artboards, and when
|
||||
/// the plug-ins or the fonts change.
|
||||
#[test]
|
||||
fn art_to_fit_is_measured_once_for_a_version_of_the_document() {
|
||||
let mut s = row_of_artboards(2);
|
||||
let both = [0, 1];
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 1), "the first frame");
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (false, 0), "a later frame");
|
||||
let art = box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 1), "an edit puts art on artboard 1");
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the selection");
|
||||
s.execute("view.transparencyGrid", &json!({})).unwrap();
|
||||
assert_eq!(art_to_fit_counted(&s, &both, (0, 0)), (true, 0), "after a change of the view");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (0, 0)), (false, 1), "other artboards");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 0)), (false, 1), "a plug-in installed or removed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 1), "fonts installed");
|
||||
assert_eq!(art_to_fit_counted(&s, &[1], (1, 1)), (false, 0));
|
||||
}
|
||||
|
||||
/// A change made to the document in place (`Arc::make_mut`, with no other holder and no change
|
||||
/// of revision) is measured again: the kept answer holds the document it measured weakly, so a
|
||||
/// changed document is a new allocation, not the old address.
|
||||
#[test]
|
||||
fn art_to_fit_follows_a_change_in_place() {
|
||||
let mut s = row_of_artboards(2);
|
||||
box_at(&mut s, 10.0, 20.0);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (true, 1), "art on artboard 1");
|
||||
let st = s.doc_mut().unwrap();
|
||||
assert_eq!(Arc::strong_count(&st.doc), 1, "the undo history holds the document before the edit");
|
||||
let (revision, empty_spot) = (st.revision, st.doc.artboards[1].rect);
|
||||
Arc::make_mut(&mut st.doc).artboards[0].rect = empty_spot;
|
||||
assert_eq!(st.revision, revision);
|
||||
assert_eq!(art_to_fit_counted(&s, &[0], (0, 0)), (false, 1), "artboard 1 moved off the art");
|
||||
}
|
||||
|
||||
/// The enabled state follows an edit, an undo, a redo, an added and a removed artboard, a locked
|
||||
/// artboard, and each change measures the document once.
|
||||
#[test]
|
||||
|
||||
@@ -26,7 +26,15 @@ fn install_wat(s: &mut Session, src: &str) -> Value {
|
||||
install(s, &wat::parse_str(src).unwrap())
|
||||
}
|
||||
|
||||
/// A session started to take `grant` and `allowHeavy` from requests, as most tests here install.
|
||||
fn session() -> Session {
|
||||
let mut s = strict_session();
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s
|
||||
}
|
||||
|
||||
/// A session as MCP and the CLI have by default: `grant` and `allowHeavy` need an approval.
|
||||
fn strict_session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
s
|
||||
@@ -1338,6 +1346,506 @@ fn a_grant_covers_only_the_module_that_was_approved() {
|
||||
run(&mut s, "plugin.remove", json!({"id": exempt}));
|
||||
}
|
||||
|
||||
/// Installing a module that lists no permissions under a granted id forgets the grant, so the
|
||||
/// formerly approved bytes need a new approval. A refused install leaves the grant, and a module
|
||||
/// that lists permissions keeps replacing it as before.
|
||||
#[test]
|
||||
fn a_module_without_permissions_ends_the_grant_of_its_id() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let mut s = session();
|
||||
let id = "test.engine.permissions.replaced";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let granted = || vectorcraft_plugins::registry::granted(id).map(|g| g.hash);
|
||||
for permissions in ["null", "[]"] {
|
||||
let plain = vectorcraft_format::base64_encode(&asking(id, permissions, &empty));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
// Refused installs change nothing.
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain, "hash": "0".repeat(64), "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("SHA-256 `hash`"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain, "replace": false})).unwrap_err().to_string();
|
||||
assert!(e.contains("already installed"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": plain})).unwrap_err().to_string();
|
||||
assert!(e.contains("`replace: true`"), "{e}");
|
||||
assert_eq!(granted(), Some(sha256_hex(&approved)), "{permissions}: a refused install leaves the grant");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": plain, "replace": true}));
|
||||
assert_eq!(granted(), None, "{permissions}");
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "{permissions}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("`grant`"), "{permissions}: {e}");
|
||||
assert!(!vectorcraft_plugins::registry::get(id).unwrap().manifest().asks_permissions(), "{permissions}: the module installed stays");
|
||||
}
|
||||
// With no module installed under the id, the grant ends the same way.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&asking(id, "null", &empty))}));
|
||||
assert_eq!(granted(), None);
|
||||
// A module that lists permissions records its own grant.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
assert_eq!(granted(), Some(sha256_hex(&approved)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// In a plug-in store, a module that lists no permissions removes only its own id's entry from
|
||||
/// `grants.json`, and the formerly approved bytes need a new approval after a restart. A store
|
||||
/// that holds such a module and a grant for its id has that grant forgotten when it is attached.
|
||||
#[test]
|
||||
fn a_module_without_permissions_ends_the_grant_kept_in_the_store() {
|
||||
use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex};
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-stale-grant");
|
||||
let id = "test.engine.permissions.storedstale";
|
||||
let other = "test.engine.permissions.storedother";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let other_wasm = asking(other, r#"["doc.read"]"#, &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let ids = || -> Vec<String> {
|
||||
serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap())
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|e| e["id"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
};
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other_wasm), "grant": ["doc.read"]}));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
assert_eq!(ids().len(), 2);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(ids(), vec![other.to_string()], "only this id's entry goes");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
assert!(vectorcraft_plugins::registry::granted(other).is_some(), "the other plug-in's grant stays");
|
||||
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut next, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
|
||||
// A grant the store already holds for an id whose stored module lists no permissions.
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]});
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut third = session();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the module that lists nothing still loads");
|
||||
assert_eq!(ids(), vec![other.to_string()]);
|
||||
assert!(vectorcraft_plugins::registry::get(other).is_some());
|
||||
|
||||
// So does an entry this version can't read, and a grant held only by the process.
|
||||
let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]});
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
vectorcraft_plugins::registry::grant(Grant { id: id.into(), hash: sha256_hex(&approved), permissions: vec![Permission::DocRead] });
|
||||
let mut fourth = session();
|
||||
fourth.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(ids(), vec![other.to_string()]);
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
run(&mut fourth, "plugin.remove", json!({"id": id}));
|
||||
run(&mut fourth, "plugin.remove", json!({"id": other}));
|
||||
}
|
||||
|
||||
/// A module listing no permissions that can't be written to the plug-in store leaves the stored
|
||||
/// module in place, so `grants.json` keeps the grant that module needs at the next launch.
|
||||
#[test]
|
||||
fn a_failed_store_write_of_a_module_without_permissions_keeps_the_stored_grant() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-write-plain");
|
||||
let id = "test.engine.permissions.storefail";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let before = std::fs::read(&grants).unwrap();
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
std::fs::create_dir(&file).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), before, "the grant stays with the module left in the store");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing");
|
||||
|
||||
std::fs::remove_dir(&file).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A module listing no permissions whose id's grant can't be removed from `grants.json` doesn't stay
|
||||
/// in the store, so the grant and the module it covers stay together. It does stay when the module
|
||||
/// before it can't be read back, and when the grants file is too large or doesn't hold a list and so
|
||||
/// approves nothing.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_keeps_the_stored_module() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-forget");
|
||||
let id = "test.engine.permissions.forgetfail";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let replace = json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true});
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
// An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which
|
||||
// makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none(), "the process runs the module that lists nothing");
|
||||
|
||||
let oversized = vectorcraft_plugins::Limits::default().max_module_bytes as u64 + 1;
|
||||
std::fs::File::options().write(true).open(&file).unwrap().set_len(oversized).unwrap();
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a module that can't be read back can't be put back");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
let inspect = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
|
||||
assert_eq!(run(&mut s, "plugin.inspect", inspect)["needsApproval"], true, "the grant left behind stops counting");
|
||||
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
std::fs::write(&grants, b"not a list").unwrap();
|
||||
run(&mut s, "plugin.install", replace.clone());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file that isn't a list approves nothing");
|
||||
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
std::fs::write(&grants, vec![b' '; (1 << 20) + 1]).unwrap();
|
||||
run(&mut s, "plugin.install", replace);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "a grants file over its size limit approves nothing");
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant that can't be removed stops counting for the session when the module it covers can't be
|
||||
/// written back either: the store holds the new module, and the old bytes would otherwise install
|
||||
/// without approval.
|
||||
#[test]
|
||||
fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-put-back");
|
||||
let id = "test.engine.permissions.failedputback";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
crate::store::PUT_BACK_FAILS.set(true);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
crate::store::PUT_BACK_FAILS.set(false);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), plain, "the store keeps the new module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the grant left behind stops counting");
|
||||
let refused = s.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(refused.contains("doc.read"), "{refused}");
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An entry of `grants.json` that this version can't use is kept for a version that can, so when it
|
||||
/// can't be removed, neither `plugin.remove` nor a replacing module gets past it.
|
||||
#[test]
|
||||
fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-remove-other");
|
||||
let id = "test.engine.permissions.removeother";
|
||||
let empty = json!({"objects": []});
|
||||
let first = asking(id, "null", &empty);
|
||||
let second = asking(id, "[]", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&first)}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]});
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), first, "the store keeps the module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&second), "replace": true}));
|
||||
assert_eq!(std::fs::read(&file).unwrap(), first, "the store gets its module back");
|
||||
|
||||
std::fs::write(&grants, serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the removal takes the entry out of the file");
|
||||
}
|
||||
|
||||
/// A grant that can't be removed when no module is stored for its id has no module to go with, so
|
||||
/// it stops counting for the session.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-grant-no-module");
|
||||
let id = "test.engine.permissions.forgetnomodule";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&std::fs::read(&grants).unwrap()).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert!(!std::path::Path::new(&file).exists(), "the store keeps no module");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for
|
||||
/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load.
|
||||
/// A grant recorded later counts again, and another store starts with nothing ignored.
|
||||
#[test]
|
||||
fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-load-forget");
|
||||
let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other");
|
||||
let id = "test.engine.permissions.loadforget";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let needs_approval = json!({"dataBase64": approved_data});
|
||||
let grants = folder.0.join("grants.json");
|
||||
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
|
||||
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
|
||||
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full, "the load can't rewrite the file");
|
||||
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], true);
|
||||
let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(refused.contains("doc.read"), "{refused}");
|
||||
|
||||
std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
|
||||
next.attach_plugin_store(elsewhere.0.clone());
|
||||
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
|
||||
|
||||
// A directory at the file's path gives a read error on every platform.
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
std::fs::create_dir(&grants).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut third = session();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
std::fs::remove_dir(&grants).unwrap();
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count");
|
||||
|
||||
// Attaching the same store again, with no stored module to try the removal for, keeps it out.
|
||||
let file = third.stored_plugin_file(id).unwrap();
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
third.attach_plugin_store(folder.0.clone());
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the same store's grant stays out");
|
||||
|
||||
// A later load in the session doesn't count it either, for the bytes it covers.
|
||||
std::fs::write(&file, &approved).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
third.load_stored_plugins();
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded");
|
||||
|
||||
run(&mut third, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"], "replace": true}));
|
||||
assert_eq!(run(&mut third, "plugin.inspect", needs_approval)["needsApproval"], false, "the user granted it again");
|
||||
run(&mut third, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A grants file that can't be opened or read may name the old module once it reads again, so
|
||||
/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the
|
||||
/// file's path gives a read error on every platform.
|
||||
#[test]
|
||||
fn a_grants_file_that_cannot_be_read_keeps_the_grant_and_the_module_it_covers() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-unread-grants");
|
||||
let id = "test.engine.permissions.unreadgrants";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
std::fs::remove_file(&grants).unwrap();
|
||||
std::fs::create_dir(&grants).unwrap();
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"], "replace": true}));
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module");
|
||||
|
||||
std::fs::remove_dir(&grants).unwrap();
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the file reads again and the grant goes");
|
||||
}
|
||||
|
||||
/// `plugin.remove` returns an error and keeps the plug-in when its grant can't be removed from
|
||||
/// `grants.json`; a second one tries again. A grants file that doesn't hold a list doesn't stop it.
|
||||
#[test]
|
||||
fn a_grant_that_cannot_be_removed_stops_plugin_remove() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-remove");
|
||||
let id = "test.engine.permissions.removefail";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&recorded).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
let data = crate::store::plugin_data_dir(&folder.0, id);
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(data.join("settings.json"), b"{}").unwrap();
|
||||
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "it keeps its grant");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store keeps the module the grant covers");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), full);
|
||||
assert!(data.join("settings.json").is_file(), "it keeps its settings");
|
||||
|
||||
// Settings that can't be moved aside leave the grant recorded. A file at the aside path stops
|
||||
// the move on Unix, and a file held open in the folder stops it on Windows.
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
let mut aside = data.clone().into_os_string();
|
||||
aside.push(".removed");
|
||||
let aside = std::path::PathBuf::from(aside);
|
||||
std::fs::write(&aside, b"in the way").unwrap();
|
||||
#[cfg(windows)]
|
||||
let held = {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
std::fs::File::options().read(true).share_mode(1).open(data.join("settings.json")).unwrap()
|
||||
};
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
#[cfg(windows)]
|
||||
drop(held);
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays while the settings do");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some());
|
||||
let _ = std::fs::remove_file(&aside);
|
||||
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!grants.exists(), "the second removal forgets the grant");
|
||||
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
std::fs::write(&grants, b"not a list").unwrap();
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none(), "a grants file that isn't a list approves nothing");
|
||||
assert!(!std::path::Path::new(&file).exists());
|
||||
}
|
||||
|
||||
/// Windows keeps a file another program holds open without delete sharing, so the last grant can't
|
||||
/// be removed by deleting `grants.json`.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_SHARE_READ: u32 = 1;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-held-grants");
|
||||
let id = "test.engine.permissions.heldgrants";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let file = s.stored_plugin_file(id).unwrap();
|
||||
|
||||
let held = std::fs::File::options().read(true).share_mode(FILE_SHARE_READ).open(&grants).unwrap();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true}));
|
||||
drop(held);
|
||||
assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back");
|
||||
assert!(grants.exists());
|
||||
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in folder that leaves a module listing no permissions under an id forgets the process's
|
||||
/// grant for it, unless a later file in the folder leaves a granted module there. A grant kept in
|
||||
/// the plug-in store stays, with the stored module it covers.
|
||||
#[test]
|
||||
fn a_plugin_folder_ends_the_process_grant_of_an_id_it_replaces() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.permissions.folderstale";
|
||||
let empty = json!({"objects": []});
|
||||
let approved = asking(id, r#"["doc.read"]"#, &empty);
|
||||
let approved_data = vectorcraft_format::base64_encode(&approved);
|
||||
let plain = asking(id, "null", &empty);
|
||||
let dir = crate::tests_links::Folder::new("plugin-folder-stale-grant");
|
||||
std::fs::write(dir.0.join("a-plain.wasm"), &plain).unwrap();
|
||||
std::fs::write(dir.0.join("b-approved.wasm"), &approved).unwrap();
|
||||
let path = json!({"path": dir.0.display().to_string()});
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
|
||||
let r = run(&mut s, "plugin.reload", path.clone());
|
||||
assert_eq!(r["failed"], json!([]), "{r}");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "the granted module is the one left");
|
||||
|
||||
std::fs::remove_file(dir.0.join("b-approved.wasm")).unwrap();
|
||||
let r = run(&mut s, "plugin.reload", path.clone());
|
||||
assert_eq!(r["loaded"], json!([id]), "{r}");
|
||||
assert!(vectorcraft_plugins::registry::granted(id).is_none());
|
||||
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
|
||||
let store = crate::tests_links::Folder::new("plugin-folder-stale-grant-store");
|
||||
let mut stored = session();
|
||||
stored.attach_plugin_store(store.0.clone());
|
||||
run(&mut stored, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]}));
|
||||
let grants = store.0.join("grants.json");
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
run(&mut stored, "plugin.reload", path);
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the store still holds the module its grant covers");
|
||||
assert_eq!(run(&mut stored, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false);
|
||||
run(&mut stored, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A stored module whose bytes changed is skipped at the next start and stays in the store with its
|
||||
/// grant, and the original bytes load again. A stored grant whose hash is malformed covers nothing.
|
||||
/// With a store attached, a matching grant held only by the process doesn't count.
|
||||
@@ -1639,6 +2147,69 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
|
||||
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
|
||||
}
|
||||
|
||||
/// A run past its memory budget fails before the plug-in starts, with the document and undo
|
||||
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
|
||||
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
|
||||
/// with none. The module has one page of memory, the most it may have, so a run that started would
|
||||
/// report that the plug-in ran out of memory instead.
|
||||
#[test]
|
||||
fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeKind};
|
||||
use vectorcraft_geom::FillRule;
|
||||
use vectorcraft_plugins::{Limits, Plugin, registry};
|
||||
let id = "test.engine.inputs.budget";
|
||||
let params: Vec<String> = (0..9).map(|i| format!(r#""p{i}":{{"type":"string","maxLength":4096}}"#)).collect();
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Budget","kind":"filter","api":2,"permissions":["doc.read","doc.write"],"inputs":["type"],"params":{{{}}}}}"#,
|
||||
params.join(",")
|
||||
);
|
||||
let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap();
|
||||
// One page of memory: the input and the parameters share 32 KiB.
|
||||
registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap());
|
||||
let mut s = session();
|
||||
let small = rect(&mut s, 10.0, "#ff0000");
|
||||
let long = rect(&mut s, 30.0, "#00ff00");
|
||||
let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap());
|
||||
let mut compound = NodeId(0);
|
||||
s.edit("Set up", |d, _| {
|
||||
d.node_mut(t).unwrap().name = Some("n".repeat(40_000));
|
||||
let points: Vec<Point> = (0..4_000).map(|i| Point::new(f64::from(i), 0.0)).collect();
|
||||
let outline = PathData::single(SubPath::polyline(&points, false));
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(long).unwrap().kind {
|
||||
*path = outline.clone();
|
||||
}
|
||||
let member = Node::path(d.alloc_id(), outline, Appearance::default());
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: FillRule::NonZero });
|
||||
let layer = d.layers[0].id;
|
||||
compound = d.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let padding: Value = (0..9).map(|i| (format!("p{i}"), json!("x".repeat(4096)))).collect::<serde_json::Map<_, _>>().into();
|
||||
let too_large = "memory budget (the selection is too large to hand over)";
|
||||
let named = format!("memory budget (object {} needs", t.0);
|
||||
let with_padding = |ids: Vec<u64>| {
|
||||
let mut p = padding.clone();
|
||||
p["id"] = json!(id);
|
||||
p["ids"] = json!(ids);
|
||||
p
|
||||
};
|
||||
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
for (p, says) in [
|
||||
(json!({"id": id, "ids": [t.0]}), named.as_str()),
|
||||
(json!({"id": id, "ids": [long.0]}), too_large),
|
||||
(json!({"id": id, "ids": [compound.0]}), too_large),
|
||||
(with_padding(vec![small.0]), too_large),
|
||||
(with_padding(vec![]), too_large),
|
||||
] {
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{says}: {e}");
|
||||
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}");
|
||||
}
|
||||
assert!(registry::remove(id));
|
||||
}
|
||||
|
||||
/// What the user granted is kept in the plug-in store with the module: the next session installs
|
||||
/// the plug-in again without asking. A stored plug-in that lists permissions nobody granted it is
|
||||
/// skipped, even when another store granted it, and so is one in the Additional Plug-ins Folder
|
||||
@@ -1979,6 +2550,132 @@ fn a_level_2_filter_installs_with_progress_granted_and_reports_to_the_caller() {
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// An approval of the module `wasm` with id `id`, its `permissions` and, if `heavy`, its budget.
|
||||
fn approval(id: &str, wasm: &[u8], permissions: &[&str], heavy: bool) -> crate::cmd::plugin::InstallApproval {
|
||||
crate::cmd::plugin::InstallApproval {
|
||||
id: id.into(),
|
||||
hash: vectorcraft_plugins::permissions::sha256_hex(wasm),
|
||||
permissions: permissions.iter().map(|p| p.to_string()).collect(),
|
||||
heavy,
|
||||
}
|
||||
}
|
||||
|
||||
/// In a session that wasn't started to accept them, `grant` and `allowHeavy` are refused whichever
|
||||
/// way the command runs, a batch included, until an approval covers the module, its id, SHA-256 and
|
||||
/// permissions. An approval is spent by the first install, whatever it does. A hash already approved
|
||||
/// still installs.
|
||||
#[test]
|
||||
fn a_request_cannot_grant_what_only_a_person_approves() {
|
||||
let mut s = strict_session();
|
||||
let id = "test.engine.approval";
|
||||
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&wasm);
|
||||
let refused = "take effect only in a session started with --allow-plugin-grants";
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve them in the desktop app") && e.contains("--allow-plugin-grants"), "{e}");
|
||||
let batch = json!({"commands": [{"command": "plugin.install", "params": {"dataBase64": data, "grant": ["doc.read"]}}]});
|
||||
let e = s.execute("command.batch", &batch).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "a batch can't grant: {e}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
|
||||
// Approved for other bytes, for another id or for other permissions: refused, and spent.
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]}));
|
||||
for wrong in [
|
||||
approval(id, &other, &["doc.read"], false),
|
||||
approval("test.engine.approval.other", &wasm, &["doc.read"], false),
|
||||
approval(id, &wasm, &["doc.read", "state"], false),
|
||||
] {
|
||||
s.approve_plugin_install(wrong);
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
}
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
|
||||
// The approval for this module installs it once.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.hash), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "the approval was spent: {e}");
|
||||
// A hash already approved installs without one.
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
|
||||
// A refused install spends the approval too.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"], "hash": "0"})).unwrap_err().to_string();
|
||||
assert!(e.contains("SHA-256"), "{e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
// So does one refused for its params.
|
||||
s.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
s.execute("plugin.install", &json!({"dataBase64": data, "grant": "doc.read"})).unwrap_err();
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
|
||||
// The heavy budget needs its own agreement.
|
||||
let heavy_id = "test.engine.approval.heavy";
|
||||
let heavy_wasm = heavy(heavy_id, 1);
|
||||
let heavy_data = vectorcraft_format::base64_encode(&heavy_wasm);
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "{e}");
|
||||
// Without a `permissions` list it has the ones its kind implies.
|
||||
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": heavy_data}));
|
||||
let implied: Vec<&str> = inspected["permissions"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, false));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data, "allowHeavy": true})).unwrap_err().to_string();
|
||||
assert!(e.contains(refused), "an approval without the heavy budget doesn't cover it: {e}");
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": heavy_data})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve it in the desktop app"), "{e}");
|
||||
s.approve_plugin_install(approval(heavy_id, &heavy_wasm, &implied, true));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": heavy_data, "allowHeavy": true}));
|
||||
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
|
||||
|
||||
// A session started to accept them takes them from requests.
|
||||
s.allow_plugin_grants_from_requests();
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A module a person approved in the desktop app, recorded in the store's `grants.json`, installs
|
||||
/// from another session with that store and no flag and no `grant`. Other bytes under its id are
|
||||
/// refused there, with or without `grant`.
|
||||
#[test]
|
||||
fn a_module_approved_in_the_app_installs_from_a_strict_session_with_its_store() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-approval-store");
|
||||
let id = "test.engine.approval.store";
|
||||
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&wasm);
|
||||
let mut desktop = strict_session();
|
||||
desktop.attach_plugin_store(folder.0.clone());
|
||||
desktop.approve_plugin_install(approval(id, &wasm, &["doc.read"], false));
|
||||
run(&mut desktop, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert!(std::fs::read_to_string(folder.0.join("grants.json")).unwrap().contains(id), "recorded in the store");
|
||||
|
||||
// Another process starts with an empty registry and the store's grants.
|
||||
let forget = || {
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
};
|
||||
forget();
|
||||
let mut headless = strict_session();
|
||||
headless.attach_plugin_store(folder.0.clone());
|
||||
forget();
|
||||
run(&mut headless, "plugin.install", json!({"dataBase64": data}));
|
||||
assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
|
||||
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [{"name": "x"}]}));
|
||||
let other_data = vectorcraft_format::base64_encode(&other);
|
||||
let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("approve them in the desktop app"), "{e}");
|
||||
let e = headless.execute("plugin.install", &json!({"dataBase64": other_data, "replace": true, "grant": ["doc.read"]})).unwrap_err().to_string();
|
||||
assert!(e.contains("take effect only in a session started with --allow-plugin-grants"), "{e}");
|
||||
assert_eq!(vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), Some(vectorcraft_plugins::permissions::sha256_hex(&wasm)));
|
||||
run(&mut headless, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A filter run the caller cancels (MCP's `notifications/cancelled`, the app's Cancel) stops between
|
||||
/// two slices of its budget and changes nothing.
|
||||
#[test]
|
||||
@@ -2441,7 +3138,7 @@ fn plugin_storage_is_capped_and_survives_a_damaged_settings_file() {
|
||||
assert_eq!(st.set_cache_entry("tile", b"again", m), Err(StorageError::Unavailable));
|
||||
assert!(!dir.exists());
|
||||
assert_eq!(upper.setting("k0", m).unwrap(), Some(b"upper".to_vec()));
|
||||
s.remove_plugin_storage(upper_id).unwrap();
|
||||
s.remove_plugin_storage(upper_id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// Files larger than the storage reads are not read: a settings file larger than 1 MiB, although
|
||||
@@ -2624,7 +3321,7 @@ fn removing_a_plugin_drops_its_settings_from_memory() {
|
||||
let mut m = Meter::unlimited();
|
||||
assert_eq!(st.setting("zoom", &mut m).unwrap(), Some(b"hello".to_vec()));
|
||||
assert_eq!(m.used(), bytes.len() as u64, "read from the file");
|
||||
s.remove_plugin_storage(id).unwrap();
|
||||
s.remove_plugin_storage(id, || true).unwrap();
|
||||
}
|
||||
|
||||
/// The cache's total stays in memory while the cache folder keeps its time; a write and a clear
|
||||
|
||||
@@ -199,6 +199,110 @@ fn reset_category_and_all() {
|
||||
assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err());
|
||||
}
|
||||
|
||||
/// A rectangle made into a guide path; nothing is selected after.
|
||||
fn guide_path(s: &mut Session, x: f64) -> NodeId {
|
||||
let id = square(s, x, 0.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Lock Guides by Default is off, and preferences saved before it existed leave guides unlocked.
|
||||
#[test]
|
||||
fn lock_guides_by_default_is_off_and_older_preferences_leave_guides_unlocked() {
|
||||
assert!(!Prefs::default().lock_guides_by_default);
|
||||
let older: Prefs = serde_json::from_value(json!({"keyboardIncrement": 4})).unwrap();
|
||||
assert!(!older.lock_guides_by_default);
|
||||
let mut s = Session::new();
|
||||
s.apply_prefs(older);
|
||||
assert!(!s.guides_locked());
|
||||
assert!(s.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": "yes"})).is_err());
|
||||
assert!(!s.guides_locked() && !s.prefs.lock_guides_by_default);
|
||||
}
|
||||
|
||||
/// Preferences saved with the option on start a session with guides locked. A document opened in
|
||||
/// it has its ruler guides and guide paths locked, and new guides can still be made. View › Guides
|
||||
/// › Lock Guides then unlocks them for the session and leaves the preference on.
|
||||
#[test]
|
||||
fn saved_lock_guides_by_default_locks_a_new_session_and_the_documents_it_opens() {
|
||||
let file = std::env::temp_dir().join(format!("vc-lock-guides-{}.vectorcraft", std::process::id()));
|
||||
let file = file.to_string_lossy().to_string();
|
||||
let mut unlocked = new_doc();
|
||||
assert!(!unlocked.guides_locked(), "a session without the preference");
|
||||
let path = guide_path(&mut unlocked, 100.0);
|
||||
unlocked.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
unlocked.execute("document.save", &json!({"path": file})).unwrap();
|
||||
|
||||
// The preference is set with no document open, as a headless session can.
|
||||
let mut first = Session::new();
|
||||
first.execute("prefs.set", &json!({"key": "lockGuidesByDefault", "value": true})).unwrap();
|
||||
let saved = first.prefs.to_json();
|
||||
assert_eq!(saved["lockGuidesByDefault"], json!(true));
|
||||
|
||||
let mut s = Session::new();
|
||||
s.apply_prefs(serde_json::from_value(saved).unwrap());
|
||||
assert!(s.guides_locked());
|
||||
s.execute("document.open", &json!({"path": file})).unwrap();
|
||||
let _ = std::fs::remove_file(&file);
|
||||
assert!(s.guides_locked(), "opening a document keeps the lock");
|
||||
assert!(matches!(s.execute("guide.select", &json!({"indexes": [0]})), Err(EngineError::Disabled(..))));
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "a guide path can't be selected");
|
||||
assert_eq!(s.execute("guide.add", &json!({"vertical": false, "pos": 20})).unwrap()["index"], 1);
|
||||
|
||||
assert_eq!(s.execute("view.guides.lock", &json!({})).unwrap(), json!({"locked": false}));
|
||||
assert!(s.prefs.lock_guides_by_default, "the menu leaves the preference as it is");
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, [path]);
|
||||
}
|
||||
|
||||
/// Changing the preference sets the lock at once and deselects guides in every open document.
|
||||
/// A change to any other preference, or setting it to the value it has, keeps the session's lock.
|
||||
#[test]
|
||||
fn changing_lock_guides_by_default_sets_the_lock_and_other_changes_keep_it() {
|
||||
let mut s = new_doc();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let path = guide_path(&mut s, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [path.0]})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(s.guides_locked());
|
||||
assert!(s.doc().unwrap().selection.objects.is_empty(), "the guide path in the active document");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
assert!(s.doc().unwrap().selection.guides.is_empty(), "the ruler guide in the other document");
|
||||
|
||||
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
|
||||
set_pref(&mut s, "keyboardIncrement", json!(4));
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(!s.guides_locked(), "the session's unlock stays");
|
||||
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(false));
|
||||
assert!(!s.guides_locked(), "turning the preference off unlocks guides");
|
||||
}
|
||||
|
||||
/// Reset turns the option off and unlocks guides. With the option already off, a reset keeps a
|
||||
/// lock set from the View menu.
|
||||
#[test]
|
||||
fn resetting_lock_guides_by_default_unlocks_guides_only_when_it_was_on() {
|
||||
let mut s = new_doc();
|
||||
for params in [json!({"category": "Guides & Grid"}), json!({})] {
|
||||
set_pref(&mut s, "lockGuidesByDefault", json!(true));
|
||||
assert!(s.guides_locked());
|
||||
s.execute("prefs.reset", ¶ms).unwrap();
|
||||
assert!(!s.prefs.lock_guides_by_default, "{params}");
|
||||
assert!(!s.guides_locked(), "{params}");
|
||||
}
|
||||
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert!(s.guides_locked());
|
||||
}
|
||||
|
||||
/// `prefs.set` refuses a recovery or plug-ins folder that is missing or is a file. Nothing changes,
|
||||
/// other values in the same call included, and the document gets no undo step.
|
||||
#[test]
|
||||
|
||||
@@ -618,6 +618,77 @@ fn set_bounds_leaves_the_height_of_lines_with_no_height() {
|
||||
assert!(close(geometric(&s, ids[1]), Rect::new(8.3, 100.0, 30.0, 100.0)), "{:?}", geometric(&s, ids[1]));
|
||||
}
|
||||
|
||||
/// A line with a 2 pt stroke and butt caps, selected, with Use Preview Bounds on.
|
||||
fn butt_line(s: &mut Session, from: (f64, f64), to: (f64, f64)) -> NodeId {
|
||||
let id = NodeId(run(s, "shape.line", json!({"x1": from.0, "y1": from.1, "x2": to.0, "y2": to.1}))["id"].as_u64().unwrap());
|
||||
run(s, "stroke.set", json!({"weight": 2, "cap": "butt"}));
|
||||
preview(s, true);
|
||||
run(s, "select.set", json!({"ids": [id.0]}));
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_butt_line_the_whole_height() {
|
||||
// A butt cap ends at the anchor, so 10 mm (28.3465 pt) is the length of the line itself.
|
||||
let mut s = session();
|
||||
let id = butt_line(&mut s, (100.0, 100.0), (100.0, 140.0));
|
||||
assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 140.0)), "{:?}", s.transform_bounds(&[id]));
|
||||
run(&mut s, "object.setBounds", json!({"height": 28.3465, "reference": 0, "strokes": false}));
|
||||
assert!(close(geometric(&s, id), Rect::new(100.0, 100.0, 100.0, 128.3465)), "{:?}", geometric(&s, id));
|
||||
assert!(close(s.transform_bounds(&[id]).unwrap(), Rect::new(99.0, 100.0, 101.0, 128.3465)), "{:?}", s.transform_bounds(&[id]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_diagonal_butt_line_the_size_out_of_proportion() {
|
||||
// The stroke's corners follow the line's slope, which a scale out of proportion changes.
|
||||
let mut s = session();
|
||||
let id = butt_line(&mut s, (100.0, 100.0), (130.0, 140.0));
|
||||
let before = s.transform_bounds(&[id]).unwrap();
|
||||
// The stroke's corners reach 0.8 pt across x and 0.6 pt across y at this 3-4-5 slope.
|
||||
assert!(close(before, Rect::new(99.2, 99.4, 130.8, 140.6)), "{before:?}");
|
||||
run(&mut s, "object.setBounds", json!({"height": 100, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.height() - 100.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_butt_path_with_slanted_corners_the_size_out_of_proportion() {
|
||||
// Square ends, but the bevel join at the apex sets the top edge by the slanted segments'
|
||||
// corners, which a scale out of proportion moves.
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 100, "y": 150}, {"x": 100, "y": 140}, {"x": 110, "y": 100}, {"x": 120, "y": 140}, {"x": 120, "y": 150}]);
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "stroke.set", json!({"weight": 2, "cap": "butt", "join": "bevel"}));
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.width() - 60.0).abs() < 1e-6 && (v.height() - 20.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() {
|
||||
let mut s = session();
|
||||
butt_line(&mut s, (100.0, 100.0), (130.0, 140.0));
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Line"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 20, "height": 100, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
assert!((v.width() - 20.0).abs() < 1e-6 && (v.height() - 100.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_places_a_vertical_butt_line_by_its_end_points() {
|
||||
// With Use Preview Bounds on, a butt line's ends line up with the top of a rectangle without
|
||||
// a stroke.
|
||||
let mut s = session();
|
||||
rect(&mut s, 20.0, 50.0, 0.0);
|
||||
let id = butt_line(&mut s, (200.0, 160.0), (200.0, 190.0));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "object.align", json!({"vertical": "top"}));
|
||||
assert!(close(geometric(&s, id), Rect::new(200.0, 100.0, 200.0, 130.0)), "{:?}", geometric(&s, id));
|
||||
}
|
||||
|
||||
/// The rectangles of [`thin_and_thick`] in a group, the thick one in a group of its own inside it
|
||||
/// when `nested`, selected with an unstroked rectangle from x 100 to 110 when `plain`. Returns the
|
||||
/// selected objects.
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
//! Edit → Spelling (`text.spelling.check`, `text.spelling.suggest`): the unknown words of the
|
||||
//! document's type, at the bytes `text.editRange` changes, each in its run's language.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::cmd::spelling::MAX_DICTIONARY_FILE_BYTES;
|
||||
use crate::*;
|
||||
|
||||
/// Held by each test that changes the custom dictionary, which the whole process shares: a save
|
||||
/// writes every word in it to the test's file and a reload takes the file's words back, so another
|
||||
/// test's word could come back after that test deleted it.
|
||||
fn dictionary_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A session with a new 400 × 400 document.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Runs a command that must succeed and gives its result.
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap()
|
||||
}
|
||||
|
||||
/// New point type at (10, `y`) holding `t`.
|
||||
fn text(s: &mut Session, y: f64, t: &str) -> NodeId {
|
||||
NodeId(run(s, "text.create", json!({"x": 10, "y": y, "text": t}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// The unknown words a check lists: (id, start, end, word).
|
||||
fn unknown(s: &mut Session, p: Value) -> Vec<(u64, u64, u64, String)> {
|
||||
let r = run(s, "text.spelling.check", p);
|
||||
assert_eq!(r["more"], false);
|
||||
r["words"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["end"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_lists_unknown_words_at_the_bytes_edit_range_changes() {
|
||||
let mut s = session();
|
||||
// "—" is three bytes, so the unknown word starts at byte 12, not character 10. Punctuation,
|
||||
// not a word, so the result doesn't depend on which dictionary is built in.
|
||||
let t = text(&mut s, 50.0, "drawing — qzxvw tools");
|
||||
assert_eq!(unknown(&mut s, json!({})), [(t.0, 12, 17, "qzxvw".to_string())]);
|
||||
let w = &run(&mut s, "text.spelling.check", json!({}))["words"][0];
|
||||
assert_eq!(w["lang"], "en", "text with no language is checked in English");
|
||||
// Change: the bytes the check gave, as one undo step.
|
||||
run(&mut s, "text.editRange", json!({"id": t.0, "start": 12, "end": 17, "insert": "vector"}));
|
||||
assert_eq!(unknown(&mut s, json!({})), []);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(unknown(&mut s, json!({})).len(), 1, "undo brings the word back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_goes_through_visible_unlocked_type_in_paint_order_or_the_ids_given() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "first qzxvw");
|
||||
let b = text(&mut s, 100.0, "second wvxzq");
|
||||
let hidden = text(&mut s, 150.0, "hidden qqzzx");
|
||||
let locked = text(&mut s, 200.0, "locked zzqqx");
|
||||
run(&mut s, "object.hide", json!({"ids": [hidden.0]}));
|
||||
run(&mut s, "object.lock", json!({"ids": [locked.0]}));
|
||||
let ids: Vec<u64> = unknown(&mut s, json!({})).iter().map(|w| w.0).collect();
|
||||
assert_eq!(ids, [a.0, b.0], "hidden and locked type are left out");
|
||||
assert_eq!(unknown(&mut s, json!({"ids": [b.0]})), [(b.0, 7, 12, "wvxzq".to_string())]);
|
||||
assert_eq!(unknown(&mut s, json!({"ids": null})).len(), 2, "null ids is the default");
|
||||
let both = [(a.0, 6, 11, "qzxvw".to_string()), (b.0, 7, 12, "wvxzq".to_string())];
|
||||
assert_eq!(unknown(&mut s, json!({"ids": [b.0, a.0]})), both, "given ids are listed in paint order too");
|
||||
for ids in [json!(b.0), json!("all"), json!({"id": b.0}), json!([-1]), json!(["x"]), json!([999_999])] {
|
||||
assert!(s.execute("text.spelling.check", &json!({"ids": ids})).is_err(), "malformed ids {ids} is refused");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_language_without_a_dictionary_marks_nothing() {
|
||||
let mut s = session();
|
||||
let t = text(&mut s, 50.0, "qzxvw");
|
||||
run(&mut s, "text.setFormat", json!({"ids": [t.0], "language": "German"}));
|
||||
assert_eq!(unknown(&mut s, json!({})), [], "German has no spelling dictionary in craft-proof");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suggest_offers_dictionary_words() {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "text.spelling.suggest", json!({"word": "drawng"}));
|
||||
let got: Vec<&str> = r["suggestions"].as_array().unwrap().iter().map(|w| w.as_str().unwrap()).collect();
|
||||
assert!(got.len() <= 5, "five at most by default: {got:?}");
|
||||
assert!(got.contains(&"drawing"), "{got:?}");
|
||||
assert_eq!(run(&mut s, "text.spelling.suggest", json!({"word": "drawng", "max": 1}))["suggestions"].as_array().unwrap().len(), 1);
|
||||
assert!(s.execute("text.spelling.suggest", &json!({})).is_err(), "a word is required");
|
||||
assert!(s.execute("text.spelling.suggest", &json!({"word": " "})).is_err(), "a blank word is refused");
|
||||
for max in [json!(0), json!(21), json!(-1), json!("3")] {
|
||||
assert!(s.execute("text.spelling.suggest", &json!({"word": "drawng", "max": max})).is_err(), "max {max}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_paragraph_is_checked_on_its_own_at_the_bytes_of_the_whole_text() {
|
||||
let mut s = session();
|
||||
// Read as one block, the Vietnamese first paragraph would make the whole text Vietnamese,
|
||||
// which has no dictionary, and the English typo below it would go unmarked.
|
||||
let vi = "Cảm ơn những người bạn";
|
||||
let t = text(&mut s, 50.0, &format!("{vi}\ndrawing qzxvw tools"));
|
||||
let at = vi.len() + 1 + "drawing ".len();
|
||||
assert_eq!(unknown(&mut s, json!({})), [(t.0, at as u64, at as u64 + 5, "qzxvw".to_string())]);
|
||||
}
|
||||
|
||||
// The custom dictionary is craft-proof's, shared by the whole process, so each test below uses
|
||||
// made-up words of its own: tests running at the same time never see each other's.
|
||||
|
||||
/// The words a check of the whole active document lists.
|
||||
fn marked(s: &mut Session) -> Vec<String> {
|
||||
unknown(s, json!({})).into_iter().map(|w| w.3).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_words_are_right_in_every_check_until_deleted() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "drawing Zqvwkx tools");
|
||||
assert_eq!(marked(&mut s), ["Zqvwkx"]);
|
||||
// Kept in lower case, so the capitalized word is right too.
|
||||
let r = run(&mut s, "text.spelling.addWord", json!({"word": " Zqvwkx "}));
|
||||
assert_eq!((r["word"].as_str(), r["added"].as_bool()), (Some("zqvwkx"), Some(true)));
|
||||
assert_eq!(marked(&mut s), Vec::<String>::new());
|
||||
assert_eq!(run(&mut s, "text.spelling.addWord", json!({"word": "zqvwkx"}))["added"], false, "already there");
|
||||
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
|
||||
assert!(words.as_array().unwrap().contains(&json!("zqvwkx")), "{words}");
|
||||
// Another document's check takes it as right too.
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
text(&mut s, 50.0, "zqvwkx");
|
||||
assert_eq!(marked(&mut s), Vec::<String>::new());
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "ZQVWKX"}));
|
||||
assert_eq!(marked(&mut s), ["zqvwkx"]);
|
||||
let e = s.execute("text.spelling.removeWord", &json!({"word": "zqvwkx"})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't in the custom dictionary"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_word_replaces_the_old_one() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "xkvzqa xkvzqb");
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "xkvzqa"}));
|
||||
assert_eq!(marked(&mut s), ["xkvzqb"]);
|
||||
assert_eq!(run(&mut s, "text.spelling.changeWord", json!({"word": "xkvzqa", "to": "Xkvzqb"}))["word"], "xkvzqb");
|
||||
assert_eq!(marked(&mut s), ["xkvzqa"]);
|
||||
let e = s.execute("text.spelling.changeWord", &json!({"word": "xkvzqa", "to": "x"})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't in the custom dictionary"), "{e}");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "xkvzqb"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_custom_dictionary_file_is_read_and_kept_up_to_date() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-dictionary");
|
||||
let file = dir.join("Custom Dictionary.txt");
|
||||
std::fs::write(&file, "kqzvwx\nnot one word\n\n").unwrap();
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(file.clone());
|
||||
text(&mut s, 50.0, "kqzvwx vkqzwx");
|
||||
assert_eq!(marked(&mut s), ["vkqzwx"], "the file's word is right; its line of three words is skipped");
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "vkqzwx"}));
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(saved.lines().any(|l| l == "kqzvwx") && saved.lines().any(|l| l == "vkqzwx"), "{saved}");
|
||||
run(&mut s, "text.spelling.changeWord", json!({"word": "kqzvwx", "to": "kqzvwy"}));
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "vkqzwx"}));
|
||||
let saved = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(saved.lines().any(|l| l == "kqzvwy"), "{saved}");
|
||||
assert!(!saved.lines().any(|l| l == "kqzvwx" || l == "vkqzwx"), "changed and deleted words are gone from the file: {saved}");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "kqzvwy"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_all_skips_a_word_in_the_active_document_only() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
text(&mut s, 50.0, "Wqzxkv drawing wqzxkv vqzxkw");
|
||||
run(&mut s, "text.spelling.ignoreAll", json!({"word": "WQZXKV"}));
|
||||
assert_eq!(marked(&mut s), ["vqzxkw"], "every occurrence, whatever its case");
|
||||
let words = run(&mut s, "text.spelling.dictionary", json!({}))["words"].clone();
|
||||
assert!(!words.as_array().unwrap().contains(&json!("wqzxkv")), "not added to the custom dictionary");
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
text(&mut s, 50.0, "wqzxkv");
|
||||
assert_eq!(marked(&mut s), ["wqzxkv"], "another document still marks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_dictionary_commands_refuse_what_isnt_one_word() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
let long = "q".repeat(65);
|
||||
for (id, p) in [
|
||||
("text.spelling.addWord", json!({})),
|
||||
("text.spelling.addWord", json!({"word": " "})),
|
||||
("text.spelling.addWord", json!({"word": "two words"})),
|
||||
("text.spelling.addWord", json!({"word": long})),
|
||||
("text.spelling.addWord", json!({"word": 5})),
|
||||
("text.spelling.removeWord", json!({})),
|
||||
("text.spelling.changeWord", json!({"word": "qzx"})),
|
||||
("text.spelling.changeWord", json!({"word": "qzx", "to": "a b"})),
|
||||
("text.spelling.ignoreAll", json!({"word": "a\tb"})),
|
||||
] {
|
||||
assert!(s.execute(id, &p).is_err(), "{id} {p} is refused");
|
||||
}
|
||||
let mut empty = Session::new();
|
||||
assert!(empty.execute("text.spelling.ignoreAll", &json!({"word": "qzx"})).is_err(), "Ignore All needs a document");
|
||||
assert!(empty.execute("text.spelling.dictionary", &json!({})).is_ok(), "the dictionary is the app's");
|
||||
}
|
||||
|
||||
/// Whether the custom dictionary holds `word`.
|
||||
fn in_dictionary(s: &mut Session, word: &str) -> bool {
|
||||
run(s, "text.spelling.dictionary", json!({}))["words"].as_array().unwrap().contains(&json!(word))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dictionary_file_that_cant_be_read_whole_is_never_written_over() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-unreadable");
|
||||
// A folder where the file should be can't be read as one; a file past what craft-proof reads
|
||||
// would lose its other words if written back.
|
||||
let folder = dir.join("Custom Dictionary.txt");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let big = dir.join("big.txt");
|
||||
let words = "qkzvxw\n".repeat((MAX_DICTIONARY_FILE_BYTES / 7 + 2) as usize);
|
||||
std::fs::write(&big, &words).unwrap();
|
||||
for path in [folder.clone(), big.clone()] {
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(path.clone());
|
||||
let e = s.execute("text.spelling.addWord", &json!({"word": "zkqvxw"})).unwrap_err().to_string();
|
||||
assert!(e.contains("can't be read"), "{}: {e}", path.display());
|
||||
assert!(!in_dictionary(&mut s, "zkqvxw"), "the refused word isn't kept either");
|
||||
}
|
||||
assert!(folder.is_dir());
|
||||
assert_eq!(std::fs::read_to_string(&big).unwrap(), words, "the large file is as it was");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_that_cant_be_saved_is_taken_back() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
let mut s = session();
|
||||
run(&mut s, "text.spelling.addWord", json!({"word": "wkqzvx"}));
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-rollback");
|
||||
let folder = dir.join("Custom Dictionary.txt");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut failing = session();
|
||||
failing.attach_custom_dictionary(folder);
|
||||
assert!(failing.execute("text.spelling.removeWord", &json!({"word": "wkqzvx"})).is_err());
|
||||
assert!(in_dictionary(&mut s, "wkqzvx"), "a delete that wasn't saved leaves the word");
|
||||
assert!(failing.execute("text.spelling.changeWord", &json!({"word": "wkqzvx", "to": "wkqzvy"})).is_err());
|
||||
assert!(in_dictionary(&mut s, "wkqzvx") && !in_dictionary(&mut s, "wkqzvy"), "a change that wasn't saved leaves the old word");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "wkqzvx"}));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_word_another_window_saved_stays_when_this_save_fails() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = vectorcraft_testkit::temp_dir("spelling-readonly");
|
||||
let file = dir.join("Custom Dictionary.txt");
|
||||
std::fs::write(&file, "").unwrap();
|
||||
let mut s = session();
|
||||
s.attach_custom_dictionary(file.clone());
|
||||
// Another window saves a word this session hasn't taken in, then the folder can't be written:
|
||||
// the save reads the file, takes the word in, and fails writing.
|
||||
std::fs::write(&file, "zvkqxw\n").unwrap();
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let probe = dir.join("probe");
|
||||
let writable = std::fs::write(&probe, "").is_ok();
|
||||
let r = (!writable).then(|| s.execute("text.spelling.addWord", &json!({"word": "zvkqxw"})));
|
||||
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let Some(r) = r else {
|
||||
// Run as root, the folder stays writable: there is no failing save to check.
|
||||
return;
|
||||
};
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(in_dictionary(&mut s, "zvkqxw"), "the word in the file stays, though this Add was taken back");
|
||||
run(&mut s, "text.spelling.removeWord", json!({"word": "zvkqxw"}));
|
||||
}
|
||||
|
||||
/// `misspellings` finds in one type object what the check lists for it, stops at the most it is
|
||||
/// asked for and says so, and leaves out the Ignore All words it is given.
|
||||
#[test]
|
||||
fn misspellings_of_one_object_are_what_the_check_lists() {
|
||||
use crate::cmd::spelling::misspellings;
|
||||
let mut s = session();
|
||||
let id = text(&mut s, 50.0, "the Vqzrtwx cat\nsat Wzqrvtx Xqrzvtw");
|
||||
let listed: Vec<_> = unknown(&mut s, json!({"ids": [id.0]})).into_iter().map(|(_, a, b, _)| a as usize..b as usize).collect();
|
||||
let st = s.doc().unwrap();
|
||||
let Some(vectorcraft_doc::NodeKind::Text(t)) = st.doc.node(id).map(|n| n.kind.clone()) else { panic!("type") };
|
||||
let none = Default::default();
|
||||
let (found, cut) = misspellings(&t, &none, 10);
|
||||
assert_eq!((found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), cut), (listed.clone(), false));
|
||||
assert!(found.iter().all(|m| m.lang.tag() == "en"), "{found:?}");
|
||||
let (first, cut) = misspellings(&t, &none, 2);
|
||||
assert_eq!((first.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), cut), (listed[..2].to_vec(), true));
|
||||
let ignored = std::collections::BTreeSet::from(["wzqrvtx".to_string()]);
|
||||
let (found, _) = misspellings(&t, &ignored, 10);
|
||||
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
|
||||
}
|
||||
|
||||
/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so
|
||||
/// what Auto Spell Check found before is checked again.
|
||||
#[test]
|
||||
fn custom_dictionary_changes_move_its_generation_on() {
|
||||
let _one_at_a_time = dictionary_lock();
|
||||
use crate::cmd::spelling::dictionary_generation;
|
||||
let mut s = session();
|
||||
let mut last = dictionary_generation();
|
||||
let mut moved = |s: &mut Session, id: &str, p: Value| {
|
||||
let _ = s.execute(id, &p);
|
||||
let now = dictionary_generation();
|
||||
let on = now > last;
|
||||
last = now;
|
||||
on
|
||||
};
|
||||
assert!(moved(&mut s, "text.spelling.addWord", json!({"word": "Gqzvrtx"})), "add");
|
||||
assert!(moved(&mut s, "text.spelling.changeWord", json!({"word": "gqzvrtx", "to": "hqzvrtx"})), "change");
|
||||
assert!(moved(&mut s, "text.spelling.removeWord", json!({"word": "hqzvrtx"})), "delete");
|
||||
}
|
||||
@@ -251,11 +251,16 @@ fn every_builtin_style_paints_visibly_on_a_rectangle() {
|
||||
let (_, lib) = cmd::stylelib::library(&s, b.id).unwrap();
|
||||
for g in &lib.styles {
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
// Art under the rectangle: a blend mode shows only against art, not the bare page.
|
||||
let under = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
run(&mut s, "paint.setFill", json!({"color": "#336699", "ids": [under.0]}));
|
||||
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [under.0]}));
|
||||
let id = rect(&mut s, 25.0, 30.0, 50.0, 40.0);
|
||||
run(&mut s, "graphicStyle.addFromLibrary", json!({"library": b.id, "name": g.name, "apply": true}));
|
||||
assert_eq!(doc(&s).node(id).unwrap().extras().graphic_style, doc(&s).graphic_style(&g.name).map(|x| x.id), "{}", g.name);
|
||||
let img = renderer.render_region(doc(&s), Rect::new(0.0, 0.0, 100.0, 100.0), 0.5, true);
|
||||
let painted = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[..3] != [255, 255, 255]).count();
|
||||
let bare = img.pixel(0, 0);
|
||||
let painted = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.pixel(x, y) != bare).count();
|
||||
assert!(painted > 40, "{} / {} paints {painted} pixels", b.id, g.name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,8 +84,12 @@ fn the_builtin_library_is_original_art_generated_in_code() {
|
||||
let mut s = Session::new();
|
||||
let list = run(&mut s, "symbol.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
assert_eq!(libs.len(), 1, "{libs:?}");
|
||||
assert_eq!(libs.len(), 2, "{libs:?}");
|
||||
assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn")));
|
||||
assert_eq!(
|
||||
(libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()),
|
||||
(Some("ui-frames"), Some("UI Frames"), Some("builtIn"))
|
||||
);
|
||||
let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"}));
|
||||
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]);
|
||||
@@ -95,6 +99,32 @@ fn the_builtin_library_is_original_art_generated_in_code() {
|
||||
assert!(s.execute("symbol.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_frames_symbols_carry_default_nine_slice_when_added() {
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "symbol.library", json!({"library": "ui-frames"}));
|
||||
let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Panel", "Button", "Bar"]);
|
||||
let mut placed = Vec::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let r = run(
|
||||
&mut s,
|
||||
"symbol.addFromLibrary",
|
||||
json!({"library": "ui-frames", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}),
|
||||
);
|
||||
assert_eq!(r["added"], json!([name]));
|
||||
placed.push(r["placed"].as_u64().unwrap());
|
||||
}
|
||||
let d = doc(&s);
|
||||
for name in &names {
|
||||
assert_eq!(d.symbol_nine_slice(name), Some(vectorcraft_doc::SymbolNineSlice::default()), "{name} should have default 9-slice guides");
|
||||
}
|
||||
assert!(matches!(
|
||||
d.node(NodeId(placed[0])).map(|n| &n.kind),
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == "Panel"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() {
|
||||
let dir = folder("user");
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Preferences › Type › Measure Type by Glyph Bounds (`typeGlyphBounds`): the bounding box, the
|
||||
//! Transform panel's values and `object.setBounds` measure each point type object selected as an
|
||||
//! object (not inside a selected group) by the ink of its glyphs instead of its em box.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind, OrientedBox, TextObject};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn id(v: Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A new document holding point type made by `text.create` with `params`, selected.
|
||||
fn with_type(params: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 800}));
|
||||
let t = id(run(&mut s, "text.create", params));
|
||||
run(&mut s, "select.set", json!({"ids": [t.0]}));
|
||||
(s, t)
|
||||
}
|
||||
|
||||
fn glyphs(s: &mut Session, on: bool) {
|
||||
run(s, "prefs.set", json!({"values": {"typeGlyphBounds": on}}));
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("{id:?} is not type") };
|
||||
(**t).clone()
|
||||
}
|
||||
|
||||
/// The ink of the type's glyphs on the page, laid out afresh (not from the cache).
|
||||
fn ink(s: &Session, id: NodeId) -> Rect {
|
||||
let t = text(s, id);
|
||||
t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap())
|
||||
}
|
||||
|
||||
/// The em box (the line box) of point type: what the bounding box measures by default.
|
||||
fn em(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
(a.x0 - b.x0).abs() <= tol && (a.y0 - b.y0).abs() <= tol && (a.x1 - b.x1).abs() <= tol && (a.y1 - b.y1).abs() <= tol
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The glyph box of `c` in Inter Regular, in font units (x min, y min, x max, y max), and the
|
||||
/// font's units per em, read from the font file's own `head`, `cmap`, `loca` and `glyf` tables.
|
||||
fn inter_glyph_box(c: char) -> ([f64; 4], f64) {
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::raw::TableProvider;
|
||||
let font = skrifa::FontRef::new(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap();
|
||||
let upem = f64::from(font.head().unwrap().units_per_em());
|
||||
let gid = font.charmap().map(c).unwrap();
|
||||
let glyph = font.loca(None).unwrap().get_glyf(gid, &font.glyf().unwrap()).unwrap().unwrap();
|
||||
([glyph.x_min(), glyph.y_min(), glyph.x_max(), glyph.y_max()].map(f64::from), upem)
|
||||
}
|
||||
|
||||
/// "H" in Inter at 100 pt is drawn with straight lines only, so the box of its outline is the glyph
|
||||
/// box the font file stores: the bounding box takes its size and place from the font itself.
|
||||
#[test]
|
||||
fn point_type_measures_the_glyph_box_the_font_file_stores() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "font": "Inter", "text": "H"}));
|
||||
glyphs(&mut s, true);
|
||||
let ([x0, y0, x1, y1], upem) = inter_glyph_box('H');
|
||||
let k = 100.0 / upem;
|
||||
let b = s.transform_box(&[t]).unwrap();
|
||||
assert_eq!(b.angle, 0.0);
|
||||
// Text space runs down the page from the baseline at y = 300.
|
||||
let want = Rect::new(100.0 + x0 * k, 300.0 - y1 * k, 100.0 + x1 * k, 300.0 - y0 * k);
|
||||
assert!(near(b.rect, want, 1e-6), "{:?} != {want:?}", b.rect);
|
||||
assert!(near(s.transform_bounds(&[t]).unwrap(), want, 1e-6));
|
||||
// The em box is taller than the cap height.
|
||||
assert!(em(&s, t).height() > b.rect.height() + 10.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn off_by_default_the_box_is_the_em_box() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
assert!(!s.prefs.type_glyph_bounds);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t));
|
||||
glyphs(&mut s, true);
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9));
|
||||
glyphs(&mut s, false);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t));
|
||||
}
|
||||
|
||||
/// A typed height scales the type so its ink takes that height, in one undo step, and the type
|
||||
/// stays type.
|
||||
#[test]
|
||||
fn set_bounds_gives_the_ink_the_typed_size() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let xf = text(&s, t).xf;
|
||||
let n = undo_len(&s);
|
||||
run(&mut s, "object.setBounds", json!({"height": 50}));
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert!((ink(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-6));
|
||||
assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_)));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(text(&s, t).xf, xf);
|
||||
}
|
||||
|
||||
/// A typed X moves the ink box's reference point there and keeps its size; a typed width gives
|
||||
/// the ink that width.
|
||||
#[test]
|
||||
fn set_bounds_moves_and_sizes_the_ink_box() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let before = ink(&s, t);
|
||||
run(&mut s, "object.setBounds", json!({"x": 400, "reference": 0}));
|
||||
let moved = ink(&s, t);
|
||||
assert!((moved.x0 - 400.0).abs() < 1e-6 && (moved.y0 - before.y0).abs() < 1e-6, "{moved:?}");
|
||||
assert!((moved.width() - before.width()).abs() < 1e-6 && (moved.height() - before.height()).abs() < 1e-6, "{moved:?}");
|
||||
run(&mut s, "object.setBounds", json!({"width": 123}));
|
||||
assert!((ink(&s, t).width() - 123.0).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
assert!((ink(&s, t).height() - before.height()).abs() < 1e-6, "{:?}", ink(&s, t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_with_the_current_values_records_no_undo_step() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
let n = undo_len(&s);
|
||||
run(&mut s, "object.setBounds", json!({"x": b.center().x, "y": b.center().y, "width": b.width(), "height": b.height()}));
|
||||
assert_eq!(undo_len(&s), n);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, b);
|
||||
}
|
||||
|
||||
/// A proportional width scales both sides of the ink by the same factor, about the reference
|
||||
/// point of the ink box (here its top-left corner).
|
||||
#[test]
|
||||
fn proportional_width_keeps_the_ink_in_proportion_about_the_reference_point() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let before = ink(&s, t);
|
||||
run(&mut s, "object.setBounds", json!({"width": before.width() * 2.0, "proportional": true, "reference": 0}));
|
||||
let after = ink(&s, t);
|
||||
assert!((after.width() - before.width() * 2.0).abs() < 1e-6, "{after:?}");
|
||||
assert!((after.height() - before.height() * 2.0).abs() < 1e-6, "{after:?}");
|
||||
assert!((after.x0 - before.x0).abs() < 1e-6 && (after.y0 - before.y0).abs() < 1e-6, "{before:?} -> {after:?}");
|
||||
}
|
||||
|
||||
/// Rotated type keeps its own angle, and the box is the size of the ink before the rotation. A
|
||||
/// skewed object's box is the box of its glyph outlines, not of its mapped ink rectangle.
|
||||
#[test]
|
||||
fn rotated_and_skewed_type_measure_their_outlines() {
|
||||
let (mut s, flat) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
glyphs(&mut s, true);
|
||||
let size = s.transform_box(&[flat]).unwrap().rect.size();
|
||||
let t = id(run(&mut s, "text.create", json!({"x": 300, "y": 300, "size": 100, "text": "Hg", "rotation": 30})));
|
||||
let b = s.transform_box(&[t]).unwrap();
|
||||
assert_eq!(b.angle, s.doc().unwrap().doc.oriented_bounds(&[t], false).unwrap().angle);
|
||||
assert!(b.angle != 0.0);
|
||||
assert!((b.rect.width() - size.width).abs() < 1e-6 && (b.rect.height() - size.height).abs() < 1e-6, "{b:?} vs {size:?}");
|
||||
|
||||
let o = id(run(&mut s, "text.create", json!({"x": 100, "y": 600, "size": 100, "text": "o"})));
|
||||
run(&mut s, "select.set", json!({"ids": [o.0]}));
|
||||
run(&mut s, "object.transform", json!({"matrix": [1, 0, 0.6, 1, -360, 0]}));
|
||||
let b = s.transform_box(&[o]).unwrap();
|
||||
let tx = text(&s, o);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx);
|
||||
let to_local = OrientedBox { angle: b.angle, rect: Rect::ZERO }.to_doc().inverse();
|
||||
let want = lay.ink_bounds_in(to_local * tx.xf).unwrap();
|
||||
assert!(near(b.rect, want, 1e-9), "{:?} != {want:?}", b.rect);
|
||||
let mapped = (to_local * tx.xf).transform_rect_bbox(lay.ink_bounds().unwrap());
|
||||
assert!(mapped.width() > b.rect.width() + 1.0, "a round letter's outline is narrower than its slanted box");
|
||||
}
|
||||
|
||||
/// Type that draws nothing is measured by its em box.
|
||||
#[test]
|
||||
fn empty_and_space_only_type_keep_the_em_box() {
|
||||
for text in ["", " "] {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": text}));
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap().rect, em(&s, t), "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type keeps its frame, and type on a path its path.
|
||||
#[test]
|
||||
fn area_type_and_type_on_a_path_are_measured_as_before() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 800, "height": 800}));
|
||||
let area = id(run(&mut s, "text.create", json!({"x": 100, "y": 100, "size": 24, "text": "ace", "area": {"width": 200, "height": 100}})));
|
||||
let line = id(run(&mut s, "shape.line", json!({"x1": 100, "y1": 400, "x2": 500, "y2": 400})));
|
||||
let path = id(run(&mut s, "text.createInPath", json!({"path": line.0, "mode": "onPath", "text": "ace", "size": 24})));
|
||||
for t in [area, path] {
|
||||
let off = s.transform_box(&[t]).unwrap();
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[t]).unwrap(), off, "{t:?}");
|
||||
glyphs(&mut s, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_point_type_measures_its_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 100, "size": 60, "text": "ace", "vertical": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, ink(&s, t), 1e-9), "{b:?} != {:?}", ink(&s, t));
|
||||
assert!(em(&s, t).width() > b.width() + 1.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds, the characters' strokes paint around the glyphs.
|
||||
#[test]
|
||||
fn preview_bounds_add_the_character_strokes_to_the_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
run(&mut s, "text.setStyle", json!({"ids": [t.0], "stroke": "#000000", "strokeWidth": 6}));
|
||||
run(&mut s, "prefs.set", json!({"values": {"typeGlyphBounds": true, "usePreviewBounds": true}}));
|
||||
let o = text(&s, t).char_stroke_outset();
|
||||
assert!(o > 0.0);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, ink(&s, t).inflate(o, o), 1e-9), "{b:?}");
|
||||
// A typed height is the height with the strokes.
|
||||
run(&mut s, "object.setBounds", json!({"height": 80}));
|
||||
assert!((s.transform_box(&[t]).unwrap().rect.height() - 80.0).abs() < 1e-6, "{:?}", s.transform_box(&[t]));
|
||||
}
|
||||
|
||||
/// Type inside a selected group is measured as before: the group's box does not change.
|
||||
#[test]
|
||||
fn a_group_holding_type_keeps_its_box() {
|
||||
let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let g = id(run(&mut s, "object.group", json!({})));
|
||||
let off = s.transform_box(&[g]).unwrap();
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(s.transform_box(&[g]).unwrap(), off);
|
||||
}
|
||||
|
||||
/// Runs in two fonts: the box covers the ink of both, and follows an edit of the type.
|
||||
#[test]
|
||||
fn mixed_fonts_measure_the_ink_of_every_run() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hgxo"}));
|
||||
glyphs(&mut s, true);
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "font": "Source Serif 4", "start": 2, "end": 4}));
|
||||
let tx = text(&s, t);
|
||||
assert!(tx.runs.iter().any(|r| r.style.font_family == "Source Serif 4") && tx.runs.len() > 1, "{:?}", tx.runs);
|
||||
assert!(tx.ink().is_some(), "the edit refreshed the cached ink");
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, ink(&s, t), 1e-9));
|
||||
}
|
||||
|
||||
/// A selection of type and a shape is measured by the type's ink and the shape's bounds.
|
||||
#[test]
|
||||
fn a_mixed_selection_takes_the_ink_and_the_shapes_bounds() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let r = id(run(&mut s, "shape.rectangle", json!({"x": 500, "y": 500, "width": 50, "height": 50})));
|
||||
glyphs(&mut s, true);
|
||||
assert!(near(s.transform_bounds(&[t, r]).unwrap(), ink(&s, t).union(Rect::new(500.0, 500.0, 550.0, 550.0)), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preference_is_checked_and_saved() {
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute("prefs.set", &json!({"values": {"typeGlyphBounds": "yes"}})).is_err());
|
||||
assert!(!s.prefs.type_glyph_bounds);
|
||||
assert!(!serde_json::from_value::<Prefs>(json!({})).unwrap().type_glyph_bounds);
|
||||
run(&mut s, "prefs.set", json!({"key": "typeGlyphBounds", "value": true}));
|
||||
let saved = serde_json::to_value(&s.prefs).unwrap();
|
||||
assert_eq!(saved["typeGlyphBounds"], json!(true));
|
||||
assert!(serde_json::from_value::<Prefs>(saved).unwrap().type_glyph_bounds);
|
||||
assert_eq!(run(&mut s, "prefs.get", json!({"key": "typeGlyphBounds"})), json!(true));
|
||||
}
|
||||
|
||||
/// The preference is not part of the document: a saved document is the same with it on or off.
|
||||
#[test]
|
||||
fn saved_documents_do_not_depend_on_the_preference() {
|
||||
let (mut s, _) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let off = serde_json::to_string(&s.doc().unwrap().doc).unwrap();
|
||||
assert!(!off.contains("cached_ink") && !off.contains("cachedInk"), "the cached ink is not saved");
|
||||
glyphs(&mut s, true);
|
||||
assert_eq!(serde_json::to_string(&s.doc().unwrap().doc).unwrap(), off);
|
||||
}
|
||||
|
||||
/// What the type draws on the page: its glyphs and its underline and strikethrough bars.
|
||||
fn drawn(s: &Session, id: NodeId) -> Rect {
|
||||
let t = text(s, id);
|
||||
vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap()
|
||||
}
|
||||
|
||||
/// Underline and strikethrough bars are drawn with the type, so the box takes them in and a typed
|
||||
/// height gives what is drawn that height. Underlined spaces are measured by their bar.
|
||||
#[test]
|
||||
fn underline_and_strikethrough_bars_count_as_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "H"}));
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 1, "underline": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t));
|
||||
assert!(b.y1 > ink(&s, t).y1 + 1.0, "the underline hangs below the glyph");
|
||||
run(&mut s, "object.setBounds", json!({"height": 50}));
|
||||
assert!((drawn(&s, t).height() - 50.0).abs() < 1e-6, "{:?}", drawn(&s, t));
|
||||
assert!(near(s.transform_box(&[t]).unwrap().rect, drawn(&s, t), 1e-6));
|
||||
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 40, "text": " "}));
|
||||
run(&mut s, "text.setRangeStyle", json!({"id": t.0, "start": 0, "end": 3, "strikethrough": true}));
|
||||
glyphs(&mut s, true);
|
||||
let b = s.transform_box(&[t]).unwrap().rect;
|
||||
assert!(near(b, drawn(&s, t), 1e-9), "{b:?} != {:?}", drawn(&s, t));
|
||||
assert!(em(&s, t).height() > b.height() + 10.0, "em box {:?}", em(&s, t));
|
||||
}
|
||||
|
||||
/// A transform of type keeps its cached ink, which is in text space.
|
||||
#[test]
|
||||
fn the_cached_ink_is_the_laid_out_ink() {
|
||||
let (mut s, t) = with_type(json!({"x": 100, "y": 300, "size": 100, "text": "Hg"}));
|
||||
let tx = text(&s, t);
|
||||
assert_eq!(tx.ink(), Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &tx).ink_bounds()));
|
||||
run(&mut s, "object.transform", json!({"matrix": [2, 0, 0, 3, 0, 0]}));
|
||||
assert_eq!(text(&s, t).ink(), tx.ink());
|
||||
// A cache measured with other bounds is not read.
|
||||
let mut stale = text(&s, t);
|
||||
stale.cached_bounds = Some(Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
assert_eq!(stale.ink(), None);
|
||||
}
|
||||
@@ -365,6 +365,7 @@ impl Session {
|
||||
freeform_point: self.selected_freeform_point(),
|
||||
raster_sample: self.prefs.eyedropper.sample_size,
|
||||
preview_bounds: self.prefs.use_preview_bounds,
|
||||
glyph_bounds: self.prefs.type_glyph_bounds,
|
||||
preview_memo: Some(&self.preview_memo),
|
||||
unit,
|
||||
stroke_unit,
|
||||
|
||||
Reference in New Issue
Block a user