mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 23:58:03 +00:00
Merge main into fix/fitted-gradient-turns-with-transform
This commit is contained in:
+33
-14
@@ -1,5 +1,6 @@
|
||||
//! The command registry. Ids follow Illustrator's menu structure.
|
||||
|
||||
pub mod actionset;
|
||||
mod addons;
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
@@ -83,6 +84,7 @@ pub(crate) mod slices;
|
||||
mod stroke;
|
||||
mod style;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
@@ -317,6 +319,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
v.extend(newart::specs());
|
||||
v.extend(colortheme::specs());
|
||||
v.extend(fileio::pdf::specs());
|
||||
@@ -344,6 +347,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(halftone::specs());
|
||||
v.extend(perspgrid::specs());
|
||||
v.extend(shortcutset::specs());
|
||||
v.extend(actionset::specs());
|
||||
v.extend(importmatches::specs());
|
||||
v.extend(addons::specs());
|
||||
v
|
||||
@@ -575,21 +579,31 @@ pub(crate) fn named_id(p: &Value) -> Result<Option<NodeId>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Objects a command targets: explicit `ids` param or the selection.
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
// Objects given are used as given: a value that isn't an object id fails rather than the
|
||||
// command acting on the selection instead (#785).
|
||||
match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) => return a.iter().map(object_id).collect(),
|
||||
Some(v) => return Err(EngineError::Other(format!("`ids` must be an array of object ids, not {v}"))),
|
||||
None => {}
|
||||
/// The object `p` gives as `key`, for a command that acts on the selection (or makes something new)
|
||||
/// without it: `None` when `p` leaves it out or gives null. Any other value that isn't an object id
|
||||
/// (`"abc"`, `"5"`, `true`, `{}`, `-1`, `2.5`) is an error under `cmd` that names `key`, never the
|
||||
/// selection. The id is not looked up in the document.
|
||||
pub(crate) fn object_param(p: &Value, key: &str, cmd: &str) -> Result<Option<NodeId>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(r)) if key == "id" && r.starts_with('$') => {
|
||||
Err(bad(cmd, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
|
||||
}
|
||||
Some(v) => v.as_u64().map(|id| Some(NodeId(id))).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number"))),
|
||||
}
|
||||
match p.get("id").filter(|v| !v.is_null()) {
|
||||
Some(v @ Value::Number(_)) => Ok(vec![object_id(v)?]),
|
||||
// A step reference a batch couldn't resolve (other strings are other ids, such as an
|
||||
// effect's).
|
||||
Some(Value::String(r)) if r.starts_with('$') => Err(unresolved_reference(r)),
|
||||
_ => Ok(s.doc()?.selection.objects.clone()),
|
||||
}
|
||||
|
||||
/// Objects a command targets: its `ids`, else its `id` as `ids` of one ([`named_ids`]), else the
|
||||
/// selection. An `ids` or `id` that isn't an object id is an error, never the selection. The
|
||||
/// selection is refused while an object of a dynamic symbol instance's art is selected, as by
|
||||
/// [`edit::selected_roots`].
|
||||
pub(crate) fn targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(ids) => Ok(ids),
|
||||
None => {
|
||||
edit::refuse_symbol_part(s)?;
|
||||
Ok(s.doc()?.selection.objects.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -662,6 +676,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
@@ -722,6 +737,10 @@ pub use pathops::shape_count;
|
||||
/// The gaps View › Show Live Paint Gaps shows on a Live Paint group.
|
||||
pub use buildcmds::live_paint_gaps;
|
||||
|
||||
/// Whether Reset Transformation changes a symbol instance (the Symbols panel menu and the
|
||||
/// Control bar enable it when it changes one).
|
||||
pub use brushsym::reset_transformation_changes;
|
||||
|
||||
/// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`.
|
||||
/// They run as before but the command palette leaves them out (it lists the command once).
|
||||
pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")];
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Action sets another app saves as text (`.aia` files that start `/version`), read into their
|
||||
//! actions and steps without changing anything (`actionSet.read`).
|
||||
//!
|
||||
//! The text is a set of fields and blocks. A slash name followed by a value sets a field, and a
|
||||
//! slash name followed by `{` opens a block that `}` closes. A value is a decimal number, text in
|
||||
//! parentheses, a byte count and hexadecimal bytes in square brackets (`[ 5 48656c6c6f ]`, UTF-8
|
||||
//! text, which can run over several words), or a byte count and hexadecimal bytes in angle brackets
|
||||
//! (`< 3 0a0b0c >`, raw bytes). The set's `/version` comes first, and its `/name` is hexadecimal
|
||||
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
|
||||
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
|
||||
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
|
||||
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
|
||||
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
|
||||
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
|
||||
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
|
||||
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
|
||||
//! "Made a two-way aia to json converter"
|
||||
//! (https://community.adobe.com/t5/illustrator-discussions/made-a-two-way-aia-to-json-converter/m-p/13751909),
|
||||
//! sttk3's article on names as UTF-8 hexadecimal
|
||||
//! (https://sttk3.com/blog/tips/illustrator/dynamic-generate-action.html), and the MIT-licensed
|
||||
//! reader in zachshallbetter/adobe-mcp (https://github.com/zachshallbetter/adobe-mcp). The raw form
|
||||
//! follows the forum thread "Creating a dynamic action"
|
||||
//! (https://community.adobe.com/questions-652/creating-a-dynamic-action-to-use-with-app-doscript-method-814406).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
|
||||
|
||||
/// The most bytes of a file read.
|
||||
const MAX_BYTES: usize = 8 << 20;
|
||||
/// The most bytes taken in: [`MAX_BYTES`] after a byte order mark, and one more that shows the text
|
||||
/// goes on.
|
||||
const READ_LIMIT: usize = MAX_BYTES + 4;
|
||||
/// The most blocks open at once.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most actions read.
|
||||
const MAX_ACTIONS: usize = 1000;
|
||||
/// The most steps read in one action.
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
|
||||
/// the answer holds an object for each.
|
||||
const MAX_SET_STEPS: usize = 100_000;
|
||||
/// The longest name kept (bytes).
|
||||
const MAX_NAME: usize = 1024;
|
||||
/// The most tokens listed as unread.
|
||||
const MAX_UNREAD: usize = 1000;
|
||||
/// The longest unread token shown (characters).
|
||||
const UNREAD_SHOWN: usize = 80;
|
||||
|
||||
/// The extensions of action sets other apps save.
|
||||
pub const EXTS: &[&str] = &["aia"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "actionSet.read",
|
||||
"Read Action Set File",
|
||||
[],
|
||||
None,
|
||||
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
|
||||
always,
|
||||
read
|
||||
)]
|
||||
}
|
||||
|
||||
/// A step of an action: an `/event-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaStep {
|
||||
/// Its `/internalName`.
|
||||
pub name: String,
|
||||
/// Its `/localizedName`, if it has one.
|
||||
pub label: Option<String>,
|
||||
/// Its `/isOn`, if it has one.
|
||||
pub on: Option<i64>,
|
||||
/// How many `/parameter-N` blocks it has.
|
||||
pub params: usize,
|
||||
/// Its `/parameterCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The line its block opens on (from 1).
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// An action: an `/action-N` block.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaAction {
|
||||
pub name: String,
|
||||
pub steps: Vec<AiaStep>,
|
||||
/// Its `/eventCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
}
|
||||
|
||||
/// An action set read from text.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AiaSet {
|
||||
pub version: i64,
|
||||
/// The set's `/name`, if it has one.
|
||||
pub name: Option<String>,
|
||||
pub actions: Vec<AiaAction>,
|
||||
/// Its `/actionCount`, if it has one.
|
||||
pub declared: Option<i64>,
|
||||
/// The tokens that weren't read, with their lines.
|
||||
pub unread: Vec<(usize, String)>,
|
||||
/// A cap stopped the reading or cut a name, the text ends inside a block or a value or after a
|
||||
/// field's name, its counts differ from the actions, steps and recorded values read (a negative
|
||||
/// count, one too large for an `i64` and one that isn't a number always differ), or a hexadecimal
|
||||
/// name, label or recorded `/value` isn't as many bytes as its count says.
|
||||
pub truncated: bool,
|
||||
/// How many steps were read in all the actions.
|
||||
steps: usize,
|
||||
}
|
||||
|
||||
/// A token of the text.
|
||||
enum Token {
|
||||
/// A slash name.
|
||||
Name(Vec<u8>),
|
||||
/// An integer; `None` when it doesn't fit an `i64`.
|
||||
Int(Option<i64>),
|
||||
/// Text in parentheses, a backslash taking the next byte as it is.
|
||||
Text(Vec<u8>),
|
||||
/// The bytes of `[ count hex… ]`; `None` when the hexadecimal digits don't make whole bytes or
|
||||
/// as many bytes as the count says.
|
||||
Hex(Option<Vec<u8>>),
|
||||
/// `< count hex… >`.
|
||||
Raw,
|
||||
Open,
|
||||
Close,
|
||||
/// Anything else, as written.
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
/// The tokens of `text`, each with its line.
|
||||
struct Tokens<'a> {
|
||||
text: &'a [u8],
|
||||
at: usize,
|
||||
line: usize,
|
||||
/// The text ended inside a value in parentheses, square brackets or angle brackets.
|
||||
unclosed: bool,
|
||||
}
|
||||
|
||||
impl<'a> Tokens<'a> {
|
||||
/// Past one byte, counting a line at LF, at CR alone, and once for CRLF.
|
||||
fn step(&mut self) -> Option<u8> {
|
||||
let b = *self.text.get(self.at)?;
|
||||
if b == b'\n' || b == b'\r' && self.text.get(self.at + 1) != Some(&b'\n') {
|
||||
self.line += 1;
|
||||
}
|
||||
self.at += 1;
|
||||
Some(b)
|
||||
}
|
||||
|
||||
/// The bytes up to `end` (not taken in); `None` when the text ends first.
|
||||
fn until(&mut self, end: u8) -> Option<&'a [u8]> {
|
||||
let (text, start) = (self.text, self.at);
|
||||
while text.get(self.at).is_some_and(|&b| b != end) {
|
||||
self.step();
|
||||
}
|
||||
let inside = text.get(start..self.at)?;
|
||||
text.get(self.at)?;
|
||||
self.at += 1;
|
||||
Some(inside)
|
||||
}
|
||||
|
||||
fn next_token(&mut self) -> Option<(usize, Token)> {
|
||||
while self.text.get(self.at).is_some_and(|&b| b.is_ascii_whitespace() || b == 0) {
|
||||
self.step();
|
||||
}
|
||||
let line = self.line;
|
||||
let b = *self.text.get(self.at)?;
|
||||
let ends = |b: u8| b.is_ascii_whitespace() || b == 0 || b"{}[]()<>/".contains(&b);
|
||||
let token = match b {
|
||||
b'{' | b'}' => {
|
||||
self.at += 1;
|
||||
if b == b'{' { Token::Open } else { Token::Close }
|
||||
}
|
||||
b'(' => {
|
||||
self.at += 1;
|
||||
let (mut text, mut depth) = (vec![], 0usize);
|
||||
self.unclosed = true;
|
||||
while let Some(c) = self.step() {
|
||||
match c {
|
||||
b'\\' => text.extend(self.step()),
|
||||
b'(' => {
|
||||
depth += 1;
|
||||
text.push(c);
|
||||
}
|
||||
b')' if depth == 0 => {
|
||||
self.unclosed = false;
|
||||
break;
|
||||
}
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
text.push(c);
|
||||
}
|
||||
_ => text.push(c),
|
||||
}
|
||||
}
|
||||
Token::Text(text)
|
||||
}
|
||||
b'[' | b'<' => {
|
||||
self.at += 1;
|
||||
let close = if b == b'[' { b']' } else { b'>' };
|
||||
let inside = self.until(close);
|
||||
self.unclosed = inside.is_none();
|
||||
let inside = inside.unwrap_or_default().to_vec();
|
||||
if b == b'<' {
|
||||
Token::Raw
|
||||
} else {
|
||||
// The first word is the byte count; the bytes follow in one or more words.
|
||||
let mut words = inside.split(|c| c.is_ascii_whitespace()).filter(|w| !w.is_empty());
|
||||
let count = words.next().and_then(|w| std::str::from_utf8(w).ok()).and_then(|w| w.parse::<usize>().ok());
|
||||
let digits: Vec<u8> = words.flatten().copied().collect();
|
||||
Token::Hex(hex_bytes(&digits).filter(|b| Some(b.len()) == count))
|
||||
}
|
||||
}
|
||||
b'/' => {
|
||||
self.at += 1;
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
Token::Name(self.text.get(start..self.at).unwrap_or_default().to_vec())
|
||||
}
|
||||
_ => {
|
||||
let start = self.at;
|
||||
while self.text.get(self.at).is_some_and(|&c| !ends(c)) {
|
||||
self.at += 1;
|
||||
}
|
||||
// Always past at least one byte.
|
||||
self.at = self.at.max(start + 1);
|
||||
let word = self.text.get(start..self.at).unwrap_or_default();
|
||||
let number = word.strip_prefix(b"-").or_else(|| word.strip_prefix(b"+")).unwrap_or(word);
|
||||
if !number.is_empty() && number.iter().all(u8::is_ascii_digit) {
|
||||
Token::Int(std::str::from_utf8(word).ok().and_then(|s| s.parse().ok()))
|
||||
} else {
|
||||
Token::Other(word.to_vec())
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((line, token))
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes hexadecimal `digits` stand for, two digits a byte.
|
||||
fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
|
||||
let nibble = |c: u8| (c as char).to_digit(16).and_then(|d| u8::try_from(d).ok());
|
||||
if !digits.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
digits.chunks(2).map(|pair| Some((nibble(*pair.first()?)? << 4) | nibble(*pair.get(1)?)?)).collect()
|
||||
}
|
||||
|
||||
/// What a block is.
|
||||
enum Kind {
|
||||
Action,
|
||||
Step,
|
||||
Param,
|
||||
/// A block that isn't read, or one past a cap.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// `name` ends with `-` and a number after `prefix`, as `/action-1` does.
|
||||
fn numbered(name: &[u8], prefix: &[u8]) -> bool {
|
||||
name.strip_prefix(prefix).is_some_and(|n| !n.is_empty() && n.iter().all(u8::is_ascii_digit))
|
||||
}
|
||||
|
||||
/// A name as text: at most [`MAX_NAME`] bytes, read as UTF-8 with replacement characters.
|
||||
fn name_text(name: &[u8], set: &mut AiaSet) -> String {
|
||||
if name.len() > MAX_NAME {
|
||||
set.truncated = true;
|
||||
}
|
||||
let mut s = String::from_utf8_lossy(name.get(..MAX_NAME).unwrap_or(name)).into_owned();
|
||||
// A character cut at the limit reads as one replacement character.
|
||||
if name.len() > MAX_NAME && s.ends_with('\u{FFFD}') {
|
||||
s.pop();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// How the unread list shows a value in square brackets that isn't as many bytes as its count says.
|
||||
const BAD_HEX: &str = "[ … ] (not the hexadecimal bytes its count says)";
|
||||
|
||||
/// List a token that isn't read.
|
||||
fn unread(set: &mut AiaSet, line: usize, text: impl AsRef<[u8]>) {
|
||||
if set.unread.len() < MAX_UNREAD {
|
||||
let text: String = String::from_utf8_lossy(text.as_ref()).chars().take(UNREAD_SHOWN).collect();
|
||||
set.unread.push((line, text));
|
||||
}
|
||||
}
|
||||
|
||||
/// What the block `name` that opens on `line` inside the blocks `stack` is: a new action, step or
|
||||
/// recorded value of `set`, or a block that isn't read (listed when it is out of place).
|
||||
fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kind {
|
||||
match stack.last() {
|
||||
_ if stack.len() >= MAX_DEPTH => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
None if numbered(name, b"action-") => {
|
||||
if set.actions.len() < MAX_ACTIONS {
|
||||
set.actions.push(AiaAction::default());
|
||||
Kind::Action
|
||||
} else {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
Some(Kind::Action) if numbered(name, b"event-") => match set.actions.last_mut() {
|
||||
Some(a) if a.steps.len() < MAX_STEPS && set.steps < MAX_SET_STEPS => {
|
||||
a.steps.push(AiaStep { line, ..AiaStep::default() });
|
||||
set.steps += 1;
|
||||
Kind::Step
|
||||
}
|
||||
_ => {
|
||||
set.truncated = true;
|
||||
Kind::Other
|
||||
}
|
||||
},
|
||||
Some(Kind::Step) if numbered(name, b"parameter-") => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.params += 1;
|
||||
}
|
||||
Kind::Param
|
||||
}
|
||||
Some(Kind::Param | Kind::Other) => Kind::Other,
|
||||
_ => {
|
||||
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
|
||||
Kind::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the hexadecimal text `bytes`
|
||||
/// on `line`: the set's or an action's `/name`, or a step's `/localizedName`.
|
||||
fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Option<Vec<u8>>, line: usize) {
|
||||
let Some(bytes) = bytes else {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
return;
|
||||
};
|
||||
match (kind, name) {
|
||||
(None, Some(b"name")) => set.name = Some(name_text(&bytes, set)),
|
||||
(Some(Kind::Action), Some(b"name")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.name = text;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"localizedName")) => {
|
||||
let text = name_text(&bytes, set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.label = Some(text);
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, "[ … ]"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
|
||||
/// says.
|
||||
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
|
||||
if bytes.is_none() {
|
||||
set.truncated = true;
|
||||
unread(set, line, BAD_HEX);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark `set` truncated when the field `name` of the block `kind` (the set when `None`) is a count
|
||||
/// (the set's `/actionCount`, an action's `/eventCount` or a step's `/parameterCount`) whose value is
|
||||
/// not a number that fits an `i64`.
|
||||
fn bad_count(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>) {
|
||||
if matches!((kind, name), (None, Some(b"actionCount")) | (Some(Kind::Action), Some(b"eventCount")) | (Some(Kind::Step), Some(b"parameterCount")))
|
||||
{
|
||||
set.truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the field `name` of the block `kind` (the set when `None`) to the integer `value` on `line`:
|
||||
/// the set's `/actionCount`, an action's `/eventCount`, a step's `/parameterCount`, or a step's
|
||||
/// `/isOn`. A count too large for an `i64` marks the set truncated.
|
||||
fn set_int(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, value: Option<i64>, line: usize) {
|
||||
if value.is_none() {
|
||||
bad_count(set, kind, name);
|
||||
}
|
||||
match (kind, name) {
|
||||
(None, Some(b"actionCount")) => set.declared = value,
|
||||
(Some(Kind::Action), Some(b"eventCount")) => {
|
||||
if let Some(a) = set.actions.last_mut() {
|
||||
a.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"parameterCount")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.declared = value;
|
||||
}
|
||||
}
|
||||
(Some(Kind::Step), Some(b"isOn")) => {
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.on = value;
|
||||
}
|
||||
}
|
||||
(_, Some(_)) => {}
|
||||
(_, None) => unread(set, line, value.map_or_else(|| "(a number too large)".to_string(), |v| v.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read an action set saved as text. An error when the text isn't one: it doesn't start with
|
||||
/// `/version` and an integer.
|
||||
pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
|
||||
let mut set = AiaSet::default();
|
||||
let text = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
|
||||
let text = match text.get(..MAX_BYTES) {
|
||||
Some(head) if text.len() > MAX_BYTES => {
|
||||
set.truncated = true;
|
||||
head
|
||||
}
|
||||
_ => text,
|
||||
};
|
||||
let mut tokens = Tokens { text, at: 0, line: 1, unclosed: false };
|
||||
match (tokens.next_token(), tokens.next_token()) {
|
||||
(Some((_, Token::Name(n))), Some((_, Token::Int(Some(v))))) if n == b"version" => set.version = v,
|
||||
_ => return Err("not an action set: the text doesn't start with /version and a number".into()),
|
||||
}
|
||||
let mut stack: Vec<Kind> = vec![];
|
||||
// A slash name waiting for its value or its `{`: (line, name).
|
||||
let mut pending: Option<(usize, Vec<u8>)> = None;
|
||||
while let Some((line, token)) = tokens.next_token() {
|
||||
let in_step = matches!(stack.last(), Some(Kind::Step));
|
||||
let field = |pending: &mut Option<(usize, Vec<u8>)>| pending.take().map(|(_, n)| n);
|
||||
match token {
|
||||
Token::Name(name) => {
|
||||
if let Some((l, n)) = pending.replace((line, name)) {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
}
|
||||
Token::Open => {
|
||||
let (l, name) = pending.take().unwrap_or((line, vec![]));
|
||||
bad_count(&mut set, stack.last(), Some(&name));
|
||||
let kind = open_block(&mut set, &stack, &name, l);
|
||||
stack.push(kind);
|
||||
}
|
||||
Token::Close => {
|
||||
if let Some((l, n)) = pending.take() {
|
||||
bad_count(&mut set, stack.last(), Some(&n));
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
if stack.pop().is_none() {
|
||||
unread(&mut set, line, "}");
|
||||
}
|
||||
}
|
||||
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
|
||||
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
|
||||
check_value(&mut set, bytes, line);
|
||||
}
|
||||
}
|
||||
// The other values inside a recorded value, or a block that isn't read.
|
||||
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
|
||||
pending = None;
|
||||
}
|
||||
Token::Hex(bytes) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
set_hex(&mut set, stack.last(), name.as_deref(), bytes, line);
|
||||
}
|
||||
Token::Text(t) => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
match name {
|
||||
Some(n) if in_step && n == b"internalName" => {
|
||||
let name = name_text(&t, &mut set);
|
||||
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
|
||||
s.name = name;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => unread(&mut set, line, [b"(".as_slice(), &t, b")"].concat()),
|
||||
}
|
||||
}
|
||||
Token::Int(v) => {
|
||||
let name = field(&mut pending);
|
||||
set_int(&mut set, stack.last(), name.as_deref(), v, line);
|
||||
}
|
||||
Token::Raw => {
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, "< … >");
|
||||
}
|
||||
}
|
||||
Token::Other(word) => {
|
||||
// A real number, or another word as a field's value.
|
||||
let name = field(&mut pending);
|
||||
bad_count(&mut set, stack.last(), name.as_deref());
|
||||
if name.is_none() {
|
||||
unread(&mut set, line, word);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The text ends after a field's name, before its value.
|
||||
if let Some((l, n)) = pending {
|
||||
set.truncated = true;
|
||||
unread(&mut set, l, [b"/".as_slice(), &n].concat());
|
||||
}
|
||||
// An unclosed value is the last token: it takes the rest of the text.
|
||||
if tokens.unclosed {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "a value not closed at the end");
|
||||
}
|
||||
if !stack.is_empty() {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, format!("blocks left open at the end: {}", stack.len()));
|
||||
}
|
||||
// Not as many actions, steps or recorded values as the counts give; a negative count never matches.
|
||||
let differs = |declared: Option<i64>, read: usize| declared.is_some_and(|d| !usize::try_from(d).is_ok_and(|d| d == read));
|
||||
let step_differs = |a: &AiaAction| a.steps.iter().any(|s| differs(s.declared, s.params));
|
||||
if differs(set.declared, set.actions.len()) || set.actions.iter().any(|a| differs(a.declared, a.steps.len()) || step_differs(a)) {
|
||||
set.truncated = true;
|
||||
unread(&mut set, tokens.line, "not as many actions, steps or recorded values as the counts give");
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn read(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "actionSet.read";
|
||||
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
|
||||
let name = text_param(p, "name", C)?;
|
||||
let bytes: std::borrow::Cow<[u8]> = match (path, data, b64) {
|
||||
(Some(path), None, None) => super::fileio::read_file_head(path, READ_LIMIT)?.into(),
|
||||
(None, Some(text), None) => text.as_bytes().get(..READ_LIMIT).unwrap_or(text.as_bytes()).into(),
|
||||
(None, None, Some(b64)) => super::scripts::decode_head(b64, READ_LIMIT).ok_or_else(|| bad(C, "bad dataBase64"))?.into(),
|
||||
_ => return Err(bad(C, "give exactly one of `path`, `data` and `dataBase64`")),
|
||||
};
|
||||
let set = read_aia(&bytes).map_err(EngineError::Other)?;
|
||||
let file = name.or(path).unwrap_or_default();
|
||||
let stem = std::path::Path::new(file).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = set.name.clone().filter(|n| !n.trim().is_empty()).unwrap_or(stem);
|
||||
let actions: Vec<Value> = set
|
||||
.actions
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let steps: Vec<Value> = a
|
||||
.steps
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let label = s.label.clone().filter(|l| !l.trim().is_empty());
|
||||
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
|
||||
})
|
||||
.collect();
|
||||
json!({ "name": a.name, "steps": steps })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"set": name,
|
||||
"version": set.version,
|
||||
"actions": actions,
|
||||
"unread": set.unread.iter().map(|(line, text)| json!({ "line": line, "text": text })).collect::<Vec<_>>(),
|
||||
"truncated": set.truncated,
|
||||
}))
|
||||
}
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), 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)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, 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)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, 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)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -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) → {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 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 and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -551,12 +551,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
// Where the new fill went in on the active item's object, when it went above the active row.
|
||||
let mut above = None;
|
||||
s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| {
|
||||
// The objects that got a new topmost row of the kind: the series stores its paint even when the object showed it.
|
||||
let mut added = Vec::new();
|
||||
for (id, row) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
if let Some(i) = n.appearance.item_of_kind(*row, true)
|
||||
&& let Some(paint) = n.appearance.paint_at(Some(i), true).cloned()
|
||||
{
|
||||
n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint)));
|
||||
if let Some(kind) = top_row_kind(&n.appearance, i + 1) {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
if active == Some(*id) {
|
||||
above = Some(i + 1);
|
||||
}
|
||||
@@ -591,10 +596,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
|
||||
}
|
||||
} else {
|
||||
n.appearance.items.push(item);
|
||||
added.push((*id, fill));
|
||||
}
|
||||
if !fill {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(())
|
||||
})?;
|
||||
// A fill added above the active row becomes the active row; otherwise the rows above the new
|
||||
@@ -611,10 +623,12 @@ fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
@@ -626,15 +640,66 @@ fn both_kinds(ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).collect()
|
||||
}
|
||||
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost row has another opacity in `d` than
|
||||
/// in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another opacity in `d`
|
||||
/// than in `before` (no row counts as opaque), for [`super::graph::capture_series_opacity`].
|
||||
fn top_opacity_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| {
|
||||
d.node(id).and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill).map(AppearanceItem::opacity)).unwrap_or(1.0)
|
||||
d.node(id)
|
||||
.and_then(|n| n.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()).map(AppearanceItem::opacity))
|
||||
.unwrap_or(1.0)
|
||||
};
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
|
||||
}
|
||||
|
||||
/// Each of `ids` with each kind of row (fill `true`, stroke `false`) whose topmost visible row has another paint, or a
|
||||
/// stroke another weight, in `d` than in `before` (no row counts as no paint), for
|
||||
/// [`super::graph::capture_series_top_paints`].
|
||||
fn top_paint_changed(before: &vectorcraft_doc::Document, d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Vec<(NodeId, bool)> {
|
||||
let top = |d: &vectorcraft_doc::Document, id: NodeId, fill: bool| d.node(id).map(|n| super::graph::shown_paint(n, fill));
|
||||
ids.iter().flat_map(|id| [(*id, true), (*id, false)]).filter(|(id, fill)| top(before, *id, *fill) != top(d, *id, *fill)).collect()
|
||||
}
|
||||
|
||||
/// `rows` (each object with the kind of row) whose topmost visible row of that kind has paint: a command that wrote them
|
||||
/// replaces the paint another mark of the series left on the graph, even when the mark's own row comes out as it was.
|
||||
fn painted_rows(d: &vectorcraft_doc::Document, rows: impl IntoIterator<Item = (NodeId, bool)>) -> Vec<(NodeId, bool)> {
|
||||
rows.into_iter().filter(|(id, fill)| d.node(*id).is_some_and(|n| !super::graph::shown_paint(n, *fill).0.is_none())).collect()
|
||||
}
|
||||
|
||||
/// Store on the graph what an edit of `ids` (from `before` to `d`) leaves on the topmost visible fill and stroke of the
|
||||
/// series marks among them: a paint, weight or opacity that changed, and the paint (`paints`) and opacity (`opacities`) of
|
||||
/// the kinds of row the edit wrote, as (fill, stroke). With `top_only` the edit wrote the topmost row of each kind, which
|
||||
/// counts only when it is visible. Returns whether the stored paint changed.
|
||||
pub(super) fn capture_series_writes(
|
||||
before: &vectorcraft_doc::Document,
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
ids: &[NodeId],
|
||||
paints: (bool, bool),
|
||||
opacities: (bool, bool),
|
||||
top_only: bool,
|
||||
) -> bool {
|
||||
let top_shows = |d: &vectorcraft_doc::Document, id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(AppearanceItem::visible)
|
||||
};
|
||||
let written = |d: &vectorcraft_doc::Document, (fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
|
||||
let rows = ids.iter().flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))]).flatten();
|
||||
painted_rows(d, rows.filter(|(id, kind)| !top_only || top_shows(d, *id, *kind)))
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(before, d, ids);
|
||||
opacity_rows.extend(written(d, opacities));
|
||||
let mut rows = top_paint_changed(before, d, ids);
|
||||
rows.extend(written(d, paints));
|
||||
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
kept || painted
|
||||
}
|
||||
|
||||
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
|
||||
fn top_row_kind(ap: &Appearance, at: usize) -> Option<bool> {
|
||||
let fill = ap.items.get(at)?.is_fill();
|
||||
(ap.items.iter().rposition(|it| it.is_fill() == fill && it.visible()) == Some(at)).then_some(fill)
|
||||
}
|
||||
|
||||
/// Clear Appearance on `n`: no fill, no stroke, and the object's Opacity row back to Default. A
|
||||
/// group keeps no fill or stroke rows of its own.
|
||||
fn clear(n: &mut Node) {
|
||||
@@ -666,13 +731,19 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
to.appearance = ap;
|
||||
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
if !copy && let Some(n) = d.node_mut(source) {
|
||||
clear(n);
|
||||
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
let changed = if copy { vec![target] } else { vec![source, target] };
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept))
|
||||
// The target last: on marks of one series, its paint is the one the series keeps.
|
||||
let mut rows = top_paint_changed(&before, d, &changed);
|
||||
rows.extend(painted_rows(d, both_kinds(&[target])));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -723,10 +794,12 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.blend = BlendMode::Normal;
|
||||
n.appearance.items.push(AppearanceItem::Stroke(st));
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
ok()
|
||||
@@ -752,10 +825,6 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
let Some(&idx) = at.first() else { continue };
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let items = &n.appearance.items;
|
||||
if let Some(fill) = items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f) == Some(idx)) {
|
||||
edited.push((*id, fill));
|
||||
}
|
||||
if p.get("weight").is_none()
|
||||
&& let Some(pa) = &paint
|
||||
{
|
||||
@@ -785,10 +854,27 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
|
||||
*vis = v;
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
let items = &n.appearance.items;
|
||||
if let Some(fill) =
|
||||
items.get(idx).map(AppearanceItem::is_fill).filter(|f| items.iter().rposition(|it| it.is_fill() == *f && it.visible()) == Some(idx))
|
||||
{
|
||||
edited.push((*id, fill));
|
||||
}
|
||||
}
|
||||
// The graph keeps an opacity set on the topmost fill or stroke of its series art for when it is drawn again.
|
||||
let kept = p.get("opacity").and_then(Value::as_f64).is_some() && super::graph::capture_series_opacity(d, &edited);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
// The graph keeps an opacity, paint or weight set on the topmost visible fill or stroke of its series art for when
|
||||
// it is drawn again, and hiding or showing a row changes which row that is.
|
||||
let mut opacities = top_opacity_changed(&before, d, &ids);
|
||||
if p.get("opacity").and_then(Value::as_f64).is_some() {
|
||||
opacities.extend(edited.iter().copied());
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &opacities);
|
||||
// A weight goes with the paint of its stroke; a stroke without paint leaves the series' paint alone.
|
||||
let written = edited.iter().copied().filter(|(_, fill)| paint.is_some() || (!*fill && p.get("weight").is_some()));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, written));
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
if let Some(pa) = &paint {
|
||||
s.remember_paint(pa);
|
||||
@@ -829,10 +915,12 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for &i in idx.iter().rev() {
|
||||
n.appearance.remove_item(i);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
s.remap_appearance_item(&ids, |a| (!idx.contains(&a)).then(|| a - idx.iter().filter(|i| **i < a).count()));
|
||||
ok()
|
||||
@@ -862,6 +950,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, C)?);
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
// showed it.
|
||||
let mut added = Vec::new();
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let has_contents = n.contents_label().is_some();
|
||||
@@ -877,9 +968,11 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if active == Some(*id) {
|
||||
active_at = Some(at);
|
||||
}
|
||||
let count = copies.len();
|
||||
for (k, item) in copies.into_iter().enumerate() {
|
||||
ap.insert_item(at + k, item);
|
||||
}
|
||||
added.extend((at..at + count).filter_map(|k| top_row_kind(ap, k)).map(|kind| (*id, kind)));
|
||||
if let Some(c) = contents.filter(|_| has_contents) {
|
||||
ap.set_contents_at(c);
|
||||
}
|
||||
@@ -893,6 +986,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(item) = ap.items.get(i).cloned() {
|
||||
first_at.get_or_insert(i + 1);
|
||||
ap.insert_item(i + 1, item);
|
||||
// Copies below this one go in lower down, so a copy that is the topmost row of its kind stays it.
|
||||
if let Some(kind) = top_row_kind(ap, i + 1) {
|
||||
added.push((*id, kind));
|
||||
}
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
@@ -901,6 +998,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("no item at index {}", idx[0])));
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
let mut rows = top_paint_changed(&before, d, &ids);
|
||||
rows.extend(painted_rows(d, added));
|
||||
super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(())
|
||||
})?;
|
||||
// Rows at or above each copy move up by one (by the block, for copies placed at `to`).
|
||||
@@ -918,11 +1018,26 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
|
||||
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = require_targets(s, p, "appearance.showAllHidden")?;
|
||||
let before = s.doc()?.doc.clone();
|
||||
let ids = s.edit("Show All Hidden Attributes", |d, _| {
|
||||
let shown: Vec<NodeId> = roots.iter().copied().filter(|id| d.node_mut(*id).is_some_and(|n| n.appearance.show_all())).collect();
|
||||
let shown: Vec<NodeId> = roots
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
d.node_mut(*id).is_some_and(|n| {
|
||||
let shown = n.appearance.show_all();
|
||||
if shown {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
shown
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if shown.is_empty() {
|
||||
return Err(EngineError::Other("Show All Hidden Attributes: nothing is hidden".into()));
|
||||
}
|
||||
super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown));
|
||||
super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown));
|
||||
Ok(shown)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
@@ -962,7 +1077,8 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids));
|
||||
Ok(count_changed(d, &before, &ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
// The moved row stays the active one; the rows it passed shift by one.
|
||||
s.remap_appearance_item(&ids, |a| {
|
||||
@@ -1006,7 +1122,8 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result<V
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, ids));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept))
|
||||
let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, ids));
|
||||
Ok(count_changed(d, &before, ids) + usize::from(kept || painted))
|
||||
})?;
|
||||
let m = idx.len();
|
||||
let landed = first_landed.unwrap_or(to);
|
||||
@@ -1069,6 +1186,42 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `reverse` or `append`"));
|
||||
}
|
||||
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.
|
||||
if !reverse
|
||||
&& !append
|
||||
&& !defaults_only
|
||||
&& p.get("ids").is_none()
|
||||
&& let Some((id, path)) = super::brushsym::selected_part(s)?
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
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))
|
||||
{
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
super::brushsym::edit_part(s, id, &path, "Eyedropper", |o| {
|
||||
if a.fill.color {
|
||||
o.fill = Some(fill);
|
||||
}
|
||||
if a.stroke.color {
|
||||
o.stroke = Some(stroke);
|
||||
}
|
||||
})?;
|
||||
// The clicked object becomes the Eyedropper's sample, and new art takes its paint.
|
||||
Picked::of(&src).to_defaults(s, &attrs.appearance);
|
||||
s.eyedropper_sample = Some(src);
|
||||
return Ok(json!({ "ids": [id.0] }));
|
||||
}
|
||||
let range = if !defaults_only && !reverse && !append && p.get("ids").is_none() {
|
||||
super::textedit::editing_range(s)?.filter(|(_, a, b)| a != b)
|
||||
} else {
|
||||
@@ -1160,8 +1313,41 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
picked.apply(n, &attrs, append);
|
||||
}
|
||||
}
|
||||
let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &targets));
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept))
|
||||
// The paints the pick wrote, with a weight going with the paint of its stroke, as in `set_item`. `append` adds
|
||||
// only the colors of the visible rows the source has.
|
||||
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
|
||||
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
|
||||
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let (paints, opacities) = if append {
|
||||
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
|
||||
(rows, rows)
|
||||
} else {
|
||||
(
|
||||
(fill.color, stroke.color || (stroke.weight && source_has(false))),
|
||||
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
|
||||
)
|
||||
};
|
||||
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
|
||||
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
|
||||
let top_shows = |id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
|
||||
};
|
||||
let written = |(fill, stroke): (bool, bool)| -> Vec<(NodeId, bool)> {
|
||||
targets
|
||||
.iter()
|
||||
.flat_map(|id| [fill.then_some((*id, true)), stroke.then_some((*id, false))])
|
||||
.flatten()
|
||||
.filter(|(id, kind)| rows_written || top_shows(*id, *kind))
|
||||
.collect()
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
|
||||
opacity_rows.extend(painted_rows(d, written(opacities)));
|
||||
let mut rows = top_paint_changed(&before, d, &targets);
|
||||
rows.extend(painted_rows(d, written(paints)));
|
||||
let kept = super::graph::capture_series_opacity(d, &opacity_rows);
|
||||
let painted = super::graph::capture_series_top_paints(d, &rows);
|
||||
Ok(count_changed(d, &before, &targets) + usize::from(kept || painted))
|
||||
})?;
|
||||
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
@@ -1243,6 +1429,7 @@ impl Picked {
|
||||
let placed = self.placed(n.geometric_bounds());
|
||||
n.appearance.items.extend(placed.items.into_iter().filter(|it| if it.is_fill() { ap.fill.color } else { ap.stroke.color }));
|
||||
n.appearance.effects.extend(placed.effects);
|
||||
super::object::snap_if_aligned(n);
|
||||
return;
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
@@ -1266,6 +1453,7 @@ impl Picked {
|
||||
} else {
|
||||
focal_attrs(&mut n.appearance, &placed, ap);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
//! settings Export for Screens shares (`document.exportSettings`). File → Export Selection collects
|
||||
//! the selection this way and opens Export for Screens on its Assets tab (a UI command).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{ExportAsset, NodeId};
|
||||
|
||||
use super::edit::{roots_of, selected_roots};
|
||||
use super::fileio::{SCREEN_SETTINGS_KEYS, check_screen_settings, export_crop, export_screens, store_screen_settings, with_screen_export_preset};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param};
|
||||
use super::fileio::{
|
||||
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
|
||||
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
|
||||
};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
|
||||
|
||||
/// The longest asset name kept (characters).
|
||||
const MAX_NAME: usize = 255;
|
||||
@@ -39,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)}]} 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), 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
|
||||
),
|
||||
@@ -48,10 +53,37 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default all), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
"{assets?: [asset id…] (default all but the 3D assets, which assets.export3D writes), folder?, zip?, openLocation?, formats?, preset?, settings?, prefix?, subfolders?, antiAlias?} each asset's art alone, cropped to it, in every format row: document.exportForScreens {assets} at the document's export settings (document.exportSettings) under the ones given; with subfolders false every file goes into the folder itself, mobile and density rows too → what document.exportForScreens returns (no folder: the files, or one zip, as dataBase64). Leaves the remembered settings as they are (assets.settings.set changes them)",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
cmd!(
|
||||
"assets.add3D",
|
||||
"Export 3D Object",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selected objects), format?: usda|usdz|gltf|obj (default usda)} collect each object with an Extrude & Bevel, Revolve, Inflate or Rotate effect as a 3D asset of Window › Asset Export, named after the object (else Asset 1, Asset 2…): assets.export3D writes it as a mesh file. An object already collected as a 3D asset keeps it; an object without such an effect is refused → {assets: [asset id…] (in order), added: n}",
|
||||
has_doc,
|
||||
add_3d
|
||||
),
|
||||
cmd!(
|
||||
"assets.set3DFormat",
|
||||
"3D Export Format",
|
||||
[],
|
||||
None,
|
||||
"{assets: [asset id…], format: usda|usdz|gltf|obj} the mesh format 3D assets export to (Asset Export's Format for a 3D asset) → {changed: n}",
|
||||
has_doc,
|
||||
set_3d_format
|
||||
),
|
||||
cmd!(
|
||||
"assets.export3D",
|
||||
"Export 3D Assets",
|
||||
[],
|
||||
None,
|
||||
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
|
||||
has_doc,
|
||||
export_3d
|
||||
),
|
||||
cmd!(
|
||||
"assets.settings.set",
|
||||
"Asset Export Settings",
|
||||
@@ -115,7 +147,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if name.is_some() && sets.len() > 1 {
|
||||
return Err(bad(C, "a name names one asset: give multiple: false, or one object"));
|
||||
}
|
||||
let existing = |d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes).map(|a| a.id);
|
||||
// A 3D asset of the same art is another asset.
|
||||
let existing =
|
||||
|d: &vectorcraft_doc::Document, nodes: &[NodeId]| d.assets.iter().find(|a| a.nodes == nodes && a.format_3d.is_none()).map(|a| a.id);
|
||||
let d = &s.doc()?.doc;
|
||||
// Nothing new: no undo step.
|
||||
if sets.iter().all(|set| existing(d, set).is_some()) {
|
||||
@@ -134,7 +168,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let name = name.clone().or(own).unwrap_or_else(|| d.next_asset_name());
|
||||
let id = d.alloc_id().0;
|
||||
d.assets.push(ExportAsset { id, name, nodes });
|
||||
d.assets.push(ExportAsset { id, name, nodes, format_3d: None });
|
||||
out.push(id);
|
||||
added += 1;
|
||||
}
|
||||
@@ -142,6 +176,162 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The format of param `format` of command `cmd` ([`FORMATS_3D`]), `default` when it is not given.
|
||||
fn format_3d_param(p: &Value, cmd: &str, default: Option<&str>) -> Result<String> {
|
||||
match (p.get("format"), default) {
|
||||
(None, Some(d)) => Ok(d.to_string()),
|
||||
(Some(Value::String(f)), _) if FORMATS_3D.contains(&f.as_str()) => Ok(f.clone()),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", FORMATS_3D.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key` of command `cmd`, each a 3D asset of `d`.
|
||||
fn three_d_asset_ids(d: &vectorcraft_doc::Document, p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = asset_ids(p, key, cmd)?;
|
||||
for id in &ids {
|
||||
match d.asset(*id) {
|
||||
None => return Err(bad(cmd, "no such assets (see assets.list)")),
|
||||
Some(a) if a.format_3d.is_none() => return Err(bad(cmd, format!("asset {id} isn't a 3D asset"))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn add_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.add3D";
|
||||
let format = format_3d_param(p, C, Some(DEFAULT_FORMAT_3D))?;
|
||||
let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { selected_roots(s)? };
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect (or give its ids)"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let mut ids = d.paint_order(ids);
|
||||
ids.dedup();
|
||||
for id in &ids {
|
||||
let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?;
|
||||
if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) {
|
||||
let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0));
|
||||
return Err(bad(C, format!("{what} can't be exported in 3D: {e}")));
|
||||
}
|
||||
}
|
||||
let existing = |d: &vectorcraft_doc::Document, id: NodeId| d.assets.iter().find(|a| a.nodes == [id] && a.format_3d.is_some()).map(|a| a.id);
|
||||
// Nothing new: no undo step.
|
||||
if ids.iter().all(|id| existing(d, *id).is_some()) {
|
||||
return Ok(json!({ "assets": ids.iter().filter_map(|id| existing(d, *id)).collect::<Vec<_>>(), "added": 0 }));
|
||||
}
|
||||
s.edit("Export 3D Object", |d, _| {
|
||||
let (mut out, mut added) = (vec![], 0);
|
||||
for node in ids {
|
||||
if let Some(id) = existing(d, node) {
|
||||
out.push(id);
|
||||
continue;
|
||||
}
|
||||
let name = d.node(node).and_then(|n| n.name.as_deref()).and_then(clean_name).unwrap_or_else(|| d.next_asset_name());
|
||||
let id = d.alloc_id().0;
|
||||
d.assets.push(ExportAsset { id, name, nodes: vec![node], format_3d: Some(format.clone()) });
|
||||
out.push(id);
|
||||
added += 1;
|
||||
}
|
||||
Ok(json!({ "assets": out, "added": added }))
|
||||
})
|
||||
}
|
||||
|
||||
fn set_3d_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.set3DFormat";
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = three_d_asset_ids(d, p, "assets", C)?;
|
||||
let format = format_3d_param(p, C, None)?;
|
||||
let changed = d.assets.iter().filter(|a| ids.contains(&a.id) && a.format_3d.as_deref() != Some(format.as_str())).count();
|
||||
// Nothing changes: no undo step.
|
||||
if changed == 0 {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
s.edit("3D Export Format", |d, _| {
|
||||
for a in d.assets.iter_mut().filter(|a| ids.contains(&a.id)) {
|
||||
a.format_3d = Some(format.clone());
|
||||
}
|
||||
Ok(json!({ "changed": changed }))
|
||||
})
|
||||
}
|
||||
|
||||
fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "assets.export3D";
|
||||
let d = &s.doc()?.doc;
|
||||
let ids = if p.get("assets").is_some_and(|v| !v.is_null()) {
|
||||
three_d_asset_ids(d, p, "assets", C)?
|
||||
} else {
|
||||
d.assets.iter().filter(|a| a.format_3d.is_some()).map(|a| a.id).collect()
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "no 3D assets yet: collect an object with a 3D effect first (assets.add3D)"));
|
||||
}
|
||||
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
|
||||
let zip = switch_or(p, "zip", false, C)?;
|
||||
// Every file's name, compared without case: a later file that would take one gets -2, -3…
|
||||
let mut taken: HashSet<String> = HashSet::new();
|
||||
let mut files: Vec<(String, Vec<u8>)> = vec![];
|
||||
for id in ids {
|
||||
let Some(a) = d.asset(id) else { continue };
|
||||
let format = a.format_3d.as_deref().unwrap_or(DEFAULT_FORMAT_3D);
|
||||
let mut parts = vec![];
|
||||
for node in &a.nodes {
|
||||
let n = d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))?;
|
||||
let what = &a.name;
|
||||
parts.extend(vectorcraft_render::effects::three_d_meshes(n).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?);
|
||||
}
|
||||
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
|
||||
let mut stem = base.clone();
|
||||
let mut k = 1;
|
||||
loop {
|
||||
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
|
||||
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
|
||||
break;
|
||||
}
|
||||
k += 1;
|
||||
stem = format!("{base}-{k}");
|
||||
}
|
||||
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
|
||||
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
|
||||
files.extend(made);
|
||||
}
|
||||
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
|
||||
if zip {
|
||||
let archive = super::fileio::zip::store(&files).map_err(|e| bad(C, e))?;
|
||||
// "-3D" keeps it apart from the picture assets' ZIP, which is named after the document.
|
||||
let name = Some(safe_file_name(&d.title)).filter(|t| !t.is_empty()).map_or_else(|| "3D Assets.zip".into(), |t| format!("{t}-3D.zip"));
|
||||
return match folder {
|
||||
Some(dir) => {
|
||||
create_dir(dir)?;
|
||||
let path = format!("{dir}/{name}");
|
||||
write_file(&path, &archive)?;
|
||||
Ok(json!({ "path": path, "bytes": archive.len(), "files": names }))
|
||||
}
|
||||
None => Ok(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(&archive), "bytes": archive.len(), "files": names })),
|
||||
};
|
||||
}
|
||||
match folder {
|
||||
Some(dir) => {
|
||||
create_dir(dir)?;
|
||||
let mut written = vec![];
|
||||
for (name, bytes) in &files {
|
||||
let path = format!("{dir}/{name}");
|
||||
write_file(&path, bytes)?;
|
||||
written.push(path);
|
||||
}
|
||||
Ok(json!({ "files": written }))
|
||||
}
|
||||
None => {
|
||||
let files: Vec<Value> =
|
||||
files.iter().map(|(name, bytes)| json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) })).collect();
|
||||
Ok(json!({ "files": files }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The asset ids of param `key`.
|
||||
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
|
||||
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
|
||||
@@ -186,6 +376,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"name": a.name,
|
||||
"nodes": a.nodes.iter().map(|n| n.0).collect::<Vec<_>>(),
|
||||
"bounds": bounds.map(|b| [b.x0, b.y0, b.width(), b.height()]),
|
||||
"format3D": a.format_3d,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -227,8 +418,10 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if q.get("subfolders").and_then(Value::as_bool) == Some(false) && p.get("folders").is_none() {
|
||||
q.insert("folders".into(), json!("none"));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// 3D assets are written as mesh files, by assets.export3D: the export refuses one it is given.
|
||||
if !q.contains_key("assets") {
|
||||
let all: Vec<u64> = s.doc()?.doc.assets.iter().map(|a| a.id).collect();
|
||||
let all: Vec<u64> = d.assets.iter().filter(|a| a.format_3d.is_none()).map(|a| a.id).collect();
|
||||
if all.is_empty() {
|
||||
return Err(bad(C, "no assets yet: collect art for export first (assets.add)"));
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ use super::{
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
/// Whether Reset Transformation changes a symbol instance.
|
||||
pub use symbols::reset_transformation_changes;
|
||||
|
||||
mod brushes;
|
||||
mod dynamic;
|
||||
mod symbols;
|
||||
@@ -33,15 +36,16 @@ use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_set_appearance};
|
||||
pub(crate) use dynamic::{edit_part, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol,
|
||||
stored_natural_size,
|
||||
};
|
||||
use symbols::{
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_list, symbol_new, symbol_options, symbol_place, symbol_replace,
|
||||
symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options,
|
||||
symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
|
||||
};
|
||||
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
@@ -140,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest, half way on a stroke drawn without pressure), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
@@ -263,6 +267,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
symbol_instance_set_appearance
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.selectPart",
|
||||
"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}",
|
||||
has_doc,
|
||||
symbol_instance_select_part
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.reset",
|
||||
"Reset Symbol Instance",
|
||||
@@ -272,6 +285,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
symbol_instance_reset
|
||||
),
|
||||
cmd!(
|
||||
"symbol.instance.resetTransform",
|
||||
"Reset Transformation",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?} give the selected symbol instances (in groups too) their symbol's own scale, without rotation, shear or reflection, keeping the center of each one's bounding box in place, as one undo step; other objects, instances in perspective and instances already at their symbol's scale are left as they are, and no undo step is added when nothing changes; an id naming no object, or no symbol instance among the objects, is an error → {ids: the instances changed}",
|
||||
has_selection,
|
||||
symbol_instance_reset_transform
|
||||
),
|
||||
cmd!(
|
||||
"symbol.setCurrent",
|
||||
"Current Symbol",
|
||||
|
||||
@@ -61,6 +61,62 @@ fn dynamic_instance(s: &Session, p: &Value, cmd: &str) -> Result<(NodeId, Arc<No
|
||||
Ok((id, sym.art.clone()))
|
||||
}
|
||||
|
||||
/// The selected object of a dynamic symbol instance's art (Direct Selection): the instance and the
|
||||
/// object's path in the symbol's art.
|
||||
pub(crate) fn selected_part(s: &Session) -> Result<Option<(NodeId, Vec<u32>)>> {
|
||||
Ok(s.doc()?.selection.symbol_part.as_ref().map(|sp| (sp.instance, sp.path.clone())))
|
||||
}
|
||||
|
||||
/// Change instance `id`'s own appearance for the object at `path` of its art by `f`, as one undo
|
||||
/// step named `label`; nothing is recorded when the change leaves it as it was. Replies how many
|
||||
/// objects the instance changes.
|
||||
pub(crate) fn edit_part(s: &mut Session, id: NodeId, path: &[u32], label: &str, f: impl FnOnce(&mut SymbolOverride)) -> Result<usize> {
|
||||
let list = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.extras().symbol_overrides.clone();
|
||||
let old = list.iter().find(|o| o.path == path).cloned().unwrap_or_else(|| SymbolOverride { path: path.to_vec(), ..Default::default() });
|
||||
let mut new = old.clone();
|
||||
f(&mut new);
|
||||
if new == old {
|
||||
return Ok(list.len());
|
||||
}
|
||||
s.edit(label, |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut e = n.extras_mut();
|
||||
let list = &mut e.symbol_overrides;
|
||||
list.retain(|o| o.path != path);
|
||||
if !new.is_empty() {
|
||||
list.push(new);
|
||||
}
|
||||
Ok(list.len())
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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())
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_select_part(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "symbol.instance.selectPart";
|
||||
if p.get("id").is_none() {
|
||||
return Err(bad(C, "missing id"));
|
||||
}
|
||||
let (id, art) = dynamic_instance(s, p, C)?;
|
||||
let path = path_param(p, &art, C)?;
|
||||
// Direct Selection passes over hidden, locked and template objects, and over everything in a
|
||||
// group or layer that is: the instance in the document, and the object in the symbol's art.
|
||||
let editable = |n: &Node| n.visible && !n.locked && !n.is_template();
|
||||
if !s.doc()?.doc.is_editable(id) || !(0..=path.len()).all(|k| symbol_overrides::part(&art, &path[..k]).is_some_and(editable)) {
|
||||
return Err(bad(C, "the object is hidden or locked"));
|
||||
}
|
||||
if !symbol_overrides::part(&art, &path).is_some_and(symbol_overrides::takes_part_paint) {
|
||||
return Err(part_only());
|
||||
}
|
||||
let shown = json!(path);
|
||||
s.select(|_, sel| sel.set_symbol_part(id, path))?;
|
||||
Ok(json!({ "id": id.0, "path": shown }))
|
||||
}
|
||||
|
||||
/// The `path` param: child indices from the art's root, naming an object of `art`.
|
||||
fn path_param(p: &Value, art: &Node, cmd: &str) -> Result<Vec<u32>> {
|
||||
let path: Option<Vec<u32>> =
|
||||
@@ -117,16 +173,7 @@ pub(super) fn symbol_instance_set_appearance(s: &mut Session, p: &Value) -> Resu
|
||||
let d = &s.doc()?.doc;
|
||||
let old = d.node(id).and_then(|n| n.extras().symbol_overrides.iter().find(|o| o.path == path).cloned());
|
||||
let new = changed(s, p, old.unwrap_or_else(|| SymbolOverride { path: path.clone(), ..Default::default() }), C)?;
|
||||
let count = s.edit("Symbol Instance Appearance", |d, _| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
let mut e = n.extras_mut();
|
||||
let list = &mut e.symbol_overrides;
|
||||
list.retain(|o| o.path != path);
|
||||
if !new.is_empty() {
|
||||
list.push(new);
|
||||
}
|
||||
Ok(list.len())
|
||||
})?;
|
||||
let count = edit_part(s, id, &path, "Symbol Instance Appearance", |o| *o = new)?;
|
||||
Ok(json!({ "id": id.0, "overrides": count }))
|
||||
}
|
||||
|
||||
|
||||
@@ -696,6 +696,62 @@ pub(super) fn symbol_replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// How far a transform coefficient may be from Reset Transformation's for the instance to count as
|
||||
/// already reset.
|
||||
const RESET_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// The transform Reset Transformation gives instance `n` of the document of `boxes`: its symbol's
|
||||
/// own scale, without rotation, shear or reflection, with the center of its art's bounding box
|
||||
/// where it is. `None` when [`reset_transformation_changes`] is false for `n`.
|
||||
fn reset_transformation(boxes: &vectorcraft_doc::SymbolBoxes, n: &Node) -> Option<Affine> {
|
||||
let d = boxes.document();
|
||||
if !reset_transformation_changes(d, n) {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
|
||||
let scale = d.symbol_natural_xf(symbol);
|
||||
// The art's box in symbol space (the ±HALF square when the art cannot be measured): its
|
||||
// center keeps its place on the page.
|
||||
let art = boxes.art_bounds(symbol).unwrap_or_else(|| vectorcraft_geom::Rect::new(-HALF, -HALF, HALF, HALF));
|
||||
let center = xf.transform_rect_bbox(art).center();
|
||||
Some(Affine::translate(center - scale * art.center()) * scale)
|
||||
}
|
||||
|
||||
/// Does Reset Transformation change `n`? True for an instance of a symbol `d` holds, not in
|
||||
/// perspective, whose scale, rotation, shear or reflection differs from the symbol's own scale
|
||||
/// (its stored natural size, or the art unscaled when that size is not positive and finite).
|
||||
/// It does not measure the art.
|
||||
pub fn reset_transformation_changes(d: &Document, n: &Node) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return false };
|
||||
if n.extras().perspective.is_some() || !d.symbols.iter().any(|s| s.name == *symbol) {
|
||||
return false;
|
||||
}
|
||||
let natural = d.symbol_natural_xf(symbol).as_coeffs();
|
||||
xf.as_coeffs()[..4].iter().zip(&natural[..4]).any(|(a, b)| (a - b).abs() > RESET_TOLERANCE)
|
||||
}
|
||||
|
||||
pub(super) fn symbol_instance_reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_instances(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no symbol instances selected".into()));
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
let boxes = d.symbol_boxes();
|
||||
let changes: Vec<(NodeId, Affine)> = ids.iter().filter_map(|id| Some((*id, reset_transformation(&boxes, d.node(*id)?)?))).collect();
|
||||
if !changes.is_empty() {
|
||||
s.edit("Reset Transformation", |d, _| {
|
||||
for (id, new) in &changes {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
*xf = *new;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let changed: Vec<NodeId> = changes.iter().map(|(id, _)| *id).collect();
|
||||
Ok(json!({ "ids": ids_json(&changed) }))
|
||||
}
|
||||
|
||||
pub(super) fn symbol_set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = resolve_symbol(&s.doc()?.doc, p, "symbol.setCurrent")?;
|
||||
set_unknown(s, CURRENT_SYMBOL, Some(json!(name)))?;
|
||||
@@ -832,6 +888,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0);
|
||||
let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0;
|
||||
let alt = switch_or(p, "alt", false, C)?;
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
crate::cmd::edit::refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let color = match color_param(p, "color", C)? {
|
||||
Some(c) => crate::cmd::paint::new_color(s, p, c),
|
||||
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, white is always its own colour, at most ten; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white unless ignoreWhite makes them holes; fills/strokes are ignored; gradients and photos are refused)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -153,7 +153,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make and Expand",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{…as imageTrace.make} same as imageTrace.make, then expand → {id, paths, anchors, colors}",
|
||||
"{…as imageTrace.make, byColor?: false (each color's paths in a group of their own, as imageTrace.expand)} same as imageTrace.make, then expand → {id, paths, anchors, colors}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, true)
|
||||
),
|
||||
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?, ids?: [id…] (instead of id)} keep only the traced paths (drop the source image) → {ids}",
|
||||
"{id?, ids?: [id…] (instead of id), byColor?: false (each color's paths in a group of their own, named by the swatch the color links to or as #rrggbb, gradient fills in one group named Gradients; the groups stack by their lowest path and keep their paths' order; a color whose paths overlap another color's from above and below gets a group for each part, so the art draws the same; refused for a trace made with autoGrouping and for a trace with a live Pathfinder effect)} keep only the traced paths (drop the source image) → {ids}",
|
||||
has_selection_or_ids,
|
||||
trace_expand
|
||||
),
|
||||
|
||||
@@ -4,10 +4,16 @@ use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::ImageObject;
|
||||
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point,
|
||||
Appearance, AppearanceItem, Arc, Beside, Color, Document, EngineError, LineCap, LineJoin, LiveShape, Node, NodeId, NodeKind, Paint, Point, Rect,
|
||||
Result, Session, StrokeLayer, TRACE_NAME, TraceView, Value, bad, fill_only, ids_json, json, root_ids, shape_node, str_param, switch_or, tr,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
// ---------- Image Trace ----------
|
||||
|
||||
fn is_trace_group(n: &Node) -> bool {
|
||||
@@ -16,6 +22,8 @@ fn is_trace_group(n: &Node) -> bool {
|
||||
&& n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_))))
|
||||
}
|
||||
|
||||
const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor";
|
||||
|
||||
/// The `view` param ([`TraceView`] id), if given.
|
||||
fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
let Some(v) = p.get("view").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
@@ -368,6 +376,156 @@ fn grouped(d: &mut Document, nodes: Vec<Node>, parents: &[Option<usize>]) -> Vec
|
||||
roots.iter().filter_map(|&r| built.get_mut(r)?.take()).chain(ring).collect()
|
||||
}
|
||||
|
||||
/// The `byColor` param of an Expand (false when not given).
|
||||
fn by_color_param(cmd: &str, p: &Value) -> Result<bool> {
|
||||
match p.get("byColor").filter(|v| !v.is_null()) {
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "byColor must be true or false")),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand by color: an expanded trace's `items` (bottom-most first) in a group for each paint, a
|
||||
/// stroked line counted by its stroke. A solid color's group is named by the swatch it links to (a
|
||||
/// tint with its percentage) or as `#rrggbb`, and gradient fills share one group, "Gradients". The
|
||||
/// groups stack in the order of the lowest item in each, and each keeps its items' order. When the
|
||||
/// paths meet, an item joins its paint's last group only if no item of a later group meets it
|
||||
/// (by the boxes of everything they paint, effects included, within one point); otherwise it
|
||||
/// starts another group of that paint, which keeps the stacking order of those items. Items
|
||||
/// farther apart can still share antialiased pixels at small view or raster-export scales, so
|
||||
/// their edge pixels may change. A group among `items` (Auto Grouping) is refused.
|
||||
fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Vec<Arc<Node>>> {
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::ops::Bound::{Excluded, Unbounded};
|
||||
use vectorcraft_color::tint_percent;
|
||||
// Grouped by the paint: unlinked (its #rrggbb), linked (the swatch and its exact tint), a
|
||||
// gradient, or another paint (its label). The name is apart from it: a swatch may be named as
|
||||
// a color's `#rrggbb` or as "Gradients".
|
||||
type PaintKey = (u8, String, u32);
|
||||
struct Run {
|
||||
name: String,
|
||||
members: Vec<Arc<Node>>,
|
||||
}
|
||||
// Boxes closer than a point count as overlapping: their antialiased edges can share pixels.
|
||||
let meet = |a: &Rect, b: &Rect| {
|
||||
#[cfg(test)]
|
||||
BOX_TESTS.with(|n| n.set(n.get() + 1));
|
||||
let b = b.inflate(1.0, 1.0);
|
||||
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
|
||||
};
|
||||
// Choose a cell size from the painted extent and path count. A box over more than eight cells
|
||||
// across but at most eight down (a stripe) is indexed by its rows, one the other way round by
|
||||
// its columns, and one over more than eight both ways stays in a separate list, keeping the
|
||||
// index bounded even when a path covers most of the document.
|
||||
let items: Vec<_> = items
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let bounds = vectorcraft_render::painted_bounds(d, &item);
|
||||
(item, bounds)
|
||||
})
|
||||
.collect();
|
||||
let extent = items.iter().filter_map(|(_, b)| *b).reduce(|a, b| a.union(b));
|
||||
let cell_size = extent.map_or(1.0, |r| ((r.x1 - r.x0).abs() * (r.y1 - r.y0).abs() / items.len().max(1) as f64).sqrt().max(1.0));
|
||||
// The first and last column and row of the cells `r` covers; `None` when it isn't finite.
|
||||
let span = |r: Rect| -> Option<(i64, i64, i64, i64)> {
|
||||
let coord = |v: f64| (v / cell_size).floor() as i64;
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then(|| (coord(r.x0), coord(r.y0), coord(r.x1), coord(r.y1)))
|
||||
};
|
||||
let count = |first: i64, last: i64| i128::from(last) - i128::from(first) + 1;
|
||||
// A box over more cells than this is checked against every box.
|
||||
const MAX_CELLS: i128 = 1024;
|
||||
let mut groups: Vec<Run> = vec![];
|
||||
let mut latest: HashMap<PaintKey, usize> = HashMap::new();
|
||||
// An item can join an earlier group, so insertion order is not group-index order. Index
|
||||
// boxes by group to skip older groups without scanning their entries.
|
||||
let mut spatial: HashMap<(i64, i64), BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut rows: HashMap<i64, BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut columns: HashMap<i64, BTreeMap<usize, Vec<Rect>>> = HashMap::new();
|
||||
let mut large: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
let mut all_boxes: BTreeMap<usize, Vec<Rect>> = BTreeMap::new();
|
||||
for (item, bounds) in items {
|
||||
if matches!(item.kind, NodeKind::Group { .. }) {
|
||||
return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
let paint = match item.appearance.fill_paint() {
|
||||
Paint::None => item.appearance.stroke_paint(),
|
||||
fill => fill,
|
||||
};
|
||||
let (key, name) = match &paint {
|
||||
Paint::Solid { swatch: Some(n), tint, .. } => {
|
||||
let percent = tint_percent(*tint);
|
||||
let name = if *tint < 1.0 { format!("{n} {percent}%") } else { n.clone() };
|
||||
((1, n.clone(), tint.to_bits()), name)
|
||||
}
|
||||
Paint::Solid { color, .. } => ((0, color.to_hex(), 0), color.to_hex()),
|
||||
Paint::Gradient(_) => ((2, String::new(), 0), "Gradients".to_string()),
|
||||
other => ((3, other.label(), 0), other.label()),
|
||||
};
|
||||
// Joining an earlier group moves the item under every later group's items.
|
||||
let hidden_by_later = |at: usize| {
|
||||
bounds.is_some_and(|b| {
|
||||
let overlaps_later = |boxes: &BTreeMap<usize, Vec<Rect>>| {
|
||||
boxes.range((Excluded(at), Unbounded)).rev().any(|(_, group_boxes)| {
|
||||
group_boxes.iter().rev().any(|box_bounds| {
|
||||
#[cfg(test)]
|
||||
CANDIDATE_VISITS.with(|n| n.set(n.get() + 1));
|
||||
meet(box_bounds, &b)
|
||||
})
|
||||
})
|
||||
};
|
||||
match span(b) {
|
||||
Some((x0, y0, x1, y1)) if count(x0, x1) * count(y0, y1) <= MAX_CELLS => {
|
||||
(y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))).filter_map(|c| spatial.get(&c)).any(overlaps_later)
|
||||
|| (y0..=y1).filter_map(|y| rows.get(&y)).any(overlaps_later)
|
||||
|| (x0..=x1).filter_map(|x| columns.get(&x)).any(overlaps_later)
|
||||
|| overlaps_later(&large)
|
||||
}
|
||||
_ => overlaps_later(&all_boxes),
|
||||
}
|
||||
})
|
||||
};
|
||||
let at = latest.get(&key).copied().filter(|&at| !hidden_by_later(at));
|
||||
let mut started = Run { name, members: vec![] };
|
||||
let joins = at.and_then(|at| groups.get_mut(at));
|
||||
let new = joins.is_none();
|
||||
let g = joins.unwrap_or(&mut started);
|
||||
g.members.push(item);
|
||||
if new {
|
||||
groups.push(started);
|
||||
latest.insert(key, groups.len() - 1);
|
||||
}
|
||||
if let Some(b) = bounds {
|
||||
let index = if new { groups.len() - 1 } else { at.unwrap_or_default() };
|
||||
all_boxes.entry(index).or_default().push(b);
|
||||
match span(b.inflate(1.0, 1.0)) {
|
||||
Some((x0, y0, x1, y1)) if count(x0, x1) <= 8 && count(y0, y1) <= 8 => {
|
||||
for place in (y0..=y1).flat_map(|y| (x0..=x1).map(move |x| (x, y))) {
|
||||
spatial.entry(place).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
Some((_, y0, _, y1)) if count(y0, y1) <= 8 => {
|
||||
for y in y0..=y1 {
|
||||
rows.entry(y).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
Some((x0, _, x1, _)) if count(x0, x1) <= 8 => {
|
||||
for x in x0..=x1 {
|
||||
columns.entry(x).or_default().entry(index).or_default().push(b);
|
||||
}
|
||||
}
|
||||
_ => large.entry(index).or_default().push(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(groups
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let mut g = Node::group(d.alloc_id(), run.members);
|
||||
g.name = Some(run.name);
|
||||
Arc::new(g)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
|
||||
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
|
||||
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
|
||||
@@ -398,6 +556,10 @@ struct Prepared {
|
||||
fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let mut params = trace_params(s, c, p)?;
|
||||
let view = view_param(c, p)?;
|
||||
let by_color = c == "imageTrace.makeAndExpand" && by_color_param(c, p)?;
|
||||
if by_color && params.auto_grouping {
|
||||
return Err(bad(c, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
let params_json = serde_json::to_value(¶ms).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// The preset's name if the parameters are exactly that preset's or its enhanced version's (a
|
||||
// saved preset's under its saved name), else "Custom".
|
||||
@@ -428,6 +590,9 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
let blob = s.doc()?.doc.images.get(&image.key).ok_or_else(|| EngineError::Other(format!("image data `{}` is missing", image.key)))?;
|
||||
let bytes = Arc::clone(&blob.bytes);
|
||||
let library = trace_library(c, s, &mut params)?;
|
||||
@@ -533,6 +698,7 @@ impl TraceRun {
|
||||
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
|
||||
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
|
||||
let group_by_color = expand && by_color_param(c, p)?;
|
||||
// A saved preset's settings join the journal entry, so a replay traces as this run did after
|
||||
// the preset is changed, renamed or deleted.
|
||||
let named = str_param(p, "preset").unwrap_or("Default");
|
||||
@@ -608,6 +774,9 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
traced.push(n);
|
||||
}
|
||||
children.extend(grouped(d, traced, &res.parents));
|
||||
if group_by_color {
|
||||
children = color_groups(c, d, children)?;
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
@@ -706,7 +875,20 @@ pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.expand";
|
||||
let by_color = by_color_param(C, p)?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
if by_color {
|
||||
// A trace made with Auto Grouping is refused even when none of its paths were grouped.
|
||||
let d = &s.doc()?.doc;
|
||||
let grouped = |n: &Node| n.extras().trace.as_deref().and_then(|t| t.pointer("/params/autoGrouping")).and_then(Value::as_bool) == Some(true);
|
||||
if targets.iter().any(|g| d.node(*g).is_some_and(grouped)) {
|
||||
return Err(bad(C, "byColor can't split Auto Grouping groups: trace without Auto Grouping"));
|
||||
}
|
||||
if targets.iter().any(|g| d.node(*g).is_some_and(vectorcraft_render::effects::has_pathfinder)) {
|
||||
return Err(bad(C, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
}
|
||||
s.edit("Expand Image Trace", |d, sel| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
@@ -715,6 +897,15 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
}
|
||||
if by_color {
|
||||
let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default();
|
||||
// The paths may have been moved or reshaped since the trace was made, so any trace's
|
||||
// paths are taken to overlap.
|
||||
let groups = color_groups(C, d, items)?;
|
||||
if let Some(ch) = d.node_mut(*g).and_then(Node::children_mut) {
|
||||
*ch = groups;
|
||||
}
|
||||
}
|
||||
}
|
||||
sel.set(targets.iter().copied());
|
||||
Ok(())
|
||||
@@ -722,6 +913,160 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&targets) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod color_group_tests {
|
||||
use super::*;
|
||||
use vectorcraft_geom::{PathData, SubPath};
|
||||
|
||||
fn area(d: &mut Document, x0: f64, y0: f64, x1: f64, y1: f64, color: Color) -> Arc<Node> {
|
||||
let path = PathData::single(SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true));
|
||||
Arc::new(Node::path(d.alloc_id(), path, fill_only(Paint::solid(color))))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abutting_color_groups_preserve_order_at_shared_edges() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let a = Color::rgb(1.0, 0.0, 0.0);
|
||||
let b = Color::rgb(0.0, 0.0, 1.0);
|
||||
let items = vec![area(&mut d, 0.0, 0.0, 20.0, 20.0, a), area(&mut d, 20.0, 0.0, 40.0, 20.0, b), area(&mut d, 40.0, 0.0, 60.0, 20.0, a)];
|
||||
let original: Vec<_> = items.iter().map(|n| n.id).collect();
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let actual: Vec<_> = groups.iter().flat_map(|g| g.children().unwrap().iter().map(|n| n.id)).collect();
|
||||
assert_eq!(actual, original, "shared-edge paths changed stacking order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dense_color_groups_use_bounded_box_tests() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let a = Color::rgb(1.0, 0.0, 0.0);
|
||||
let b = Color::rgb(0.0, 0.0, 1.0);
|
||||
let items = (0..4000)
|
||||
.map(|i| {
|
||||
if i % 2 == 0 {
|
||||
let x = 100.0 + (i % 40) as f64 * 0.01;
|
||||
area(&mut d, x, 100.0, x + 0.1, 100.1, a)
|
||||
} else {
|
||||
let x = if i % 4 == 1 { 0.0 } else { 198.0 };
|
||||
area(&mut d, x, x, x + 2.0, x + 2.0, b)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
BOX_TESTS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let tests = BOX_TESTS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.iter().map(|g| g.children().map_or(0, Vec::len)).sum::<usize>(), 4000);
|
||||
assert!(tests < 4000 * 32, "{tests} box tests for 4000 paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_alternating_colors_visit_bounded_candidates() {
|
||||
const COUNT: usize = 3000;
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
|
||||
let items = (0..COUNT).map(|i| area(&mut d, 10.0, 10.0, 20.0, 20.0, colors[i % 2])).collect();
|
||||
CANDIDATE_VISITS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let visits = CANDIDATE_VISITS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.len(), COUNT);
|
||||
assert!(visits < COUNT * 16, "{visits} candidate visits for {COUNT} paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_stripes_of_alternating_colors_visit_bounded_candidates() {
|
||||
const COUNT: usize = 2000;
|
||||
let mut d = Document::new(1000.0, 4000.0);
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
|
||||
for tall in [false, true] {
|
||||
let items = (0..COUNT)
|
||||
.map(|i| {
|
||||
let at = i as f64 * 2.0;
|
||||
if tall { area(&mut d, at, 0.0, at + 0.5, 1000.0, colors[i % 2]) } else { area(&mut d, 0.0, at, 1000.0, at + 0.5, colors[i % 2]) }
|
||||
})
|
||||
.collect();
|
||||
CANDIDATE_VISITS.with(|n| n.set(0));
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let visits = CANDIDATE_VISITS.with(std::cell::Cell::get);
|
||||
assert_eq!(groups.len(), 2, "tall {tall}");
|
||||
assert!(visits < COUNT * 32, "tall {tall}: {visits} candidate visits for {COUNT} stripes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spatial_color_groups_match_simple_scan() {
|
||||
let colors = [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::rgb(0.0, 1.0, 0.0)];
|
||||
for layout in 0..6 {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let items: Vec<_> = (0..90)
|
||||
.map(|i| {
|
||||
let x = match layout {
|
||||
0 => i as f64 * 2.0,
|
||||
1 => (i % 10) as f64 * 5.0,
|
||||
2 => (i % 7) as f64 * 3.0,
|
||||
3 => (i % 13) as f64 * 9.0,
|
||||
4 => (i % 4) as f64 * 10.0,
|
||||
_ => i as f64 * 1.5,
|
||||
};
|
||||
let y = match layout {
|
||||
0 => 0.0,
|
||||
1 => (i / 10) as f64 * 5.0,
|
||||
2 => (i / 7) as f64 * 3.0,
|
||||
3 => (i / 13) as f64 * 9.0,
|
||||
4 => i as f64 * 1.5,
|
||||
_ => (i % 4) as f64 * 10.0,
|
||||
};
|
||||
// Layouts 4 and 5: wide and tall stripes, some meeting their neighbors.
|
||||
let (w, h) = match layout {
|
||||
4 => (150.0, 1.0),
|
||||
5 => (1.0, 150.0),
|
||||
_ => (3.0, 3.0),
|
||||
};
|
||||
area(&mut d, x, y, x + w, y + h, colors[i % 3])
|
||||
})
|
||||
.collect();
|
||||
let mut expected: Vec<(String, Vec<(NodeId, Rect)>)> = vec![];
|
||||
for item in &items {
|
||||
let key = item.appearance.fill_paint().color().unwrap().to_hex();
|
||||
let bounds = vectorcraft_render::painted_bounds(&d, item).unwrap();
|
||||
let previous = expected.iter().rposition(|(k, _)| *k == key);
|
||||
let can_join = previous.filter(|&at| {
|
||||
!expected.iter().skip(at + 1).any(|(_, boxes)| {
|
||||
boxes.iter().any(|(_, m)| {
|
||||
let b = bounds.inflate(1.0, 1.0);
|
||||
m.x0 < b.x1 && b.x0 < m.x1 && m.y0 < b.y1 && b.y0 < m.y1
|
||||
})
|
||||
})
|
||||
});
|
||||
match can_join.and_then(|at| expected.get_mut(at)) {
|
||||
Some((_, members)) => members.push((item.id, bounds)),
|
||||
None => expected.push((key, vec![(item.id, bounds)])),
|
||||
}
|
||||
}
|
||||
let actual = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let actual: Vec<Vec<_>> = actual.iter().map(|g| g.children().unwrap().iter().map(|n| n.id).collect()).collect();
|
||||
let expected: Vec<Vec<_>> = expected.into_iter().map(|(_, members)| members.into_iter().map(|(id, _)| id).collect()).collect();
|
||||
assert_eq!(actual, expected, "layout {layout}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_abutting_gradient_stays_above_the_solid_area_it_borders() {
|
||||
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let ramp = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops.clone()))));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let mut area = |x0: f64, x1: f64, paint: Paint| {
|
||||
let path =
|
||||
PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 60.0), Point::new(x0, 60.0)], true));
|
||||
Arc::new(Node::path(d.alloc_id(), path, fill_only(paint)))
|
||||
};
|
||||
// A gradient, a solid area beside it and a second gradient beside that, bottom to top.
|
||||
let items = vec![area(0.0, 50.0, ramp()), area(50.0, 80.0, Paint::solid(Color::rgb(0.2, 0.6, 0.2))), area(80.0, 100.0, ramp())];
|
||||
let groups = color_groups("imageTrace.makeAndExpand", &mut d, items).unwrap();
|
||||
let names: Vec<_> = groups.iter().map(|g| g.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, ["Gradients", "#339933", "Gradients"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod trace_limit_tests {
|
||||
use super::{MAX_TRACE_ANCHORS, trace_warnings};
|
||||
|
||||
@@ -241,9 +241,29 @@ pub(super) struct Used {
|
||||
impl Used {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator<Item = &'a Node>) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo: Vec<Source<'a>> = nodes.into_iter().map(Source::Node).collect();
|
||||
used.follow(defs, nodes.into_iter().map(Source::Node).collect());
|
||||
used
|
||||
}
|
||||
|
||||
/// Every character style of `defs` (with `chars`) and every paragraph style (with `paras`), and
|
||||
/// the resources they use, styles of the other kind included.
|
||||
fn of_text_styles(defs: &Defs<'_>, chars: bool, paras: bool) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo = vec![];
|
||||
for s in defs.char_styles.iter().filter(|_| chars) {
|
||||
used.note(defs, Ref::Name(Res::CharStyle, &s.name), &mut todo);
|
||||
}
|
||||
for s in defs.para_styles.iter().filter(|_| paras) {
|
||||
used.note(defs, Ref::Name(Res::ParaStyle, &s.name), &mut todo);
|
||||
}
|
||||
used.follow(defs, todo);
|
||||
used
|
||||
}
|
||||
|
||||
/// Note the references of `todo`'s sources and of the definitions they lead to.
|
||||
fn follow<'a>(&mut self, defs: &Defs<'a>, mut todo: Vec<Source<'a>>) {
|
||||
while let Some(src) = todo.pop() {
|
||||
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
|
||||
let mut found = |r: Ref<'_>| self.note(defs, r, &mut todo);
|
||||
match src {
|
||||
Source::Node(n) => node_refs(n, &mut found),
|
||||
Source::Appearance(a) => appearance_refs(a, &mut found),
|
||||
@@ -251,7 +271,6 @@ impl Used {
|
||||
Source::Paint(p) => paint_refs(p, &mut found),
|
||||
}
|
||||
}
|
||||
used
|
||||
}
|
||||
|
||||
/// Note `r`; a definition seen for the first time joins `todo`.
|
||||
@@ -505,7 +524,7 @@ impl SwatchChoices {
|
||||
}
|
||||
|
||||
/// How pasted art is relinked to the document's resources.
|
||||
#[derive(Debug, Default)]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Relink {
|
||||
renames: BTreeMap<Res, BTreeMap<String, String>>,
|
||||
/// Graphic style id on the clipboard → its id in the document. Links to other ids are dropped.
|
||||
@@ -665,6 +684,227 @@ impl SymbolOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
|
||||
/// brush (placed with the others only when they are placed in use order) to place
|
||||
/// ([`Clipboard::import_used`]).
|
||||
#[derive(Clone, Copy)]
|
||||
enum Def<'c> {
|
||||
Style(Res, &'c TextStyleDef),
|
||||
Symbol(&'c Symbol, Option<&'c SymbolOptions>),
|
||||
Pattern(&'c PatternDef),
|
||||
Brush(&'c Brush),
|
||||
}
|
||||
|
||||
impl<'c> Def<'c> {
|
||||
fn key(&self) -> (Res, &'c str) {
|
||||
match self {
|
||||
Def::Style(r, s) => (*r, &s.name),
|
||||
Def::Symbol(s, _) => (Res::Symbol, &s.name),
|
||||
Def::Pattern(p) => (Res::Pattern, &p.name),
|
||||
Def::Brush(b) => (Res::Brush, &b.name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `f` with each resource it refers to by name.
|
||||
fn each_use(&self, f: &mut dyn FnMut(Res, &str)) {
|
||||
let mut g = |r: Ref<'_>| {
|
||||
if let Ref::Name(res, n) = r {
|
||||
f(res, n);
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Def::Style(_, s) => attrs_refs(&s.attrs, &mut g),
|
||||
Def::Symbol(s, _) => node_refs(&s.art, &mut g),
|
||||
Def::Pattern(p) => p.art.iter().for_each(|a| node_refs(a, &mut g)),
|
||||
Def::Brush(b) => b.art().into_iter().for_each(|a| node_refs(a, &mut g)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is it the definition `d` has under `name`, once relinked by `r`? (`brushes`: the brush
|
||||
/// library of `d`.)
|
||||
fn same_in(&self, d: &Document, brushes: &Brushes<'_>, name: &str, r: &Relink) -> bool {
|
||||
match self {
|
||||
Def::Style(res, s) => {
|
||||
let theirs = if *res == Res::CharStyle { &d.char_styles } else { &d.para_styles };
|
||||
let mut attrs = s.attrs.clone();
|
||||
r.attrs(&mut attrs);
|
||||
theirs.iter().any(|x| x.name == name && x.attrs == attrs)
|
||||
}
|
||||
Def::Symbol(s, options) => d.symbols.iter().any(|x| {
|
||||
x.name == name
|
||||
&& options.is_none_or(|o| SymbolOptions::of(d, name) == *o)
|
||||
&& same_art(r, std::slice::from_ref(&x.art), std::slice::from_ref(&s.art))
|
||||
}),
|
||||
Def::Pattern(p) => {
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
d.pattern(name).is_some_and(|x| bare(x) == bare(p) && same_art(r, &x.art, &p.art))
|
||||
}
|
||||
Def::Brush(b) => brushes.get().iter().any(|x| x.name == name && same_brush(r, x, b)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of its kind in `d` (`brushes`: its brush library) that are its name or a numbered
|
||||
/// copy of it.
|
||||
fn names_in(&self, d: &Document, brushes: &Brushes<'_>) -> Vec<String> {
|
||||
let (res, name) = self.key();
|
||||
let names: Vec<String> = match res {
|
||||
Res::CharStyle => d.char_styles.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::ParaStyle => d.para_styles.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(),
|
||||
Res::Brush => brushes.get().iter().map(|b| b.name.clone()).collect(),
|
||||
_ => d.patterns.iter().map(|p| p.name.clone()).collect(),
|
||||
};
|
||||
names.into_iter().filter(|n| copy_of(name, n)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// `defs` in rounds: each round takes those that use none of the others left, in their order.
|
||||
/// → (those, the rest, which use each other in a loop or use one that does, in their order)
|
||||
fn use_order(defs: Vec<Def<'_>>) -> (Vec<Def<'_>>, Vec<Def<'_>>) {
|
||||
let uses = uses_of(&defs);
|
||||
// The round of each definition; `None` for one in a loop or one that uses such a definition.
|
||||
let mut round: Vec<Option<usize>> = vec![None; defs.len()];
|
||||
// A group outside a loop holds one definition, and comes after the groups it uses.
|
||||
for (group, looped) in components(&uses) {
|
||||
for v in group.into_iter().filter(|_| !looped) {
|
||||
let r = uses[v].iter().try_fold(0, |r, &w| round.get(w).copied().flatten().map(|k| r.max(k + 1)));
|
||||
round[v] = r;
|
||||
}
|
||||
}
|
||||
let mut ready: Vec<(usize, usize)> = round.iter().enumerate().filter_map(|(i, r)| r.map(|r| (r, i))).collect();
|
||||
ready.sort_unstable();
|
||||
let order = ready.into_iter().filter_map(|(_, i)| defs.get(i).copied()).collect();
|
||||
let rest = defs.iter().zip(&round).filter(|(_, r)| r.is_none()).map(|(def, _)| *def).collect();
|
||||
(order, rest)
|
||||
}
|
||||
|
||||
/// The positions in `defs` of the definitions each one uses, itself included.
|
||||
fn uses_of(defs: &[Def<'_>]) -> Vec<Vec<usize>> {
|
||||
let mut at: BTreeMap<(Res, &str), Vec<usize>> = BTreeMap::new();
|
||||
for (i, def) in defs.iter().enumerate() {
|
||||
at.entry(def.key()).or_default().push(i);
|
||||
}
|
||||
defs.iter()
|
||||
.map(|def| {
|
||||
let mut to = vec![];
|
||||
def.each_use(&mut |res, n| to.extend(at.get(&(res, n)).into_iter().flatten()));
|
||||
to.sort_unstable();
|
||||
to.dedup();
|
||||
to
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `rest` ([`use_order`]'s definitions that use each other in a loop or use one that does) split
|
||||
/// into its loops and the definitions outside a loop, each group after the groups it uses:
|
||||
/// (positions in `rest`, in their order; true for a loop, definitions that use each other or one
|
||||
/// that uses itself).
|
||||
fn loop_groups(rest: &[Def<'_>]) -> Vec<(Vec<usize>, bool)> {
|
||||
components(&uses_of(rest))
|
||||
}
|
||||
|
||||
/// The strongly connected components of the graph `uses` (each node's successors), each after
|
||||
/// those it reaches: (nodes, in their order; true for a loop, two or more nodes or one that uses
|
||||
/// itself).
|
||||
fn components(uses: &[Vec<usize>]) -> Vec<(Vec<usize>, bool)> {
|
||||
// Tarjan's algorithm, with an explicit stack of calls.
|
||||
const NONE: usize = usize::MAX;
|
||||
let (mut index, mut low, mut on) = (vec![NONE; uses.len()], vec![0; uses.len()], vec![false; uses.len()]);
|
||||
let (mut stack, mut next, mut groups) = (vec![], 0, vec![]);
|
||||
for root in 0..uses.len() {
|
||||
if index[root] != NONE {
|
||||
continue;
|
||||
}
|
||||
let mut calls: Vec<(usize, usize)> = vec![(root, 0)];
|
||||
(index[root], low[root], on[root]) = (next, next, true);
|
||||
next += 1;
|
||||
stack.push(root);
|
||||
while let Some(&(v, k)) = calls.last() {
|
||||
if let Some(&w) = uses[v].get(k) {
|
||||
if let Some(top) = calls.last_mut() {
|
||||
top.1 += 1;
|
||||
}
|
||||
if index[w] == NONE {
|
||||
(index[w], low[w], on[w]) = (next, next, true);
|
||||
next += 1;
|
||||
stack.push(w);
|
||||
calls.push((w, 0));
|
||||
} else if on[w] {
|
||||
low[v] = low[v].min(index[w]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
calls.pop();
|
||||
if let Some(&(u, _)) = calls.last() {
|
||||
low[u] = low[u].min(low[v]);
|
||||
}
|
||||
if low[v] == index[v] {
|
||||
let mut group = vec![];
|
||||
while let Some(w) = stack.pop() {
|
||||
on[w] = false;
|
||||
group.push(w);
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
group.sort_unstable();
|
||||
let looped = group.len() > 1 || uses[v].contains(&v);
|
||||
groups.push((group, looped));
|
||||
}
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// The names in `d` that `looped` (a loop of definitions that use each other, [`loop_groups`])
|
||||
/// all have at once, each the same once relinked by `r` with those names: each one's name or a
|
||||
/// numbered copy of it. The names are picked one definition at a time, in order, and each
|
||||
/// definition is compared as soon as the names of those it uses are picked, so a pick that does
|
||||
/// not fit is dropped with every combination that follows from it; at most 65,536 comparisons are
|
||||
/// made. `None` when no combination fits, or none was found within that many comparisons. The brush
|
||||
/// library of `d` is read once, the first time a brush is compared.
|
||||
fn names_of_loop(d: &Document, looped: &[Def<'_>], r: &Relink) -> Option<Vec<String>> {
|
||||
let library = OnceCell::new();
|
||||
let brushes = Brushes::Lazy(d, &library);
|
||||
let names: Vec<Vec<String>> = looped.iter().map(|def| def.names_in(d, &brushes)).collect();
|
||||
if names.is_empty() || names.iter().any(Vec::is_empty) {
|
||||
return None;
|
||||
}
|
||||
// The definitions compared once the name at each position is picked.
|
||||
let mut compare_at: Vec<Vec<usize>> = vec![vec![]; looped.len()];
|
||||
for (i, uses) in uses_of(looped).iter().enumerate() {
|
||||
compare_at[uses.iter().copied().fold(i, usize::max)].push(i);
|
||||
}
|
||||
let (mut pick, mut guess, mut budget, mut k) = (vec![0usize; looped.len()], r.clone(), 1usize << 16, 0);
|
||||
loop {
|
||||
let (res, own) = looped[k].key();
|
||||
guess.renames.entry(res).or_default().insert(own.to_string(), names[k][pick[k]].clone());
|
||||
let fits = compare_at[k].iter().all(|&i| {
|
||||
budget = budget.saturating_sub(1);
|
||||
looped[i].same_in(d, &brushes, &names[i][pick[i]], &guess)
|
||||
});
|
||||
if fits && k + 1 == looped.len() {
|
||||
return Some(names.iter().zip(&pick).map(|(l, &p)| l[p].clone()).collect());
|
||||
}
|
||||
if budget == 0 {
|
||||
return None;
|
||||
}
|
||||
if fits {
|
||||
k += 1;
|
||||
pick[k] = 0;
|
||||
continue;
|
||||
}
|
||||
// The next name at this position, or back to the position before.
|
||||
loop {
|
||||
pick[k] += 1;
|
||||
if pick[k] < names[k].len() {
|
||||
break;
|
||||
}
|
||||
k = k.checked_sub(1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What pasting did to the document's resources (part of the paste result).
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Imported {
|
||||
@@ -704,6 +944,12 @@ impl Clipboard {
|
||||
pub(crate) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of(&Defs::of(src, &library), &nodes);
|
||||
Self::with_used(src, &used, &library, nodes)
|
||||
}
|
||||
|
||||
/// `nodes` and the resources of `src` that `used` names (`library`: the brush library of `src`,
|
||||
/// read when a brush was used).
|
||||
fn with_used(src: &Document, used: &Used, library: &OnceCell<Vec<Brush>>, nodes: Vec<Node>) -> Self {
|
||||
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
|
||||
// Read when a brush was used.
|
||||
let brushes = match (used.names.get(&Res::Brush), library.get()) {
|
||||
@@ -757,61 +1003,158 @@ impl Clipboard {
|
||||
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
|
||||
/// pasted copies relink to them.
|
||||
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Imported {
|
||||
let used = self.used();
|
||||
self.import_used(d, &self.used(), choices, same_doc, false)
|
||||
}
|
||||
|
||||
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
|
||||
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
|
||||
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
|
||||
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
|
||||
/// of definitions that use each other is matched on its own ([`loop_groups`]).
|
||||
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Imported {
|
||||
let mut out = Imported::default();
|
||||
self.import_images(d, &used, same_doc, &mut out);
|
||||
self.import_swatches(d, &used, choices, same_doc, &mut out);
|
||||
self.import_images(d, used, same_doc, &mut out);
|
||||
self.import_swatches(d, used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
// they may brush; the others once those are in.
|
||||
let mut added_brushes: HashSet<String> = self.import_brushes(d, &used, same_doc, false, &mut out).into_iter().collect();
|
||||
// Character and paragraph styles (their colours relinked first).
|
||||
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
|
||||
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
|
||||
let mut s = def.clone();
|
||||
// they may brush; the others once those are in. With `in_use_order`, the brushes are
|
||||
// placed in use order with the others.
|
||||
let mut added_brushes: HashSet<String> =
|
||||
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
|
||||
let mut defs: Vec<Def<'_>> = vec![];
|
||||
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
|
||||
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
|
||||
}
|
||||
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
|
||||
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
|
||||
if in_use_order {
|
||||
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
|
||||
}
|
||||
// Groups to place in order; true for a loop of definitions that use each other.
|
||||
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
|
||||
let (order, rest) = use_order(defs);
|
||||
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
|
||||
std::iter::once((order, false)).chain(loops).collect()
|
||||
} else {
|
||||
vec![(defs, false)]
|
||||
};
|
||||
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
|
||||
// symbols with their options too). The symbols and patterns added are relinked at the end,
|
||||
// when every new name and graphic style id is known; with `in_use_order`, so are the
|
||||
// styles added, which a loop of uses may place before a pattern they paint with.
|
||||
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
|
||||
// Each definition, whether it is in a loop, and the loop it starts.
|
||||
let steps = groups
|
||||
.iter()
|
||||
.flat_map(|(group, looped)| group.iter().enumerate().map(move |(i, def)| (*def, *looped, (*looped && i == 0).then_some(group))));
|
||||
// In a loop the document does not have all at once, every definition uses one that is
|
||||
// added under a free name, so each one is added too.
|
||||
let mut fresh = false;
|
||||
// The names in the document of the loop being placed, when it has them all at once.
|
||||
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
|
||||
// The document's brush library, read the first time a brush is placed in use order and
|
||||
// stored again after each brush added; nothing else in the loop changes it.
|
||||
let mut library: Option<Vec<Brush>> = None;
|
||||
for (def, looped, starts) in steps {
|
||||
fresh &= looped;
|
||||
if !looped {
|
||||
matched.clear();
|
||||
}
|
||||
// A loop of uses that the document has all at once is known under those names before
|
||||
// its definitions are compared.
|
||||
if let Some(group) = starts {
|
||||
matched.clear();
|
||||
match names_of_loop(d, group, &out.relink) {
|
||||
Some(names) => {
|
||||
for (def, name) in group.iter().zip(names) {
|
||||
let (res, own) = def.key();
|
||||
if own != name {
|
||||
out.relink.renames.entry(res).or_default().insert(own.to_string(), name.clone());
|
||||
}
|
||||
matched.insert((res, own.to_string()), name);
|
||||
}
|
||||
fresh = false;
|
||||
}
|
||||
None => fresh = true,
|
||||
}
|
||||
}
|
||||
// A definition of such a loop is the document's under the name found for it.
|
||||
let (res, own) = def.key();
|
||||
if let Some(name) = matched.get(&(res, own.to_string())) {
|
||||
let p = if name == own { Placed::Existing } else { Placed::Reused(name.clone()) };
|
||||
out.placed(res, own, &p);
|
||||
continue;
|
||||
}
|
||||
match def {
|
||||
Def::Style(r, def) => {
|
||||
let mut s = def.clone();
|
||||
out.relink.attrs(&mut s.attrs);
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
|
||||
if in_use_order && let Some(name) = p.new_name(&def.name) {
|
||||
added_styles.push((r, name, def));
|
||||
}
|
||||
out.placed(r, &def.name, &p);
|
||||
}
|
||||
Def::Symbol(def, options) => {
|
||||
let theirs: HashMap<String, SymbolOptions> = match options {
|
||||
Some(_) => d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|s| copy_of(&def.name, &s.name))
|
||||
.map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name)))
|
||||
.collect(),
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
!fresh
|
||||
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
|
||||
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
o.give(d, &name);
|
||||
}
|
||||
added_symbols.insert(name);
|
||||
}
|
||||
out.placed(Res::Symbol, &def.name, &p);
|
||||
}
|
||||
Def::Pattern(def) => {
|
||||
// Tile options alike, and the art once relinked.
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
|
||||
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
// Its swatch comes along under the same name.
|
||||
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
|
||||
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
|
||||
Placed::added(&def.name, name)
|
||||
});
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
Def::Brush(b) => {
|
||||
let lib = library.get_or_insert_with(|| vectorcraft_brush::library(d));
|
||||
let r = &out.relink;
|
||||
let p = place(lib, b, same_doc, |ours, theirs| !fresh && same_brush(r, ours, theirs));
|
||||
if let Some(name) = p.new_name(&b.name) {
|
||||
vectorcraft_brush::store(d, lib);
|
||||
added_brushes.insert(name);
|
||||
}
|
||||
out.placed(Res::Brush, &b.name, &p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !in_use_order {
|
||||
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
|
||||
}
|
||||
self.import_graphic_styles(d, used, same_doc, &mut out);
|
||||
for (r, name, def) in added_styles {
|
||||
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
|
||||
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
|
||||
s.attrs = def.attrs.clone();
|
||||
out.relink.attrs(&mut s.attrs);
|
||||
let p = place(theirs, &s, same_doc, PartialEq::eq);
|
||||
out.placed(r, &def.name, &p);
|
||||
}
|
||||
}
|
||||
// Symbols and patterns, compared once relinked (symbols with their options too). Those
|
||||
// added are relinked at the end, when every new name and graphic style id is known.
|
||||
let mut added_symbols = HashSet::new();
|
||||
for def in self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)) {
|
||||
let options = self.symbol_options.get(&def.name);
|
||||
let theirs: HashMap<String, SymbolOptions> = match options {
|
||||
Some(_) => {
|
||||
d.symbols.iter().filter(|s| copy_of(&def.name, &s.name)).map(|s| (s.name.clone(), SymbolOptions::of(d, &s.name))).collect()
|
||||
}
|
||||
None => HashMap::new(),
|
||||
};
|
||||
let r = &out.relink;
|
||||
let p = place(&mut d.symbols, def, same_doc, |a, b| {
|
||||
options.is_none_or(|o| theirs.get(&a.name) == Some(o)) && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|
||||
});
|
||||
if let Some(name) = p.new_name(&def.name) {
|
||||
if let Some(o) = options {
|
||||
o.give(d, &name);
|
||||
}
|
||||
added_symbols.insert(name);
|
||||
}
|
||||
out.placed(Res::Symbol, &def.name, &p);
|
||||
}
|
||||
let mut added_patterns = HashSet::new();
|
||||
for def in self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)) {
|
||||
// Tile options alike, and the art once relinked.
|
||||
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
|
||||
let same = |n: &str| d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
|
||||
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
|
||||
// Its swatch comes along under the same name.
|
||||
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
|
||||
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
|
||||
Placed::added(&def.name, name)
|
||||
});
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out));
|
||||
self.import_graphic_styles(d, &used, same_doc, &mut out);
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
}
|
||||
@@ -925,6 +1268,43 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a loaded text style is in the document ([`import_text_styles`]).
|
||||
pub(crate) struct LoadedStyle {
|
||||
/// A paragraph style (else a character style).
|
||||
pub para: bool,
|
||||
/// Its name in the document.
|
||||
pub name: String,
|
||||
/// It was added (else the document's own was the same).
|
||||
pub added: bool,
|
||||
}
|
||||
|
||||
/// Add every character style of `src` (with `chars`) and every paragraph style (with `paras`) to
|
||||
/// `d`, with the swatches, patterns and what their art uses (styles of the other kind included)
|
||||
/// that the styles' fill and stroke lead to, as Paste adds those of pasted type
|
||||
/// ([`Clipboard::import_into`]; a global or spot color whose name `d` gives another color is
|
||||
/// `d`'s). Each style, symbol and pattern is placed after those it uses, so that a style follows
|
||||
/// a pattern added under a free name and a pattern follows a style renamed on the way in. A style
|
||||
/// `d` has under its name, or a numbered copy of it ("Body 2"), that is the same once relinked is
|
||||
/// used; any other is added under a free name. → each style of `src` placed, in order, character
|
||||
/// styles first.
|
||||
pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, paras: bool) -> Vec<LoadedStyle> {
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true);
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
let name = out.relink.renamed(r, &s.name);
|
||||
let again = placed.iter().any(|p| p.para == para && p.name == name);
|
||||
let added = !again && !before[usize::from(para)].contains(&name);
|
||||
placed.push(LoadedStyle { para, name, added });
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
|
||||
/// share one namespace).
|
||||
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
|
||||
|
||||
@@ -19,7 +19,7 @@ use vectorcraft_render::proof;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::EngineError;
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, color_value, has_doc, str_param, targets};
|
||||
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
|
||||
|
||||
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
|
||||
/// to `Document::color_profiles` on load).
|
||||
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
proof_setup
|
||||
),
|
||||
cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| {
|
||||
toggle_view(s, p, |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
|
||||
toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors))
|
||||
}),
|
||||
cmd!(
|
||||
query "view.overprintPreview",
|
||||
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
Some("Cmd+Alt+Shift+Y"),
|
||||
"{on?: bool (default: toggle)} → proof state",
|
||||
always,
|
||||
|s, p| toggle_view(s, p, |v, on| v.overprint = on.unwrap_or(!v.overprint))
|
||||
|s, p| toggle_view(s, p, "view.overprintPreview", |v, on| v.overprint = on.unwrap_or(!v.overprint))
|
||||
),
|
||||
cmd!(
|
||||
query "view.separationsPreview",
|
||||
@@ -143,12 +143,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn intent_param(p: &Value, cmd: &str) -> Result<Option<Intent>> {
|
||||
match str_param(p, "intent") {
|
||||
match text_param(p, "intent", cmd)? {
|
||||
None => Ok(None),
|
||||
Some(i) => Intent::parse(i).map(Some).ok_or_else(|| bad(cmd, format!("unknown intent `{i}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The true or false `p` gives for `key`, or `None` when `p` leaves it out or gives null. Any other
|
||||
/// value is an error, as [`switch_or`] reads it.
|
||||
fn on_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
if p.get(key).is_none_or(Value::is_null) {
|
||||
return Ok(None);
|
||||
}
|
||||
switch_or(p, key, false, cmd).map(Some)
|
||||
}
|
||||
|
||||
fn settings_json(st: &ColorSettings) -> Value {
|
||||
json!({
|
||||
"rgb": st.rgb,
|
||||
@@ -171,16 +180,16 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colorSettings";
|
||||
let mut st = cms::active_settings();
|
||||
let before = st.clone();
|
||||
if let Some(v) = str_param(p, "rgb") {
|
||||
if let Some(v) = text_param(p, "rgb", C)? {
|
||||
st.rgb = cms::canonical_name(v).to_string();
|
||||
}
|
||||
if let Some(v) = str_param(p, "cmyk") {
|
||||
if let Some(v) = text_param(p, "cmyk", C)? {
|
||||
st.cmyk = cms::canonical_name(v).to_string();
|
||||
}
|
||||
if let Some(i) = intent_param(p, C)? {
|
||||
st.intent = i;
|
||||
}
|
||||
st.bpc = bool_or(p, "bpc", st.bpc);
|
||||
st.bpc = switch_or(p, "bpc", st.bpc, C)?;
|
||||
if st != before {
|
||||
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
|
||||
touch_all(s);
|
||||
@@ -191,7 +200,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.loadProfile";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let path = text_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)?;
|
||||
let bytes = crate::store::read_capped(std::path::Path::new(path), crate::store::MAX_PROFILE_FILE).map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
|
||||
@@ -209,7 +218,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Forget a profile `color.loadProfile` loaded, and the copy that is kept of it.
|
||||
fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.removeProfile";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?;
|
||||
let info = cms::profiles().into_iter().find(|i| i.name == name).ok_or_else(|| bad(C, format!("no profile named `{name}`")))?;
|
||||
if info.builtin {
|
||||
return Err(bad(C, format!("`{name}` is a built-in profile and stays")));
|
||||
@@ -289,7 +298,7 @@ pub enum Grays {
|
||||
impl Grays {
|
||||
/// The `grays` param of `cmd`: `"profile"` (default) or `"black"`.
|
||||
pub(crate) fn param(cmd: &str, p: &Value) -> Result<Self> {
|
||||
match str_param(p, "grays").map(str::to_ascii_lowercase).as_deref() {
|
||||
match text_param(p, "grays", cmd)?.map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("profile") => Ok(Grays::Profile),
|
||||
Some("black") => Ok(Grays::Black),
|
||||
Some(g) => Err(bad(cmd, format!("grays must be \"profile\" or \"black\", not `{g}`"))),
|
||||
@@ -302,18 +311,18 @@ impl Grays {
|
||||
/// colour through the colour settings.
|
||||
pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.documentColorMode";
|
||||
let mode = match str_param(p, "mode").map(str::to_ascii_lowercase).as_deref() {
|
||||
let mode = match p.get("mode").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("cmyk") => ColorMode::Cmyk,
|
||||
Some("rgb") => ColorMode::Rgb,
|
||||
_ => return Err(bad(C, "mode must be \"cmyk\" or \"rgb\"")),
|
||||
};
|
||||
let intent = intent_param(p, C)?;
|
||||
let grays = Grays::param(C, p)?;
|
||||
let convert = switch_or(p, "convert", true, C)?;
|
||||
// Choosing the mode the document already has (the checked menu item) is not an edit.
|
||||
if s.doc()?.doc.color_mode == mode {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
let convert = bool_or(p, "convert", true);
|
||||
let mut changed = 0usize;
|
||||
s.edit("Document Color Mode", |d, _| {
|
||||
changed = set_color_mode(d, mode, convert, intent, grays);
|
||||
@@ -654,7 +663,7 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = cms::active();
|
||||
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
|
||||
let lab = c.lab(&col);
|
||||
let (model, vals) = match str_param(p, "to").unwrap_or("rgb") {
|
||||
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
|
||||
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
|
||||
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
|
||||
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
|
||||
@@ -674,7 +683,11 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn gamut_check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut cols: Vec<Color> = vec![];
|
||||
if let Some(a) = p.get("colors").and_then(Value::as_array) {
|
||||
let colors = p.get("colors").filter(|v| !v.is_null());
|
||||
if let Some(v) = colors.filter(|v| !v.is_array()) {
|
||||
return Err(bad("color.gamutCheck", format!("`colors` must be an array of colors, not {v}")));
|
||||
}
|
||||
if let Some(a) = colors.and_then(Value::as_array) {
|
||||
for v in a {
|
||||
cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?);
|
||||
}
|
||||
@@ -728,7 +741,7 @@ fn view_json(v: &proof::ProofView) -> Value {
|
||||
fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup";
|
||||
let mut v = proof::view();
|
||||
if let Some(t) = str_param(p, "target") {
|
||||
if let Some(t) = text_param(p, "target", C)? {
|
||||
let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
|
||||
if let ProofTarget::Cmyk(name) = &t
|
||||
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
|
||||
@@ -740,8 +753,8 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(i) = intent_param(p, C)? {
|
||||
v.setup.intent = i;
|
||||
}
|
||||
v.setup.simulate_paper = bool_or(p, "simulatePaper", v.setup.simulate_paper);
|
||||
if let Some(on) = p.get("proof").and_then(Value::as_bool) {
|
||||
v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
|
||||
if let Some(on) = on_param(p, "proof", C)? {
|
||||
v.proof_colors = on;
|
||||
}
|
||||
proof::set_view(v.clone());
|
||||
@@ -749,9 +762,10 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(view_json(&v))
|
||||
}
|
||||
|
||||
fn toggle_view(s: &mut Session, p: &Value, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
|
||||
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
|
||||
let on = on_param(p, "on", cmd)?;
|
||||
let mut v = proof::view();
|
||||
f(&mut v, p.get("on").and_then(Value::as_bool));
|
||||
f(&mut v, on);
|
||||
proof::set_view(v.clone());
|
||||
touch_all(s);
|
||||
Ok(view_json(&v))
|
||||
@@ -779,16 +793,23 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|d| proof::plates(&d.doc).into_iter().map(|p| p.name).collect())
|
||||
.unwrap_or_else(|| cms::PROCESS_PLATES.iter().map(|s| s.to_string()).collect());
|
||||
let check = |n: &str| if all.iter().any(|a| a == n) { Ok(n.to_string()) } else { Err(bad(C, format!("unknown plate `{n}`"))) };
|
||||
if let Some(on) = p.get("on").and_then(Value::as_bool) {
|
||||
if let Some(on) = on_param(p, "on", C)? {
|
||||
v.separations = if on { Some(v.separations.take().unwrap_or_else(|| all.clone())) } else { None };
|
||||
}
|
||||
if let Some(a) = p.get("plates").and_then(Value::as_array) {
|
||||
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
|
||||
match p.get("plates") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
|
||||
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
|
||||
}
|
||||
Some(_) => {
|
||||
let key = "plates";
|
||||
return Err(bad(C, format!("`{key}` must be an array of these names: {}", all.join(", "))));
|
||||
}
|
||||
}
|
||||
if let Some(n) = str_param(p, "only") {
|
||||
if let Some(n) = text_param(p, "only", C)? {
|
||||
v.separations = Some(vec![check(n)?]);
|
||||
}
|
||||
if let Some(n) = str_param(p, "toggle") {
|
||||
if let Some(n) = text_param(p, "toggle", C)? {
|
||||
let n = check(n)?;
|
||||
let vis = v.separations.get_or_insert_with(|| all.clone());
|
||||
if let Some(i) = vis.iter().position(|x| *x == n) {
|
||||
@@ -804,8 +825,8 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.setSpot";
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
let spot = bool_or(p, "spot", true);
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.to_string();
|
||||
let spot = switch_or(p, "spot", true, C)?;
|
||||
let sw = s.doc()?.doc.swatch(&name).ok_or_else(|| bad(C, format!("no swatch `{name}`")))?;
|
||||
if !matches!(sw.paint, Paint::Solid { .. }) {
|
||||
return Err(bad(C, "only solid-colour swatches can be spot colours"));
|
||||
|
||||
@@ -13,7 +13,7 @@ use vectorcraft_tools::distort::liquify::{Dabber, LiquifyParams, PathStroke, Sam
|
||||
use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane};
|
||||
use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project_node, stroke_owner, warp_from_rest, warp_node_with};
|
||||
|
||||
use super::edit::{duplicate_in, outermost, selected_roots};
|
||||
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param,
|
||||
matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move in Perspective",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction; Transform Again repeats it",
|
||||
"{ids?|id?, from: [x,y], to: [x,y], plane?, copy?: bool (move copies, as Alt-dragging does), perpendicular?: bool (move along the plane's normal instead, as pressing 5 while dragging does), snap?: bool (default: View › Perspective Grid › Snap to Grid), constrain?: bool (default false; constrain each in-plane move to its plane's nearest axis or 45° diagonal)} slide objects within their own planes (unattached objects attach to `plane`/the active plane first); snapping pulls the nearer edge of the first plane's joint bounds toward a gridline within a quarter cell while preserving the constrained direction, and moves every object on that plane, at any depth, by the same plane offset; Transform Again repeats it",
|
||||
has_doc,
|
||||
persp_move
|
||||
),
|
||||
@@ -730,8 +730,13 @@ fn puppet_warp(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if pins.iter().chain(&moved).any(|q| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
return Err(bad(C, "pins must be finite"));
|
||||
}
|
||||
let ids =
|
||||
if rest { puppet_ids(p, || Ok(s.doc()?.selection.objects.clone()))? } else { outermost(&s.doc()?.doc, puppet_ids(p, || selected_roots(s))?) };
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused, as
|
||||
// `selected_roots` refuses it.
|
||||
let selected = || {
|
||||
refuse_symbol_part(s)?;
|
||||
Ok(s.doc()?.selection.objects.clone())
|
||||
};
|
||||
let ids = if rest { puppet_ids(p, selected)? } else { outermost(&s.doc()?.doc, puppet_ids(p, || selected_roots(s))?) };
|
||||
let expand = f64_or(p, "expand", 3.0).clamp(0.0, 1000.0);
|
||||
let angles: Vec<Option<f64>> = match p.get("angles") {
|
||||
None | Some(Value::Null) => vec![None; pins.len()],
|
||||
|
||||
@@ -285,7 +285,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let constrain = switch_or(p, "constrain", false, C)?;
|
||||
// `snap_fix` uses Snap to Grid's setting for a `snap` that is not true or false.
|
||||
check_switches(p, &["snap"], C)?;
|
||||
// Snap to Grid: a correction for the objects on the first one's plane and depth.
|
||||
// Shift: the constrained end point, read on the first object's plane and depth.
|
||||
let snap_to = if constrain && !perp {
|
||||
let doc = &s.doc()?.doc;
|
||||
let g = grid_of(doc);
|
||||
@@ -300,11 +300,20 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
to
|
||||
};
|
||||
let fix = if perp { None } else { crate::cmd::perspgrid::snap_fix(&s.doc()?.doc, &ids, p, (from, snap_to)) };
|
||||
let snapped = move |pl: Plane, depth: f64, raw: vectorcraft_geom::Vec2| {
|
||||
// With Snap to Grid, every object on the first one's plane, at any depth, moves by the first
|
||||
// one's plane-space offset and its correction, so the objects keep their spacing on the plane.
|
||||
let fix = if perp {
|
||||
None
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
crate::cmd::perspgrid::snap_fix(doc, &ids, p, (from, snap_to))
|
||||
.and_then(|(plane, depth, correction)| Some((plane, grid_of(doc).plane_delta(plane, depth, from, to)?, correction)))
|
||||
};
|
||||
let snapped = move |pl: Plane, raw: vectorcraft_geom::Vec2| {
|
||||
let raw = fix.filter(|f| f.0 == pl).map_or(raw, |f| f.1);
|
||||
let (direction, dv) =
|
||||
if constrain { vectorcraft_tools::distort::perspective::constrain_move_delta(raw) } else { (vectorcraft_geom::Vec2::ZERO, raw) };
|
||||
dv + fix.filter(|f| f.0 == pl && f.1 == depth).map_or(vectorcraft_geom::Vec2::ZERO, |f| {
|
||||
dv + fix.filter(|f| f.0 == pl).map_or(vectorcraft_geom::Vec2::ZERO, |f| {
|
||||
if !constrain {
|
||||
return f.2;
|
||||
}
|
||||
@@ -325,7 +334,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let to_depth = g.depth_at(pl, depth, from, to).ok_or_else(beyond_horizon)?;
|
||||
Ok((g.transform_map(pl, depth, Affine::IDENTITY, to_depth - depth).ok_or_else(beyond_horizon)?, to_depth))
|
||||
} else {
|
||||
let dv = snapped(pl, depth, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
let dv = snapped(pl, g.plane_delta(pl, depth, from, to).ok_or_else(beyond_horizon)?);
|
||||
Ok((g.transform_map(pl, depth, Affine::translate(dv), 0.0).ok_or_else(beyond_horizon)?, depth))
|
||||
}
|
||||
};
|
||||
@@ -336,7 +345,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if perp {
|
||||
g.depth_at(pl, depth, from, to).is_some_and(|d| (d - depth).abs() <= 1e-9)
|
||||
} else {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, depth, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| snapped(pl, dv)).is_some_and(|dv| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9)
|
||||
}
|
||||
};
|
||||
let first_still = if copy { None } else { unmoved(s, &ids, still)? };
|
||||
@@ -350,9 +359,7 @@ pub(super) fn persp_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let again = match perp {
|
||||
_ if first_still.is_some() => Some(json!({"matrix": matrix_json(Affine::IDENTITY), "copy": copy})),
|
||||
true => g.depth_at(pl, depth, from, to).map(|d| json!({"matrix": matrix_json(Affine::IDENTITY), "depth": d - depth, "copy": copy})),
|
||||
false => {
|
||||
g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, depth, dv))), "copy": copy}))
|
||||
}
|
||||
false => g.plane_delta(pl, depth, from, to).map(|dv| json!({"matrix": matrix_json(Affine::translate(snapped(pl, dv))), "copy": copy})),
|
||||
};
|
||||
if let Some(a) = again {
|
||||
record_again(s, a)?;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -130,13 +130,15 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects and the rows of its Repeat objects.
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a pattern.
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
repeats: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
category: Option<&str>,
|
||||
) -> Vec<Section> {
|
||||
let names = |k: &str| -> Vec<(String, String)> {
|
||||
@@ -180,7 +182,7 @@ fn sections(
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"spotColors" => names("spotColors"),
|
||||
"patterns" => names("patternNames"),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
@@ -252,12 +254,67 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result<String> {
|
||||
Ok(v["text"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
fn paint_kind(p: &Paint) -> Option<&'static str> {
|
||||
match p {
|
||||
Paint::Gradient(_) => Some("gradients"),
|
||||
Paint::Pattern { .. } => Some("patterns"),
|
||||
_ => None,
|
||||
/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a
|
||||
/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and
|
||||
/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the
|
||||
/// type object's own fills and strokes paint on its characters, so only those runs paint. The type
|
||||
/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
|
||||
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet<usize>)> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
|
||||
let own = n.appearance.items.iter().any(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint),
|
||||
});
|
||||
if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) {
|
||||
return None;
|
||||
}
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let resolved = d.inline_resolved(t);
|
||||
let lay = vectorcraft_text::layout(db, &resolved);
|
||||
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
|
||||
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
|
||||
Some((t, painted))
|
||||
}
|
||||
|
||||
/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke
|
||||
/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide
|
||||
/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint
|
||||
/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
|
||||
/// only where an effect gives them a shape.
|
||||
fn own_patterns<'a>(
|
||||
n: &'a Node,
|
||||
members: &HashSet<*const Node>,
|
||||
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet<usize>)>,
|
||||
) -> Vec<&'a str> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| members.contains(&std::ptr::from_ref(n))
|
||||
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
|
||||
{
|
||||
return vec![];
|
||||
}
|
||||
// The patterns an image's shaped fills and strokes paint (their effects can transform the
|
||||
// pattern, so they are matched by name).
|
||||
let shaped: Option<Vec<String>> = matches!(n.kind, NodeKind::Image(_)).then(|| {
|
||||
vectorcraft_render::effects::image_paint(n)
|
||||
.into_iter()
|
||||
.filter_map(|(_, _, item)| match item.paint() {
|
||||
Paint::Pattern { pattern, .. } => Some(pattern.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let mut out: Vec<&str> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
let Paint::Pattern { pattern, .. } = item.paint() else { continue };
|
||||
let paints = item.visible()
|
||||
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
|
||||
&& shaped.as_ref().is_none_or(|s| s.contains(pattern));
|
||||
if paints && !out.contains(&pattern.as_str()) {
|
||||
out.push(pattern);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -293,9 +350,19 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
|
||||
let mut repeats: Vec<Value> = vec![];
|
||||
let mut repeat_rows: Vec<(String, String)> = vec![];
|
||||
// `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order.
|
||||
let mut pattern_objects: Vec<Value> = vec![];
|
||||
let mut pattern_rows: Vec<(String, String)> = vec![];
|
||||
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
|
||||
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
|
||||
let mut seen: HashSet<*const Node> = HashSet::new();
|
||||
// The members of the document's compound paths: the compound path's own fills and strokes paint them.
|
||||
let mut members: HashSet<*const Node> = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
|
||||
}
|
||||
});
|
||||
for r in roots {
|
||||
r.walk(&mut |n| {
|
||||
if !seen.insert(std::ptr::from_ref(n)) {
|
||||
@@ -345,16 +412,18 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The paint kinds this object's fills and strokes use, each once.
|
||||
let mut kinds = BTreeSet::new();
|
||||
// The patterns this object's fills and strokes use, each once.
|
||||
let mut used_patterns: Vec<&str> = vec![];
|
||||
let painted_runs = painted_runs(d, n);
|
||||
for pattern in own_patterns(n, &members, painted_runs.as_ref()) {
|
||||
patterns.insert(pattern.to_string());
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
for item in &n.appearance.items {
|
||||
let paint = match item {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => &f.paint,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => &s.paint,
|
||||
};
|
||||
if let Some(k) = paint_kind(paint) {
|
||||
kinds.insert(k);
|
||||
}
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
let paint = item.paint();
|
||||
// Objects counts an object with a pattern when Pattern Objects lists it, below.
|
||||
if let Paint::Gradient(_) = paint {
|
||||
kinds.insert("gradients");
|
||||
}
|
||||
if let Paint::Solid { swatch: Some(name), .. } = paint
|
||||
&& d.swatch(name).is_some_and(|s| s.spot)
|
||||
@@ -362,6 +431,28 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spot.insert(name.clone());
|
||||
}
|
||||
}
|
||||
// The characters' own paints: an inline graphic draws no outline and does not take its
|
||||
// run's paint (a list marker set in its run does), and a stroke with no width paints
|
||||
// nothing.
|
||||
if let Some((t, painted)) = &painted_runs {
|
||||
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
|
||||
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
|
||||
for paint in std::iter::once(&run.style.fill).chain(stroke) {
|
||||
if let Paint::Pattern { pattern, .. } = paint {
|
||||
patterns.insert(pattern.clone());
|
||||
if !used_patterns.contains(&pattern.as_str()) {
|
||||
used_patterns.push(pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !used_patterns.is_empty() {
|
||||
let name = n.display_name();
|
||||
pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns }));
|
||||
pattern_rows.push((name, used_patterns.join(", ")));
|
||||
kinds.insert("patterns");
|
||||
}
|
||||
for k in kinds {
|
||||
*counts.entry(k).or_default() += 1;
|
||||
}
|
||||
@@ -412,10 +503,11 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"paragraphStyles": d.para_styles.len(),
|
||||
"patterns": d.patterns.len(),
|
||||
"patternNames": patterns,
|
||||
"patternObjects": pattern_objects,
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -634,6 +726,120 @@ mod tests {
|
||||
assert_eq!(i["sections"][0]["rows"][0], json!(["<Grid Repeat>", "Grid Repeat, 500 rows × 500 columns, 125000 instances"]));
|
||||
}
|
||||
|
||||
/// Document Info › Pattern Objects lists each object filled or stroked with a pattern once,
|
||||
/// with the patterns it uses, one in a group and a type object whose characters use a pattern
|
||||
/// included; a pattern no art uses adds no row, and Objects counts the listed objects. With
|
||||
/// Selection Only it lists the patterned objects in the selection, and the report writes the
|
||||
/// same rows.
|
||||
#[test]
|
||||
fn info_lists_the_pattern_objects() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let square =
|
||||
|s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let tile = square(&mut s, 0.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [tile], "name": "Dots", "edit": false})).unwrap();
|
||||
let spare = square(&mut s, 20.0);
|
||||
s.execute("object.pattern.make", &json!({"ids": [spare], "name": "Unused", "edit": false})).unwrap();
|
||||
let (a, b, c) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0));
|
||||
s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Dots"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [b], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
// A type object whose characters are filled with the pattern.
|
||||
let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
|
||||
// A hidden pattern fill and a pattern stroke with no width paint nothing, so neither object is listed.
|
||||
let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0));
|
||||
s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// A type object with no characters paints nothing either.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
|
||||
// Its own fill (a copy of its characters' pattern fill) paints on its characters, so it paints nothing.
|
||||
s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
|
||||
// Nor does type of only spaces and a line break, or a guide made from a patterned path.
|
||||
let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Dots"})).unwrap();
|
||||
let guide = square(&mut s, 300.0);
|
||||
s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
// Nor does a compound path's member's own pattern fill: the compound path's own fill paints it.
|
||||
let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
|
||||
let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
|
||||
let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
|
||||
// Nor does an image's pattern fill without an effect that gives it a shape.
|
||||
let pic = square(&mut s, 360.0);
|
||||
s.execute("select.set", &json!({"ids": [pic]})).unwrap();
|
||||
s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
|
||||
let image = s.doc().unwrap().selection.objects[0];
|
||||
s.edit("own paint", |d, _| {
|
||||
d.node_mut(member).unwrap().appearance = paint.clone();
|
||||
d.node_mut(image).unwrap().appearance = paint;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Underlined spaces draw a bar in the pattern, so that type object is listed.
|
||||
let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Dots"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [bar]})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"underline": true})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap();
|
||||
// A list marker set in an inline graphic's run draws in that run's pattern, so that type object is listed.
|
||||
s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let listed = s.execute("text.create", &json!({"x": 0, "y": 360, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("text.insertInline", &json!({"id": listed, "at": 0, "symbol": "Mark"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [listed], "list": "bullet"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [listed], "swatch": "Dots"})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": listed, "name": "Listed"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
i["patternObjects"],
|
||||
json!([
|
||||
{"id": a, "name": "Both", "patterns": ["Dots"]},
|
||||
{"id": b, "name": "<Rectangle>", "patterns": ["Dots"]},
|
||||
{"id": t, "name": "Type", "patterns": ["Dots"]},
|
||||
{"id": bar, "name": "Bar", "patterns": ["Dots"]},
|
||||
{"id": listed, "name": "Listed", "patterns": ["Dots"]},
|
||||
])
|
||||
);
|
||||
assert_eq!(i["patternNames"], json!(["Dots"]));
|
||||
// Objects counts the objects that Pattern Objects lists.
|
||||
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
|
||||
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
|
||||
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("patterns"), Some("Pattern Objects")));
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([["Both", "Dots"], ["<Rectangle>", "Dots"], ["Type", "Dots"], ["Bar", "Dots"], ["Listed", "Dots"]])
|
||||
);
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "patterns"})).unwrap();
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["<Rectangle>", "Dots"]]));
|
||||
s.execute("select.set", &json!({"ids": [t]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "patterns"})).unwrap();
|
||||
assert_eq!((i["sections"][0]["rows"].clone(), i["patternNames"].clone()), (json!([["Type", "Dots"]]), json!(["Dots"])));
|
||||
let text = s.execute("document.info", &json!({"category": "patterns", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nPATTERN OBJECTS\nBoth: Dots\n<Rectangle>: Dots\nType: Dots\nBar: Dots\nListed: Dots\n"), "{text}");
|
||||
assert!(!text.contains("Unused"), "{text}");
|
||||
}
|
||||
|
||||
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
|
||||
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
|
||||
/// it counts that object once.
|
||||
|
||||
@@ -14,7 +14,7 @@ pub(super) fn curvature(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "need at least one point"));
|
||||
}
|
||||
let sp = vectorcraft_tools::draw2::curvature_spline(&pts, switch_or(p, "closed", false, C)?);
|
||||
if let Some(id) = id_param(p, "id") {
|
||||
if let Some(id) = crate::cmd::object_param(p, "id", C)? {
|
||||
s.edit("Curvature", |d, sel| {
|
||||
*path_mut(d, id)? = PathData::single(sp);
|
||||
sel.set([id]);
|
||||
|
||||
+270
-10
@@ -9,9 +9,9 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req,
|
||||
finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok,
|
||||
point_param, str_param, switch_or,
|
||||
CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_or, f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param,
|
||||
index, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -41,6 +41,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
cmd!(
|
||||
query "document.compare",
|
||||
"Compare with Image",
|
||||
[],
|
||||
None,
|
||||
"{path: an image file (PNG, JPEG, WebP, TIFF or BMP), artboard?: index=0, background?: \"#rrggbb\"=\"#ffffff\" (the render and the image are both flattened on it), threshold?: 0.08 (0–1), diffPath?: a PNG to write (each pixel's absolute R, G and B differences)} render the artboard at the image's size (the image's width in pixels over the artboard's width in points), drawn as document.export draws a PNG (linked images and placed documents from their files), and compare it with the image; an image whose height differs by more than a pixel from the artboard's height at that scale is refused (not in the browser) → {width, height, rmse: the root mean square of the R, G and B differences, 0–1 (6 decimals), over: the pixels with a channel that differs by more than threshold, total: the pixels, threshold, diffPath?, warnings?: as a PNG export's (type that doesn't fit its frame, an image that couldn't be decoded, type in a font or style that isn't available, previews drawn because a linked file can't be read)}",
|
||||
has_doc,
|
||||
doc_compare
|
||||
),
|
||||
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
|
||||
cmd!(
|
||||
"document.setUnits",
|
||||
@@ -116,6 +125,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
can_clear_history,
|
||||
clear_history
|
||||
),
|
||||
cmd!(
|
||||
"edit.newDocumentFromState",
|
||||
"New Document from State",
|
||||
[],
|
||||
None,
|
||||
"{index?: a row of the History panel (0: the oldest state kept; default: the current state), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches)} make a new document holding the art as it was at that state, and make it the active document (the History panel's New Document from State button). The new document is named with the next Untitled-N, has nothing selected and no steps to undo or redo, is marked unsaved and links to the same files. It is out of symbol, opacity-mask and pattern editing, with the art drawn in a pattern's tile stored in the pattern as object.pattern.done stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step, as edit.undo keeps it; `index` names the row as it was listed before that. An index that names no state is an error and changes nothing → {index: the new document's, title}",
|
||||
has_doc,
|
||||
new_document_from_state
|
||||
),
|
||||
cmd!(
|
||||
"edit.undoGroup.begin",
|
||||
"Begin Undo Group",
|
||||
@@ -139,7 +157,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut",
|
||||
["Edit"],
|
||||
Some("Cmd+X"),
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)",
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (selected ruler guides go too; the Artboard tool chosen: artboard.cut); refused while an object of a symbol instance's art is selected",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
cut
|
||||
),
|
||||
@@ -148,7 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy",
|
||||
["Edit"],
|
||||
Some("Cmd+C"),
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}",
|
||||
"{lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
|
||||
has_selection_guides_or_artboard_tool,
|
||||
copy
|
||||
),
|
||||
@@ -202,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -376,6 +394,155 @@ fn select_found(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Render an artboard at an image's size, drawn as a PNG export draws it (linked images and placed
|
||||
/// documents from their files, with the export's warnings), and measure how far the
|
||||
/// two are apart: both flattened on `background`, the root mean square of the R, G and B
|
||||
/// differences (0–1), and the pixels with a channel that differs by more than `threshold`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn doc_compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_render::encode::{RasterExportOptions, RasterFormat, png};
|
||||
const C: &str = "document.compare";
|
||||
let path = str_param(p, "path").ok_or_else(|| bad(C, "missing `path`"))?;
|
||||
let diff_path = match p.get("diffPath") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(v)) => Some(v.as_str()),
|
||||
Some(_) => {
|
||||
let key = "diffPath";
|
||||
return Err(bad(C, format!("`{key}` must be a string")));
|
||||
}
|
||||
};
|
||||
let background = match p.get("background") {
|
||||
None | Some(Value::Null) => [255; 3],
|
||||
Some(v) => match super::fileio::background(v) {
|
||||
Ok(Some(rgb)) => rgb,
|
||||
_ => return Err(bad(C, format!("background {v}: a color such as \"#808080\""))),
|
||||
},
|
||||
};
|
||||
let threshold = match p.get("threshold") {
|
||||
None | Some(Value::Null) => 0.08,
|
||||
Some(v) => v.as_f64().filter(|t| (0.0..=1.0).contains(t)).ok_or_else(|| bad(C, "`threshold` must be a number from 0 to 1"))?,
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let count = doc.artboards.len();
|
||||
let i = opt_u64(p, C, "artboard")?.unwrap_or(0);
|
||||
let region = usize::try_from(i)
|
||||
.ok()
|
||||
.and_then(|i| doc.artboards.get(i))
|
||||
.map(|a| a.rect)
|
||||
.ok_or_else(|| bad(C, format!("no artboard {i} (0-based; the document has {count})")))?;
|
||||
if let Some(d) = diff_path {
|
||||
crate::file_access::check_write(d).map_err(EngineError::Other)?;
|
||||
}
|
||||
let image = compare_image(path)?;
|
||||
let (iw, ih) = image.dimensions();
|
||||
// The image's width sets the scale; its height may differ from the artboard's at that scale by
|
||||
// the pixel the rounding of a render takes.
|
||||
let scale = f64::from(iw) / region.width();
|
||||
let rendered_height = region.height() * scale;
|
||||
if iw == 0 || ih == 0 || !rendered_height.is_finite() || (rendered_height - f64::from(ih)).abs() > 1.0 {
|
||||
let (rw, rh) = (iw, rendered_height.round());
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ"),
|
||||
));
|
||||
}
|
||||
vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?;
|
||||
vectorcraft_render::raster_size(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(iw), f64::from(ih)), 1.0).map_err(|e| bad(C, e))?;
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
let opts = RasterExportOptions { background: Some(background), ..Default::default() }.render_options(RasterFormat::Png);
|
||||
// As a PNG export: linked images and placed documents drawn from their files, not the
|
||||
// previews saved for them.
|
||||
let (full, linked) = super::place::document::full_documents(doc);
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let rendered = vectorcraft_render::Renderer::new().render(&full, iw, ih, view, &opts);
|
||||
// A canceled render stops drawing: the picture is not whole.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
// As a PNG export says, in its order: type on the artboard that doesn't fit its frame, an image
|
||||
// the renderer couldn't decode (missing from the render), type in a missing font or style (drawn
|
||||
// in another one), and linked files drawn from their previews.
|
||||
let mut warnings: Vec<String> = super::fonts::export_overflow_warning(&full, &full.layers, Some(&[region])).into_iter().collect();
|
||||
if let Some(w) = super::rasterfx::undecoded_warning(failed) {
|
||||
warnings.push(w.into());
|
||||
}
|
||||
if let Some(w) = super::fonts::substitution_warning(&full) {
|
||||
warnings.push(w);
|
||||
}
|
||||
warnings.extend(linked);
|
||||
let rendered = rendered.to_straight();
|
||||
let flat = |px: &[u8; 4]| {
|
||||
let a = u32::from(px[3]);
|
||||
[0, 1, 2].map(|k| ((u32::from(px[k]) * a + u32::from(background[k]) * (255 - a) + 127) / 255) as u8)
|
||||
};
|
||||
let row = iw as usize * 4;
|
||||
let limit = threshold * 255.0;
|
||||
let (mut squares, mut over) = (0.0f64, 0u64);
|
||||
let mut diff = diff_path.map(|_| Vec::with_capacity(row * ih as usize));
|
||||
for (a, b) in rendered.chunks_exact(row).zip(image.as_raw().chunks_exact(row)) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) {
|
||||
let (fa, fb) = (flat(pa), flat(pb));
|
||||
let d = [0, 1, 2].map(|k| fa[k].abs_diff(fb[k]));
|
||||
squares += d.iter().map(|&x| f64::from(x) * f64::from(x)).sum::<f64>();
|
||||
if d.iter().any(|&x| f64::from(x) > limit) {
|
||||
over += 1;
|
||||
}
|
||||
if let Some(out) = &mut diff {
|
||||
out.extend_from_slice(&[d[0], d[1], d[2], 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let total = u64::from(iw) * u64::from(ih);
|
||||
let rmse = (squares / (total as f64 * 3.0)).sqrt() / 255.0;
|
||||
let mut out = json!({
|
||||
"width": iw,
|
||||
"height": ih,
|
||||
"rmse": (rmse * 1e6).round() / 1e6,
|
||||
"over": over,
|
||||
"total": total,
|
||||
"threshold": threshold,
|
||||
});
|
||||
if let (Some(d), Some(pixels)) = (diff_path, diff) {
|
||||
let bytes = png::encode(&pixels, iw, ih, &png::PngOptions { ppi: None, interlaced: false }).map_err(EngineError::Other)?;
|
||||
super::fileio::write_file(d, &bytes)?;
|
||||
out["diffPath"] = json!(d);
|
||||
}
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The image `document.compare` reads from `path` (through the automation read root), as straight
|
||||
/// RGBA: a PNG, JPEG, WebP, TIFF or BMP within the allocation an opened image may take.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_image(path: &str) -> Result<image::RgbaImage> {
|
||||
use image::ImageDecoder as _;
|
||||
const C: &str = "document.compare";
|
||||
let bytes = super::fileio::read_file(path)?;
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(&bytes) {
|
||||
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let readable = [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::WebP, image::ImageFormat::Tiff, image::ImageFormat::Bmp];
|
||||
if !reader.format().is_some_and(|f| readable.contains(&f)) {
|
||||
return Err(bad(C, format!("{path}: not a PNG, JPEG, WebP, TIFF or BMP image")));
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let decoder = reader.into_decoder().map_err(|e| bad(C, format!("{path}: {e}")))?;
|
||||
let (w, h) = decoder.dimensions();
|
||||
if decoder.total_bytes() > vectorcraft_doc::MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > vectorcraft_doc::MAX_RASTER_ALLOC {
|
||||
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(image::DynamicImage::from_decoder(decoder).map_err(|e| bad(C, format!("{path}: {e}")))?.to_rgba8())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn doc_compare(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("document.compare", "comparing with an image file isn't available in the browser"))
|
||||
}
|
||||
|
||||
/// Document Setup's units (also `document.setup {units}`).
|
||||
fn set_units(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let u = str_param(p, "units").and_then(Unit::named).ok_or_else(|| bad("document.setUnits", "unknown units"))?;
|
||||
@@ -606,6 +773,53 @@ fn clear_history(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "cleared": cleared }))
|
||||
}
|
||||
|
||||
/// History panel › New Document from State: a new document with the art of a state, and without
|
||||
/// the editing state that state may hold (opacity-mask or symbol editing, Puppet Warp pins, new art).
|
||||
/// Its links point at the files the source finds, which may be in the source's folder away from
|
||||
/// the links' paths. Later artboards in the two documents take their ids separately. A later save of the new document
|
||||
/// over the file its art was read from asks first, as a save of the source does.
|
||||
fn new_document_from_state(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.newDocumentFromState";
|
||||
let created = date_param(p, "created", C)?;
|
||||
let st = s.doc()?;
|
||||
// The row as the panel lists it now: keeping an edit in progress below changes the rows.
|
||||
let chosen = match p.get("index") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let state = v.as_u64().and_then(|row| st.history.state(&st.doc, index(row)));
|
||||
Some(state.ok_or_else(|| bad(C, format!("no history state {v}")))?.clone())
|
||||
}
|
||||
};
|
||||
settle_interaction(s)?;
|
||||
let st = s.doc()?;
|
||||
let mut doc = Document::clone(chosen.as_ref().unwrap_or(&st.doc));
|
||||
let (imported_from, import_losses, opened_by) = (st.imported_from.clone(), st.import_losses.clone(), st.opened_by.clone());
|
||||
if let Some(path) = st.path.as_deref() {
|
||||
// Files are looked for within the asking caller's roots, else within those of the caller that opened the source.
|
||||
let roots = crate::file_access::current().or_else(|| opened_by.clone());
|
||||
crate::file_access::confine(roots.as_ref(), || super::links::with_found_paths(&mut doc, path));
|
||||
}
|
||||
doc.drop_edit_modes();
|
||||
if doc.pattern_edit.is_some() {
|
||||
super::patterncmds::finish_edit(&mut doc, &mut vectorcraft_doc::Selection::default())?;
|
||||
}
|
||||
doc.puppet = None;
|
||||
doc.new_art.set(Arc::default());
|
||||
let retired = vectorcraft_doc::RetiredArtboardId::default();
|
||||
retired.raise(doc.retired_artboard_id.get());
|
||||
doc.retired_artboard_id = retired;
|
||||
doc.title = s.next_untitled();
|
||||
doc.metadata.created = clock_date(s, "created", created);
|
||||
doc.metadata.modified = None;
|
||||
let i = s.add_document(doc, None);
|
||||
let st = s.doc_mut()?;
|
||||
st.imported_from = imported_from;
|
||||
st.import_losses = import_losses;
|
||||
st.opened_by = st.opened_by.take().or(opened_by);
|
||||
st.mark_unsaved();
|
||||
Ok(json!({ "index": i, "title": st.title() }))
|
||||
}
|
||||
|
||||
/// `selection` for an undo (redo) step, sharing that of `like`, the step beside it, when the same.
|
||||
fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::HistoryEntry>) -> Arc<vectorcraft_doc::Selection> {
|
||||
match like {
|
||||
@@ -615,16 +829,38 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::
|
||||
}
|
||||
|
||||
/// Selected top-level objects in paint order, dropping any whose ancestor is also selected.
|
||||
///
|
||||
/// Refused with [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art
|
||||
/// is selected ([`super::brushsym::selected_part`]): only the paint commands change that object,
|
||||
/// and only its solid fill and stroke, so a command that gathers the selection here leaves the
|
||||
/// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]).
|
||||
pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc)))
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
/// for the commands that read the selected objects without [`selected_roots`]. A command that
|
||||
/// changes nothing in the document ([`Session::reading`]) reads the instance instead.
|
||||
pub(crate) fn refuse_symbol_part(s: &Session) -> Result<()> {
|
||||
if !s.reading && s.doc()?.selection.symbol_part.is_some() { Err(super::brushsym::part_only()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// [`refuse_symbol_part`] as a command's `enabled` check: the command is dimmed, and refused with
|
||||
/// [`super::brushsym::part_only`]'s message, while an object of a dynamic symbol instance's art is
|
||||
/// selected.
|
||||
pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
|
||||
if !s.reading && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { Err(super::brushsym::part_only().to_string()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// [`selected_roots`] for the commands that move or reshape the art (Move, Transform, Rotate…): a
|
||||
/// path of a compound path selected on its own (Group Selection, or in the isolated compound path)
|
||||
/// is an object of its own, so the hole of a ring moves without the ring (#2441). Paint and the
|
||||
/// rest still go to the compound path, which holds the paint.
|
||||
/// rest still go to the compound path, which holds the paint. Refused while an object of a symbol
|
||||
/// instance's art is selected, as [`selected_roots`] is: it moves with its instance only.
|
||||
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
|
||||
}
|
||||
@@ -633,8 +869,10 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
|
||||
/// ([`super::inside_isolation`]): `root` itself and objects outside it are left out before the
|
||||
/// objects held by another selected object are dropped. A selected path of a compound path stands
|
||||
/// for its compound unless the compound is `root` or `members` is set (as in
|
||||
/// [`selected_roots_to_transform`]).
|
||||
/// [`selected_roots_to_transform`]). Refused while an object of a symbol instance's art is
|
||||
/// selected, as [`selected_roots`] is.
|
||||
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
|
||||
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
|
||||
@@ -711,6 +949,7 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), false);
|
||||
}
|
||||
// With an object of a dynamic symbol instance's art selected, the instance is copied.
|
||||
let (direct, targets) = copy_cut_targets(s)?;
|
||||
let st = s.doc()?;
|
||||
// Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay
|
||||
@@ -751,6 +990,7 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.tool_id() == "artboard" {
|
||||
return super::panelcmds::artboard_copy(s, &artboard_clipboard_params(p), true);
|
||||
}
|
||||
refuse_symbol_part(s)?;
|
||||
// Ruler guides selected on their own: Copy takes them, Clear removes them.
|
||||
if s.doc()?.selection.is_empty() {
|
||||
copy(s, p)?;
|
||||
@@ -824,6 +1064,10 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
|
||||
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
|
||||
return super::path::delete_anchors(s, p);
|
||||
@@ -1055,10 +1299,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
imported.apply(&mut c);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
// including the pattern phase, independently of transform-tool settings.
|
||||
c.transform(xf, vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() });
|
||||
c.transform(xf, sc);
|
||||
}
|
||||
let layer = match clip.source_layers.get(k) {
|
||||
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
|
||||
@@ -1094,6 +1339,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
if let NodeKind::Path { live, .. } = &mut child_node.kind {
|
||||
*live = None;
|
||||
}
|
||||
if child_node.extras().pixel_aligned {
|
||||
child_node.extras_mut().pixel_aligned = false;
|
||||
}
|
||||
let insert_idx = if idx == usize::MAX { usize::MAX } else { idx.saturating_add(offset) };
|
||||
new_ids.push(d.insert(par, insert_idx, child_node)?);
|
||||
}
|
||||
@@ -1106,6 +1354,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
if let NodeKind::Path { live, .. } = &mut c.kind {
|
||||
*live = None;
|
||||
}
|
||||
// A path inside a compound path snaps with the compound path, whose property it takes.
|
||||
if c.extras().pixel_aligned {
|
||||
c.extras_mut().pixel_aligned = false;
|
||||
}
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
_ => {
|
||||
@@ -1114,14 +1366,19 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let offset = *placed.entry(outer_par).or_default();
|
||||
*placed.entry(outer_par).or_default() += 1;
|
||||
let insert_idx = if beside_idx == usize::MAX { usize::MAX } else { beside_idx.saturating_add(offset) };
|
||||
super::object::keep_pixel_aligned(&mut c, sc);
|
||||
new_ids.push(d.insert(outer_par, insert_idx, c)?);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
super::object::keep_pixel_aligned(&mut c, sc);
|
||||
new_ids.push(d.insert(par, idx, c)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in &new_ids {
|
||||
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
|
||||
// paste of guides alone keeps them where they were, but onto another artboard or every
|
||||
@@ -1193,7 +1450,10 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Duplicate `roots` directly above each original, transform the copies, select them
|
||||
/// ([`copy_above`]).
|
||||
pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result<Vec<NodeId>> {
|
||||
let out = copy_above(d, roots, |_, _, c| c.transform(xf, true))?;
|
||||
let out = copy_above(d, roots, |_, _, c| {
|
||||
c.transform(xf, true);
|
||||
super::object::keep_pixel_aligned(c, true.into());
|
||||
})?;
|
||||
sel.set(out.iter().copied());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -18,6 +18,22 @@ use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
|
||||
|
||||
/// The name of the `svg.filter` effect drawing `xml`: its `<filter>` id. An effect names the
|
||||
/// document's filter of that name, so `xml` that differs from the document's filter of the same
|
||||
/// name is refused.
|
||||
fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> {
|
||||
let name = effects::svg_filter::check(xml).map_err(|e| bad(cmd, e))?;
|
||||
if let Some(held) = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name)
|
||||
&& held.xml != xml.trim()
|
||||
{
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("the document has another SVG filter named {name:?}: use svgFilter.apply, or svgFilter.define with `replace` to edit it"),
|
||||
));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// The effect commands of the Effect menu and the Appearance panel.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -35,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Effects",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: object ids (default: the selection), target?: \"object\"|\"contents\"} → {catalog: [{id, label, menu, params, defaults, raster, lengths: {always, absolute (while relative is false)} (distance params Scale Strokes & Effects scales)}] (installed effect plug-ins last: id plugin.<plug-in id>, menu Effect › Plug-ins), applied: [{id, effects, items: [{index, kind: fill|stroke, effects}]}], activeItem} for the selection",
|
||||
"{ids?|id?: object ids (default: the selection), target?: \"object\"|\"contents\"} → {catalog: [{id, label, menu, params, defaults, raster, lengths: {always, absolute (while relative is false)} (distance params Scale Strokes & Effects scales)}] (installed effect plug-ins last: id plugin.<plug-in id>, menu Effect › Plug-ins), applied: [{id, effects, items: [{index, kind: fill|stroke, effects}]}] (an effect has skipped: true while Safe Mode skips it: a plug-in effect, which the object keeps and draws without), activeItem} for the selection",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -53,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Effect Options",
|
||||
[],
|
||||
None,
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], 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)} → {ids}",
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], 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)} → {ids}",
|
||||
has_doc,
|
||||
set_params
|
||||
),
|
||||
@@ -71,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes, or one selected with the art it measures when that art is replaced, becomes a plain group of its art. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -222,6 +238,16 @@ pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existin
|
||||
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.apply";
|
||||
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
// An effect given as `id` names no objects: the targets are read with that `id` as null.
|
||||
let effect_as_id;
|
||||
let p = if str_param(p, "effect").is_none() {
|
||||
let mut q = p.clone();
|
||||
q["id"] = Value::Null;
|
||||
effect_as_id = q;
|
||||
&effect_as_id
|
||||
} else {
|
||||
p
|
||||
};
|
||||
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
if !params.is_null() && !params.is_object() {
|
||||
return Err(bad(C, "`params` must be an object"));
|
||||
@@ -235,6 +261,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if texture_load_effect(id) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
// An SVG filter needs its <filter> element, and is named by its id.
|
||||
if id == effects::SVG_FILTER {
|
||||
let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG <filter> element"))?;
|
||||
params["name"] = json!(svg_filter_name(s, xml, C)?);
|
||||
}
|
||||
let effect = effects::new_effect(id, ¶ms).ok_or_else(|| bad(C, format!("unknown effect `{id}`")))?;
|
||||
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
|
||||
aligned(p, C)?;
|
||||
@@ -297,7 +328,22 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect();
|
||||
let mut applied = vec![];
|
||||
if s.active().is_some() {
|
||||
let fx = |e: &[Effect]| serde_json::to_value(e).unwrap_or(Value::Null);
|
||||
// A plug-in effect Safe Mode skips says so (`skipped`): the object keeps it.
|
||||
let fx = |e: &[Effect]| {
|
||||
Value::Array(
|
||||
e.iter()
|
||||
.map(|e| {
|
||||
let mut v = serde_json::to_value(e).unwrap_or(Value::Null);
|
||||
if vectorcraft_plugins::effect::skipped(&e.id)
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.insert("skipped".into(), json!(true));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
for id in appearance_targets(s, p)? {
|
||||
if let Some(n) = s.doc()?.doc.node(id) {
|
||||
let items: Vec<Value> = n
|
||||
@@ -422,10 +468,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec<String> {
|
||||
return vec![];
|
||||
};
|
||||
let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] };
|
||||
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| Some(st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id.clone());
|
||||
// A 3D effect whose type `threeDType` changes takes the new effect's parameters.
|
||||
let kind = three_d_type(p, C).ok().flatten();
|
||||
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| {
|
||||
let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id;
|
||||
Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string))
|
||||
};
|
||||
targets.iter().filter_map(effect).collect()
|
||||
}
|
||||
|
||||
/// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given.
|
||||
fn three_d_type(p: &Value, cmd: &str) -> Result<Option<&'static str>> {
|
||||
let key = "threeDType";
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
match v.as_str().and_then(|t| effects::THREE_D_TYPES.iter().find(|(name, _)| *name == t)) {
|
||||
Some((_, id)) => Ok(Some(id)),
|
||||
None => {
|
||||
let names: Vec<&str> = effects::THREE_D_TYPES.iter().map(|(name, _)| *name).collect();
|
||||
Err(bad(cmd, format!("`{key}` must be one of {}", names.join(", "))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.lightingPreset";
|
||||
let patch = str_param(p, "preset")
|
||||
@@ -450,8 +514,9 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// `effect.setParams`: merges `params` into the effect at `index` of the targets' active item, and
|
||||
/// sets its Warp style (`warpStyle`) or visibility (`visible`), as one undo step. They are checked
|
||||
/// as `effect.apply` checks them, and a visible 3D effect must still fit. → `{ids}`.
|
||||
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
|
||||
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
|
||||
/// fit. → `{ids}`.
|
||||
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.setParams";
|
||||
let index = index_param(p, "index", C)?;
|
||||
@@ -459,6 +524,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !params.is_null() && !params.is_object() {
|
||||
return Err(bad(C, "`params` must be an object"));
|
||||
}
|
||||
let kind = three_d_type(p, C)?;
|
||||
let warp_id = p
|
||||
.get("warpStyle")
|
||||
.map(|v| -> Result<String> {
|
||||
@@ -476,21 +542,47 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
}
|
||||
for (id, target, index) in effect_targets(s, p, item, index, C)? {
|
||||
let targets = effect_targets(s, p, item, index, C)?;
|
||||
// The type each 3D effect already has, with nothing else to change, is no edit (and is not
|
||||
// checked again).
|
||||
let nothing_else = params.as_object().is_none_or(serde_json::Map::is_empty) && visible.is_none() && warp_id.is_none();
|
||||
if let Some(to) = kind
|
||||
&& nothing_else
|
||||
{
|
||||
let d = &s.doc()?.doc;
|
||||
// The effects edited: a target without an effect at `index` is left as it is.
|
||||
let ids: Vec<&str> =
|
||||
targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index).map(|e| e.id.as_str())).collect();
|
||||
if !ids.is_empty() && ids.iter().all(|id| *id == to) {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
}
|
||||
// An SVG filter is named by its id: another filter renames the effect.
|
||||
if edited.iter().any(|e| e == effects::SVG_FILTER)
|
||||
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
|
||||
{
|
||||
params["name"] = json!(svg_filter_name(s, xml, C)?);
|
||||
}
|
||||
for &(id, target, index) in &targets {
|
||||
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index));
|
||||
if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) {
|
||||
return Err(bad(C, "warpStyle can only edit an applied Warp effect"));
|
||||
}
|
||||
if kind.is_some() && effect.is_some_and(|e| !effects::is_three_d(&e.id)) {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
}
|
||||
if let Some(e) = effect
|
||||
&& effects::is_three_d(&e.id)
|
||||
&& visible != Some(false)
|
||||
{
|
||||
let mut prospective = effects::merged_params(&e.id, &e.params);
|
||||
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(&e.id, ¶ms)) {
|
||||
let to = kind.unwrap_or(&e.id);
|
||||
let mut prospective =
|
||||
if to == e.id { effects::merged_params(&e.id, &e.params) } else { effects::three_d_params_as(&e.id, &e.params, to) };
|
||||
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, ¶ms)) {
|
||||
cur.extend(new);
|
||||
}
|
||||
effects::validate_three_d(n, &e.id, &prospective).map_err(|e| bad(C, e))?;
|
||||
effects::validate_three_d(n, to, &prospective).map_err(|e| bad(C, e))?;
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
@@ -498,6 +590,12 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
@@ -823,8 +921,40 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
changed.then_some(n)
|
||||
}
|
||||
|
||||
/// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that
|
||||
/// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an
|
||||
/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's
|
||||
/// art counts where an instance of it expands. `seen` holds the symbols already looked into.
|
||||
fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet<String>) -> bool {
|
||||
let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some();
|
||||
let mut symbols = vec![];
|
||||
let mut holds = false;
|
||||
n.walk(&mut |c| {
|
||||
if !in_art && !expandable(c) {
|
||||
return;
|
||||
}
|
||||
holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin));
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
symbols.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
holds
|
||||
|| symbols.into_iter().any(|name| {
|
||||
seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen))
|
||||
})
|
||||
}
|
||||
|
||||
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = appearance_targets(s, p)?;
|
||||
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
let d = &s.doc()?.doc;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) {
|
||||
return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into()));
|
||||
}
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
@@ -859,5 +989,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
mod lighting_presets_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod three_d_type_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn setup(effect: &str, params: Value) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":params})).unwrap();
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn effect(s: &Session, id: NodeId) -> (String, Value) {
|
||||
let e = &s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0];
|
||||
(e.id.clone(), e.params.clone())
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_turns_the_effect_in_place_keeping_shared_settings_in_one_undo_step() {
|
||||
let types = [("plane", "threeD.rotate"), ("extrude", "threeD.extrude"), ("revolve", "threeD.revolve"), ("inflate", "threeD.inflate")];
|
||||
for (from_type, from) in types {
|
||||
for (to_type, to) in types {
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
let (mut s, id) = setup(from, json!({"rotationX": 12.0, "rotationY": -30.0, "rotationZ": 5.0, "ambient": 40.0, "lightIntensity": 55.0}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let p = json!({"index": 0, "item": null, "threeDType": to_type});
|
||||
s.check_params("effect.setParams", &p).unwrap();
|
||||
s.execute("effect.setParams", &p).unwrap();
|
||||
let (now, params) = effect(&s, id);
|
||||
assert_eq!(now, to, "{from_type} → {to_type}");
|
||||
assert_eq!(params["rotationX"], 12.0, "{from_type} → {to_type}");
|
||||
assert_eq!(params["rotationY"], -30.0);
|
||||
assert_eq!(params["ambient"], 40.0);
|
||||
assert_eq!(params["lightIntensity"], 55.0);
|
||||
// Settings only the new effect takes start at its defaults; others are dropped.
|
||||
let defaults = vectorcraft_render::effects::default_params(to).unwrap();
|
||||
for key in params.as_object().unwrap().keys() {
|
||||
assert!(defaults.get(key).is_some(), "{from_type} → {to_type} kept `{key}`");
|
||||
}
|
||||
if to == "threeD.extrude" {
|
||||
assert_eq!(params["bevel"], defaults["bevel"]);
|
||||
}
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_carries_depth_between_extrude_and_inflate_and_merges_params_after() {
|
||||
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0, "twist": 30.0, "bevel": "classic"}));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "inflate", "params": {"volume": 70.0}})).unwrap();
|
||||
let (now, params) = effect(&s, id);
|
||||
assert_eq!(now, "threeD.inflate");
|
||||
assert_eq!(params["depth"], 80.0);
|
||||
assert_eq!(params["twist"], 30.0);
|
||||
assert_eq!(params["volume"], 70.0);
|
||||
assert!(params.get("bevel").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolve_angles_outside_half_a_turn_wrap_when_the_type_leaves_revolve() {
|
||||
let (mut s, id) = setup("threeD.revolve", json!({"rotationX": 270.0, "rotationY": -200.0}));
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "plane"})).unwrap();
|
||||
let (_, params) = effect(&s, id);
|
||||
assert_eq!(params["rotationX"], -90.0);
|
||||
assert_eq!(params["rotationY"], 160.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_type_alone_changes_nothing_and_records_no_undo_step() {
|
||||
let (mut s, id) = setup("threeD.extrude", json!({"depth": 80.0}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let r = s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert_eq!(undo_len(&s), history);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// With other changes the edit runs as usual.
|
||||
s.execute("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 90.0}})).unwrap();
|
||||
assert_eq!(effect(&s, id).1["depth"], 90.0);
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_type_with_an_object_without_effects_selected_too_records_no_undo_step() {
|
||||
let (mut s, a) = setup("threeD.extrude", json!({}));
|
||||
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(undo_len(&s), history);
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_rejects_unknown_types_and_effects_that_are_not_3d() {
|
||||
let (mut s, _) = setup("threeD.extrude", json!({}));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
for t in [json!("cube"), json!(""), json!(null), json!(2), json!("Plane"), json!("plane/../x")] {
|
||||
let p = json!({"index": 0, "threeDType": t});
|
||||
let err = s.execute("effect.setParams", &p).unwrap_err().to_string();
|
||||
assert!(err.contains("must be one of plane, extrude, revolve, inflate"), "{t}: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
|
||||
let err = s.execute("effect.setParams", &json!({"index": 1, "threeDType": "plane"})).unwrap_err().to_string();
|
||||
assert!(err.contains("needs a 3D effect at index 1"), "{err}");
|
||||
let err = s.execute("effect.setParams", &json!({"index": 5, "threeDType": "plane"})).unwrap_err().to_string();
|
||||
assert!(err.contains("no effect at index 5"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_type_turns_every_selected_object_in_one_undo_step() {
|
||||
let (mut s, a) = setup("threeD.rotate", json!({}));
|
||||
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#d63333"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.rotate","item":null})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "item": null, "aligned": true, "threeDType": "extrude"})).unwrap();
|
||||
assert_eq!(effect(&s, a).0, "threeD.extrude");
|
||||
assert_eq!(effect(&s, b).0, "threeD.extrude");
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_for_the_new_type_pass_the_parameter_check() {
|
||||
let (s, _) = setup("threeD.rotate", json!({}));
|
||||
// `depth` is an Extrude & Bevel setting, checked against the effect the type makes.
|
||||
s.check_params("effect.setParams", &json!({"index": 0, "threeDType": "extrude", "params": {"depth": 20.0}})).unwrap();
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place.
|
||||
//! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`).
|
||||
//!
|
||||
//! [`FORMATS`] is the single list of formats (append-only); open dialogs use [`open_filters`],
|
||||
//! agents query `document.formats`.
|
||||
@@ -32,7 +33,9 @@ mod export;
|
||||
pub(crate) mod imagemap;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod heifread;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
@@ -54,6 +57,7 @@ pub mod zip;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
@@ -72,6 +76,8 @@ pub use load::{
|
||||
read_for_open, texture_image,
|
||||
};
|
||||
pub use load::{losses_summary, overwrite_losses};
|
||||
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
|
||||
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
@@ -202,6 +208,8 @@ mod tests_psd;
|
||||
#[cfg(test)]
|
||||
mod tests_psdread;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_heifread;
|
||||
#[cfg(test)]
|
||||
mod tests_jp2read;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -95,11 +95,93 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
match source {
|
||||
"folder" => batch_folder(s, C, p, override_open, &run),
|
||||
"datasets" => batch_datasets(s, C, &run),
|
||||
"datasets" => {
|
||||
let one_file = batch_overwrites_one_file(s, p);
|
||||
let mut r = batch_datasets(s, C, &run)?;
|
||||
if one_file {
|
||||
r["warning"] = json!(ONE_FILE_WARNING);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
_ => Err(bad(C, "`source` must be `folder` or `datasets`")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `warning` of a Data Sets batch for which [`batch_overwrites_one_file`] holds.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const ONE_FILE_WARNING: &str = "each data set saves over the same file, which keeps only the last data set";
|
||||
|
||||
/// Whether an `action.batch` with params `p` plays on data sets of the open document in `s` and
|
||||
/// writes each data set to the same file. Save and Close saves the open document over its own file
|
||||
/// after every data set, unless a Save step that Override Save points into `destinationFolder`
|
||||
/// first makes each data set's file the document's own. A step that the batch does not point into `destinationFolder` writes the
|
||||
/// same file every time when it writes one: a Save, Save As, Save a Copy, Save as Template, Export,
|
||||
/// Export Selection, PDF, EPS, DXF, Save for Web or Save for Office Documents step that gives a
|
||||
/// `path`; a Save step without a `path` when the document has a file of its own (saved, and not
|
||||
/// converted from an older version or restored by Data Recovery) and the step gives no `format` or
|
||||
/// the document's own; an Export for Screens step whose `folder`, given or from its
|
||||
/// `exportPreset`, names a folder, whatever the overrides.
|
||||
/// Other steps return their data instead of writing a file.
|
||||
pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool {
|
||||
if p.get("source").and_then(Value::as_str) != Some("datasets") {
|
||||
return false;
|
||||
}
|
||||
let folder = p.get("destinationFolder").and_then(Value::as_str).is_some();
|
||||
let redirected = |key: &str| folder && p.get(key).and_then(Value::as_bool).unwrap_or(true);
|
||||
let (save, export) = (redirected("overrideSave"), redirected("overrideExport"));
|
||||
let steps = p.get("commands").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
|
||||
if p.get("destination").and_then(Value::as_str) == Some("saveAndClose") && !saves_move_to_each_file(steps, save) {
|
||||
return true;
|
||||
}
|
||||
// The format of the open document's own file, which a Save step without a `path` writes.
|
||||
let own_format = s.active().filter(|st| st.path.is_some() && !st.converted && !st.recovered).map(|st| st.format);
|
||||
let names = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.is_empty());
|
||||
steps.iter().any(|c| {
|
||||
let params = c.get("params").cloned().unwrap_or_else(|| Value::Object(Default::default()));
|
||||
let path = names(params.get("path"));
|
||||
let own_file = || match params.get("format").and_then(Value::as_str).filter(|f| !f.is_empty()) {
|
||||
None => own_format.is_some(),
|
||||
Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)),
|
||||
};
|
||||
match c.get("command").and_then(Value::as_str).unwrap_or("") {
|
||||
"document.save" | "file.save" => !save && (path || own_file()),
|
||||
"file.saveAs" => !save && path,
|
||||
"file.saveCopy" | "file.saveAsTemplate" => path,
|
||||
"document.export" | "document.exportSelection" => !export && path,
|
||||
// The batch does not point these exports into `destinationFolder`.
|
||||
"document.exportPdf" | "document.exportEps" | "document.exportDxf" | "document.exportForWeb" | "document.exportForOffice" => path,
|
||||
// Override Export sets `path`, which Export for Screens does not read: its `folder` stays.
|
||||
"document.exportForScreens" => super::screens::with_preset(s, ¶ms).is_ok_and(|p| names(p.get("folder"))),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `steps` hold a Save, Save As or `document.save` step that Override Save points at each
|
||||
/// data set's own file in the destination folder (`redirected`). Such a step makes that file the
|
||||
/// document's own, so Save and Close then saves each data set to its own file.
|
||||
fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool {
|
||||
redirected && steps.iter().any(|c| retargeting_save(c, true))
|
||||
}
|
||||
|
||||
/// Whether step `c` is a Save, Save As or `document.save` that writes a file (its own `path`, or one
|
||||
/// in the destination folder when `redirected`) and makes that file the document's own: a save in
|
||||
/// the native template format writes a copy and leaves the document's file as it was.
|
||||
fn retargeting_save(c: &Value, redirected: bool) -> bool {
|
||||
if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) {
|
||||
return false;
|
||||
}
|
||||
let params = c.get("params");
|
||||
let path = params.and_then(|p| p.get("path")).and_then(Value::as_str).filter(|p| !p.is_empty());
|
||||
let format_ok = match params.and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()) {
|
||||
Some(f) => super::format(f).is_some_and(|f| f.id != "template"),
|
||||
// Override Save gives the step a native file name; else its own path names the format.
|
||||
None if redirected => true,
|
||||
None => path.and_then(super::format_for_name).is_none_or(|f| f.id != "template"),
|
||||
};
|
||||
format_ok && (redirected || path.is_some())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: &Run<'_>) -> Result<Value> {
|
||||
use super::{absolute_path, may_read};
|
||||
@@ -145,6 +227,18 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> {
|
||||
if names.len() > MAX_BATCH_FILES {
|
||||
return Err(bad(cmd, format!("more than {MAX_BATCH_FILES} data sets")));
|
||||
}
|
||||
let redirected = run.override_save && run.dest_folder.is_some();
|
||||
// A recorded save with a file to write gives the document a file of its own before Save and Close.
|
||||
if run.destination == "saveAndClose" && !run.steps.iter().any(|c| retargeting_save(c, redirected)) {
|
||||
if st.path.is_none() {
|
||||
return Err(bad(cmd, "the document has never been saved"));
|
||||
}
|
||||
// `save_plan` writes no file for a document converted from an older version or restored by
|
||||
// Data Recovery.
|
||||
if st.converted || st.recovered {
|
||||
return Err(bad(cmd, "save the document with Save As before Save and Close"));
|
||||
}
|
||||
}
|
||||
let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string();
|
||||
let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?;
|
||||
let steps = filter_steps(run.steps, true, false);
|
||||
@@ -1292,6 +1386,213 @@ mod tests {
|
||||
assert_eq!(file_names(&dest), ["Untitled_A-B-3.vectorcraft", "Untitled_a-b-2.vectorcraft", "Untitled_a-b.vectorcraft"], "{r}");
|
||||
}
|
||||
|
||||
/// A saved document with a text object bound to `Name` and two data sets, `A` and `B`.
|
||||
fn saved_with_two_data_sets(path: &std::path::Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "A"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
s.execute("variable.bind", &json!({"variable": "Name", "ids": [id]})).unwrap();
|
||||
s.execute("dataset.capture", &json!({"name": "A"})).unwrap();
|
||||
s.execute("text.setText", &json!({"ids": [id], "text": "B"})).unwrap();
|
||||
s.execute("dataset.capture", &json!({"name": "B"})).unwrap();
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn save_and_close_over_data_sets(s: &mut Session) -> Result<Value> {
|
||||
s.execute(
|
||||
"action.batch",
|
||||
&json!({"source": "datasets", "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_over_data_sets_saves_each_over_the_template_and_warns() {
|
||||
let path = tmp("save-close-sets").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
std::fs::write(&path, b"stale").unwrap();
|
||||
let r = save_and_close_over_data_sets(&mut s).unwrap();
|
||||
assert_eq!((r["count"].as_u64(), r["failed"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
assert_ne!(std::fs::read(&path).unwrap(), b"stale", "the template's file is saved over");
|
||||
assert_eq!(file_names(path.parent().unwrap()), ["template.vectorcraft"], "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset.as_deref(), Some("B"), "the last data set is applied");
|
||||
assert_eq!(st.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the template stays open");
|
||||
assert!(!st.is_dirty(), "the last data set is saved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_warns_when_a_recorded_save_writes_one_file_for_every_data_set() {
|
||||
let path = tmp("recorded-save-sets").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let save = json!([{"command": "document.save", "params": {}}]);
|
||||
let r = s.execute("action.batch", &json!({"source": "datasets", "commands": save})).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
let dest = tmp("recorded-save-dest");
|
||||
let p = json!({"source": "datasets", "destination": "folder", "destinationFolder": dest.to_string_lossy(), "commands": save});
|
||||
let r = s.execute("action.batch", &p).unwrap();
|
||||
assert!(r.get("warning").is_none(), "Override Save points each save into the folder: {r}");
|
||||
let unlock = json!({"source": "datasets", "commands": [{"command": "object.unlockAll", "params": {}}]});
|
||||
let r = s.execute("action.batch", &unlock).unwrap();
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_after_a_redirected_save_writes_each_data_set_to_its_own_file() {
|
||||
let save_close = |dest: &std::path::Path| {
|
||||
json!({
|
||||
"source": "datasets",
|
||||
"destination": "saveAndClose",
|
||||
"destinationFolder": dest.to_string_lossy(),
|
||||
"commands": [{"command": "document.save", "params": {}}]
|
||||
})
|
||||
};
|
||||
let path = tmp("redirected-save-close").join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let dest = tmp("redirected-save-close-dest");
|
||||
let p = save_close(&dest);
|
||||
let mut kept = p.clone();
|
||||
kept["overrideSave"] = json!(false);
|
||||
assert!(batch_overwrites_one_file(&s, &kept), "without Override Save the save stays on the template");
|
||||
let r = s.execute("action.batch", &p).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
assert_eq!(file_names(&dest), ["template_A.vectorcraft", "template_B.vectorcraft"], "{r}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the template's file stays as it was");
|
||||
// A document never saved gets its files from the redirected save too.
|
||||
let mut unsaved = with_data_sets(&["a", "b"]);
|
||||
let dest = tmp("redirected-save-close-unsaved");
|
||||
let r = unsaved.execute("action.batch", &save_close(&dest)).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert!(r.get("warning").is_none(), "{r}");
|
||||
assert_eq!(file_names(&dest), ["Untitled_a.vectorcraft", "Untitled_b.vectorcraft"], "{r}");
|
||||
// A template save writes a copy: Save and Close still saves over the document's own file.
|
||||
let mut template = save_close(&dest);
|
||||
template["commands"] = json!([{"command": "document.save", "params": {"format": "template"}}]);
|
||||
assert!(batch_overwrites_one_file(&s, &template), "{template}");
|
||||
let mut never = with_data_sets(&["a", "b"]);
|
||||
let msg = never.execute("action.batch", &template).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("the document has never been saved"), "{msg}");
|
||||
// A recorded Save As with its own path gives a never-saved document its file, the same one
|
||||
// for every data set.
|
||||
let one = tmp("save-as-then-close").join("one.vectorcraft");
|
||||
let p = json!({
|
||||
"source": "datasets",
|
||||
"destination": "saveAndClose",
|
||||
"commands": [{"command": "file.saveAs", "params": {"path": one.to_string_lossy()}}]
|
||||
});
|
||||
let r = never.execute("action.batch", &p).unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_eq!(r["warning"], ONE_FILE_WARNING, "{r}");
|
||||
assert!(one.exists(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_file_rule_covers_save_and_close_and_steps_left_in_place() {
|
||||
let saved = saved_with_two_data_sets(&tmp("one-file-rule").join("template.vectorcraft"));
|
||||
let unsaved = with_data_sets(&["a"]);
|
||||
let with = |extra: Value| {
|
||||
let mut p = json!({"source": "datasets", "commands": [{"command": "document.export", "params": {"path": "/x/a.png"}}]});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
batch_overwrites_one_file(&saved, &p)
|
||||
};
|
||||
assert!(with(json!({})), "an export with its own path");
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out"})));
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "overrideExport": false})));
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "overrideSave": false})));
|
||||
assert!(!with(json!({"source": "folder"})), "a folder source opens a file per pass");
|
||||
assert!(with(json!({"destination": "saveAndClose", "commands": [{"command": "object.unlockAll"}]})));
|
||||
let saved_as = json!({"commands": [{"command": "file.saveAs", "params": {"path": "/x/a.svg"}}]});
|
||||
assert!(with(saved_as.clone()));
|
||||
assert!(!with(json!({"destination": "folder", "destinationFolder": "/out", "commands": saved_as["commands"]})));
|
||||
assert!(!with(json!({"commands": [{"command": "file.saveAs", "params": {}}]})), "no path: the data comes back");
|
||||
assert!(!with(json!({"commands": [{"command": "document.export", "params": {"format": "png"}}]})), "no path: the data comes back");
|
||||
let copy = json!([{"command": "file.saveCopy", "params": {"path": "/x/a.vectorcraft"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": copy})), "Override Save leaves copies alone");
|
||||
let save = |format: Option<&str>| {
|
||||
let params = format.map_or(json!({}), |f| json!({"format": f}));
|
||||
json!({"source": "datasets", "commands": [{"command": "document.save", "params": params}]})
|
||||
};
|
||||
assert!(batch_overwrites_one_file(&saved, &save(None)), "the document's own file");
|
||||
assert!(batch_overwrites_one_file(&saved, &save(Some("vectorcraft"))), "the document's own format");
|
||||
assert!(!batch_overwrites_one_file(&unsaved, &save(None)), "a document never saved has no file to write");
|
||||
assert!(!batch_overwrites_one_file(&saved, &save(Some("svg"))), "another format without a path: the data comes back");
|
||||
assert!(!with(json!({"commands": [{"command": "file.saveCopy", "params": {"folder": "/x"}}]})), "a folder alone: the data comes back");
|
||||
let screens = json!([{"command": "document.exportForScreens", "params": {"folder": "/x"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": screens})), "Override Export leaves its folder");
|
||||
assert!(!with(json!({"commands": [{"command": "document.exportForScreens", "params": {}}]})));
|
||||
let preset = json!([{"command": "document.exportForScreens", "params": {"exportPreset": "Logo Package"}}]);
|
||||
assert!(!with(json!({"commands": preset})), "a preset without a folder: the data comes back");
|
||||
for id in ["document.exportPdf", "document.exportEps", "document.exportDxf", "document.exportForWeb", "document.exportForOffice"] {
|
||||
let step = json!([{"command": id, "params": {"path": "/x/a.out"}}]);
|
||||
assert!(with(json!({"destination": "folder", "destinationFolder": "/out", "commands": step})), "{id} keeps its path");
|
||||
assert!(!with(json!({"commands": [{"command": id, "params": {}}]})), "{id} without a path: the data comes back");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_save_and_close_over_data_sets_of_a_converted_or_recovered_document() {
|
||||
for converted in [true, false] {
|
||||
let path = tmp(if converted { "converted-sets" } else { "recovered-sets" }).join("template.vectorcraft");
|
||||
let mut s = saved_with_two_data_sets(&path);
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let (active, revision) = {
|
||||
let st = s.doc_mut().unwrap();
|
||||
if converted {
|
||||
st.converted = true;
|
||||
} else {
|
||||
st.recovered = true;
|
||||
}
|
||||
(st.doc.variables.active_dataset.clone(), st.revision)
|
||||
};
|
||||
let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("save the document with Save As before Save and Close"), "{msg}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes, "the file is not written");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected");
|
||||
assert_eq!(st.revision, revision, "no step runs");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_save_and_close_over_data_sets_of_an_unsaved_document() {
|
||||
let mut s = with_data_sets(&["a", "b"]);
|
||||
let (active, revision) = {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.variables.active_dataset.clone(), st.revision)
|
||||
};
|
||||
let msg = save_and_close_over_data_sets(&mut s).unwrap_err().to_string();
|
||||
assert!(msg.ends_with("the document has never been saved"), "{msg}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.variables.active_dataset, active, "no data set is selected");
|
||||
assert_eq!(st.revision, revision, "no step runs");
|
||||
assert!(st.path.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_save_and_close_saves_and_closes_each_source_file() {
|
||||
let src = tmp("save-close-src");
|
||||
let a = write_svg(&src, "a.svg", "#f00");
|
||||
let before = std::fs::read(&a).unwrap();
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"action.batch",
|
||||
&json!({"folder": src.to_string_lossy(), "destination": "saveAndClose", "commands": [{"command": "object.unlockAll", "params": {}}]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["failed"], 0, "{r}");
|
||||
assert_ne!(std::fs::read(&a).unwrap(), before, "the source file is saved over");
|
||||
assert_eq!(file_names(&src), ["a.svg"], "{r}");
|
||||
assert!(s.doc().is_err(), "the source file is closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_refuses_nesting_and_empty_commands() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch…",
|
||||
[],
|
||||
None,
|
||||
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped}",
|
||||
"{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportForScreens / document.exportSelection the same way), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-`; a name already used in the batch or whose output already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)",
|
||||
always,
|
||||
action_batch::action_batch
|
||||
),
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_cad::{ColorDepth, DxfOptions, DxfVersion, Preserve, RasterFormat};
|
||||
use vectorcraft_cad::{ColorDepth, DxfOptions, DxfPreset, DxfVersion, Preserve, RasterFormat};
|
||||
use vectorcraft_doc::{Document, Unit};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}",
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
@@ -33,6 +33,12 @@ pub(super) const OPTIONS: &[FormatOption] = &[
|
||||
super::ARTBOARDS,
|
||||
super::RANGE,
|
||||
super::USE_ARTBOARDS,
|
||||
FormatOption {
|
||||
name: "dxfPreset",
|
||||
ty: "string",
|
||||
default: "\"custom\"",
|
||||
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it",
|
||||
},
|
||||
FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" },
|
||||
FormatOption {
|
||||
name: "unit",
|
||||
@@ -120,6 +126,7 @@ impl Unsupported {
|
||||
struct Params {
|
||||
#[serde(flatten)]
|
||||
boards: ArtboardPick,
|
||||
dxf_preset: Option<String>,
|
||||
version: Option<Value>,
|
||||
unit: Option<String>,
|
||||
scale: Option<f64>,
|
||||
@@ -150,7 +157,8 @@ fn choice<T>(field: &str, v: Option<String>, read: impl Fn(&str) -> Option<T>, d
|
||||
/// The DXF options in `p` (the region and crop are set per drawing) and the artboard choice.
|
||||
fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
let q: Params = if p.is_object() { Params::deserialize(p).map_err(|e| bad(C, format!("DXF options: {e}")))? } else { Params::default() };
|
||||
let d = DxfOptions::default();
|
||||
// The options a preset sets are the defaults of those `p` leaves out.
|
||||
let d = choice("dxfPreset", q.dxf_preset, DxfPreset::from_id, DxfPreset::Custom, "custom or cnc")?.options();
|
||||
let scale = q.scale.unwrap_or(d.scale);
|
||||
if !(scale.is_finite() && vectorcraft_cad::SCALE_RANGE.contains(&scale)) {
|
||||
return Err(bad(C, format!("DXF scale must be a positive number up to {}, not {scale}", vectorcraft_cad::SCALE_RANGE.end())));
|
||||
@@ -181,6 +189,11 @@ pub fn check(p: &Value) -> std::result::Result<(), String> {
|
||||
parse(p).map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The DXF options in `p` (the region and crop left at their defaults).
|
||||
pub fn options(p: &Value) -> std::result::Result<DxfOptions, String> {
|
||||
parse(p).map(|(o, _)| o).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Encode `doc` as DXF: one drawing whose origin is the chosen artboard's bottom-left corner
|
||||
/// (default the first), or with `use_artboards` one drawing per chosen artboard (default all)
|
||||
/// holding the art over it.
|
||||
|
||||
@@ -214,10 +214,11 @@ fn selection(s: &mut Session, cmd: &str) -> Result<(Document, vectorcraft_geom::
|
||||
}
|
||||
|
||||
/// The selected objects (their top-most selected ancestors) that are artwork: those on template
|
||||
/// layers are guides and are left out.
|
||||
/// layers are guides and are left out. With an object of a dynamic symbol instance's art selected,
|
||||
/// the instance is exported whole.
|
||||
pub(crate) fn selected_artwork(s: &Session) -> Result<Vec<NodeId>> {
|
||||
let ids = edit::selected_roots(s)?;
|
||||
let st = s.doc()?;
|
||||
let ids = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
|
||||
let is_template = |id| st.doc.node(id).is_some_and(|l| matches!(l.kind, NodeKind::Layer { template: true, .. }));
|
||||
// On a template layer or sublayer, at any depth.
|
||||
let on_template = |id| st.doc.ancestry(id).is_some_and(|a| a.into_iter().any(is_template));
|
||||
|
||||
@@ -503,6 +503,8 @@ pub const FORMATS: &[Format] = &[
|
||||
reader("pxr", "Pixar", &["pxr"], "image/x-pixar", true),
|
||||
// JP2 and raw codestreams are decoded to PNG; JPX composition is not supported.
|
||||
reader("jpeg2000", "JPEG 2000", &["jpf", "jpx", "jp2", "j2k", "j2c", "jpc"], "image/jp2", true),
|
||||
// HEVC-coded HEIF still images, decoded to PNG; image sequences are not read.
|
||||
reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true),
|
||||
];
|
||||
|
||||
/// Every extension `document.open` reads (the "All readable files" filter of open dialogs).
|
||||
@@ -537,6 +539,8 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
"j2k",
|
||||
"j2c",
|
||||
"jpc",
|
||||
"heic",
|
||||
"heif",
|
||||
"psd",
|
||||
"pdd",
|
||||
"psb",
|
||||
@@ -554,11 +558,13 @@ pub const OPEN_EXTS: &[&str] = &[
|
||||
|
||||
/// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to
|
||||
/// raster editors, so Finder and file managers don't offer a vector app for them, and there is no
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar or JPEG 2000 type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000 or HEIC/HEIF type, nor one for the `.pns`, `.dib` and `.rle` names of
|
||||
/// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS
|
||||
/// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it.
|
||||
pub const UNASSOCIATED_EXTS: &[&str] =
|
||||
&["psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc"];
|
||||
pub const UNASSOCIATED_EXTS: &[&str] = &[
|
||||
"psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc",
|
||||
"heic", "heif",
|
||||
];
|
||||
|
||||
/// The extension that picks each writable format when exporting (the format's first; PNG-8 shares
|
||||
/// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order.
|
||||
@@ -621,6 +627,8 @@ pub const PLACE_EXTS: &[&str] = &[
|
||||
"j2k",
|
||||
"j2c",
|
||||
"jpc",
|
||||
"heic",
|
||||
"heif",
|
||||
"psd",
|
||||
"pdd",
|
||||
"psb",
|
||||
|
||||
@@ -0,0 +1,627 @@
|
||||
//! HEIC and HEIF images for File › Open and File › Place, decoded with heic-rs when the engine's
|
||||
//! `heif` feature is on (the default). The image is bounded before decoding and converted to RGBA
|
||||
//! for the common PNG storage path. A build without the feature still recognizes the files and
|
||||
//! refuses them with a message.
|
||||
|
||||
#[cfg(all(test, feature = "heif"))]
|
||||
pub(super) use decoder::{active_sps, picture_bytes, sps_signal, sps_size};
|
||||
#[cfg(feature = "heif")]
|
||||
pub(super) use decoder::{decode, quarter_turned, with_exif};
|
||||
|
||||
/// The brands heic-rs 0.1.4 reads: HEVC-coded images and image sequences (ISO/IEC 23008-12 annex
|
||||
/// B) and the general image and sequence brands.
|
||||
const BRANDS: [&[u8; 4]; 7] = [b"heic", b"heix", b"heim", b"heis", b"hevc", b"mif1", b"msf1"];
|
||||
|
||||
/// Recognize a HEIF file by its `ftyp` box: one of [`BRANDS`] as the major brand or a compatible
|
||||
/// one, and no AVIF brand (`avif`, `avis`), as heic-rs refuses a file that lists one. The box is
|
||||
/// read as JP2 boxes are ([`super::jp2read::boxes`]): ISO BMFF sizes, the 64-bit one included.
|
||||
pub(super) fn is_heif(bytes: &[u8]) -> bool {
|
||||
let Some((b"ftyp", ftyp)) = super::jp2read::boxes(bytes).next() else { return false };
|
||||
let Some(major) = ftyp.get(..4).and_then(|b| <&[u8; 4]>::try_from(b).ok()) else { return false };
|
||||
if ftyp.len() < 8 {
|
||||
return false;
|
||||
}
|
||||
let compatible = ftyp.get(8..).unwrap_or_default().as_chunks::<4>().0;
|
||||
let brands = || std::iter::once(major).chain(compatible);
|
||||
!brands().any(|brand| matches!(brand, b"avif" | b"avis")) && brands().any(|brand| BRANDS.contains(&brand))
|
||||
}
|
||||
|
||||
/// Without the `heif` feature every HEIF file is refused.
|
||||
#[cfg(not(feature = "heif"))]
|
||||
pub(super) fn decode(_bytes: &[u8], _max_alloc: u64) -> Result<image::RgbaImage, String> {
|
||||
Err("HEIC and HEIF images can't be opened in this build".into())
|
||||
}
|
||||
|
||||
/// Without the `heif` feature no image is decoded, so none is turned.
|
||||
#[cfg(not(feature = "heif"))]
|
||||
pub(super) fn quarter_turned(_bytes: &[u8]) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Without the `heif` feature no resolution is read.
|
||||
#[cfg(not(feature = "heif"))]
|
||||
pub(super) fn with_exif<T>(_bytes: &[u8], _read: impl FnOnce(&[u8]) -> Option<T>) -> Option<T> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
mod decoder {
|
||||
use heic_rs::context::Context;
|
||||
use heic_rs::{DecodeOptions, Error, MatrixCoefficients, Nclx, PixelLayout, Range};
|
||||
|
||||
/// The message for a file that isn't a readable HEIF image.
|
||||
const UNREADABLE: &str = "the HEIC or HEIF file can't be read";
|
||||
/// The message for an image sequence, an overlay, an image that isn't HEVC-coded, a grid whose
|
||||
/// tiles are cropped, turned or mirrored, or an HEVC coding tool the decoder doesn't implement.
|
||||
const UNSUPPORTED: &str = "the HEIC or HEIF file holds a kind of image that can't be read";
|
||||
|
||||
/// Decode the primary image within `max_alloc` bytes, counting the decoder's planes, the RGBA
|
||||
/// output and the copy that rotating or cropping makes, with the container's rotation, mirror
|
||||
/// and crop applied. An embedded RGB ICC profile, or `nclx` Display P3 primaries with the sRGB
|
||||
/// curve, is converted to sRGB; other `nclx` values are read as sRGB. A panic inside the
|
||||
/// decoder is reported as an unreadable file.
|
||||
pub(in super::super) fn decode(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
|
||||
crate::guard::catch_panic(|| decode_unguarded(bytes, max_alloc)).unwrap_or_else(|_| Err(UNREADABLE.into()))
|
||||
}
|
||||
|
||||
/// Whether the container's rotations of the primary image add up to an odd number of quarter
|
||||
/// turns, so its width and height swap. The decoder applies every `irot` the item lists.
|
||||
pub(in super::super) fn quarter_turned(bytes: &[u8]) -> bool {
|
||||
let turned = || {
|
||||
let ctx = Context::open(bytes).ok()?;
|
||||
let props = ctx.props(ctx.meta.primary).ok()?;
|
||||
let quarters = props.transforms.iter().filter(|t| matches!(t, heic_rs::props::Transform::Rotate(r) if r.swaps_axes())).count();
|
||||
Some(quarters % 2 == 1)
|
||||
};
|
||||
crate::guard::catch_panic(turned).ok().flatten().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `read` of the primary image's EXIF block, a TIFF structure inside `bytes`, for its
|
||||
/// resolution tags.
|
||||
pub(in super::super) fn with_exif<T>(bytes: &[u8], read: impl FnOnce(&[u8]) -> Option<T>) -> Option<T> {
|
||||
let find = || {
|
||||
let ctx = Context::open(bytes).ok()?;
|
||||
ctx.exif(ctx.meta.primary).ok().flatten()
|
||||
};
|
||||
crate::guard::catch_panic(find).ok().flatten().and_then(read)
|
||||
}
|
||||
|
||||
fn decode_unguarded(bytes: &[u8], max_alloc: u64) -> Result<image::RgbaImage, String> {
|
||||
let refused = |e: Error| match e {
|
||||
Error::Unsupported(_) | Error::MissingBox("hvcC" | "meta") => UNSUPPORTED.to_string(),
|
||||
_ => UNREADABLE.to_string(),
|
||||
};
|
||||
let info = heic_rs::probe(bytes).map_err(refused)?;
|
||||
let ctx = Context::open(bytes).map_err(refused)?;
|
||||
if unsupported_items(&ctx).ok_or(UNREADABLE)? {
|
||||
return Err(UNSUPPORTED.into());
|
||||
}
|
||||
// The stored size, before a crop: the size the decoder holds.
|
||||
let too_large = || format!("an image of {} × {} pixels is too large to draw", info.coded_width, info.coded_height);
|
||||
let declared = u64::from(info.coded_width).checked_mul(u64::from(info.coded_height)).ok_or_else(too_large)?;
|
||||
// A grid is composed at the size its own data gives, which need not match `ispe`.
|
||||
let grid = grid_pixels(&ctx).ok_or(UNREADABLE)?;
|
||||
// A single picture is converted at the size its stream gives, which need not match `ispe`
|
||||
// either.
|
||||
let coded = declared.max(grid).max(stream_pixels(&ctx).ok_or(UNREADABLE)?);
|
||||
let shown = u64::from(info.width).checked_mul(u64::from(info.height)).ok_or_else(too_large)?;
|
||||
// The RGBA output, and a second RGBA image when the decoder rotates, mirrors or crops it,
|
||||
// which is no larger than the first.
|
||||
let output = coded.checked_mul(8).ok_or_else(too_large)?;
|
||||
let pictures = picture_bytes_in(&ctx).ok_or(UNREADABLE)?;
|
||||
// An alpha grid is composed into a frame of 16-bit planes (at most three samples a pixel),
|
||||
// and so is the image's grid when it is decoded with a color description of its tiles or
|
||||
// its stream. A single picture is converted in place.
|
||||
let composed = if grid > 0 { coded.checked_mul(if info.has_alpha { 12 } else { 6 }).ok_or_else(too_large)? } else { 0 };
|
||||
if coded == 0 || shown == 0 || output.checked_add(pictures).and_then(|n| n.checked_add(composed)).is_none_or(|n| n > max_alloc) {
|
||||
return Err(too_large());
|
||||
}
|
||||
let max_pixels = max_alloc / 4;
|
||||
let decoded = match tile_nclx(&ctx).or_else(|| stream_nclx(&ctx)) {
|
||||
Some(nclx) => decode_with_nclx(&ctx, nclx, max_pixels),
|
||||
None => heic_rs::decode(bytes, &DecodeOptions::default().with_layout(PixelLayout::Rgba8).with_max_pixels(Some(max_pixels))),
|
||||
}
|
||||
.map_err(|e| match e {
|
||||
Error::PixelLimit { .. } | Error::BoxTooLarge { .. } => too_large(),
|
||||
e => refused(e),
|
||||
})?;
|
||||
let mut img = image::RgbaImage::from_raw(decoded.width, decoded.height, decoded.data).ok_or(UNREADABLE)?;
|
||||
if let Some(profile) = source_profile(&ctx) {
|
||||
for pixel in img.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let device = [r, g, b].map(|v| f32::from(v) / 255.0);
|
||||
if let Some(rgb) = profile.to_srgb_into(&device, vectorcraft_color::cms::Intent::RelativeColorimetric) {
|
||||
let [r, g, b] = rgb.map(|v| (v * 255.0).round() as u8);
|
||||
pixel.0 = [r, g, b, a];
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
/// The primary image and its alpha image, when it has one.
|
||||
fn primary_and_alpha(ctx: &Context<'_>) -> Option<impl Iterator<Item = u32>> {
|
||||
let primary = ctx.meta.primary;
|
||||
Some(std::iter::once(primary).chain(ctx.alpha_item(primary).ok()?))
|
||||
}
|
||||
|
||||
/// Whether the primary image or its alpha image is neither an HEVC-coded item (`hvc1`, `hev1`)
|
||||
/// nor a grid of them, or is a grid with a tile that carries a crop, rotation or mirror. heic-rs
|
||||
/// 0.1.4 decodes any item with an `hvcC` whatever its type, and composes a grid from its tiles
|
||||
/// as coded, without their transforms: an encoder that pads tiles smaller than its coding block
|
||||
/// (64 × 64 for x265) and crops them back with `clap` gets the wrong pixels.
|
||||
fn unsupported_items(ctx: &Context<'_>) -> Option<bool> {
|
||||
let hevc = |id: u32| ctx.meta.item(id).is_some_and(|info| info.is_hevc());
|
||||
for item in primary_and_alpha(ctx)? {
|
||||
let Some((_, tiles)) = ctx.grid(item).ok()? else {
|
||||
if !hevc(item) {
|
||||
return Some(true);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
for tile in tiles {
|
||||
if !hevc(tile) || !ctx.props(tile).ok()?.transforms.is_empty() {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// The pixels of the larger of the primary image's grid and its alpha image's grid, at the
|
||||
/// output size each grid gives; 0 when neither is a grid.
|
||||
fn grid_pixels(ctx: &Context<'_>) -> Option<u64> {
|
||||
let mut largest = 0u64;
|
||||
for item in primary_and_alpha(ctx)? {
|
||||
if let Some((grid, _)) = ctx.grid(item).ok()? {
|
||||
largest = largest.max(u64::from(grid.output_width) * u64::from(grid.output_height));
|
||||
}
|
||||
}
|
||||
Some(largest)
|
||||
}
|
||||
|
||||
/// The pixels of the larger of the primary image and its alpha image when either is a single
|
||||
/// picture, at the size of its largest sequence parameter set (before its conformance window);
|
||||
/// 0 when both are grids. `None` when a size can't be read.
|
||||
fn stream_pixels(ctx: &Context<'_>) -> Option<u64> {
|
||||
let mut largest = 0u64;
|
||||
for item in primary_and_alpha(ctx)? {
|
||||
if ctx.grid(item).ok()?.is_some() {
|
||||
continue;
|
||||
}
|
||||
// An item without `hvcC` isn't decoded: heic-rs refuses the file.
|
||||
let Some(hvcc) = ctx.props(item).ok()?.hvcc else { continue };
|
||||
for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) {
|
||||
let (width, height, _) = sps_size(nal)?;
|
||||
largest = largest.max(width.checked_mul(height)?);
|
||||
}
|
||||
}
|
||||
Some(largest)
|
||||
}
|
||||
|
||||
/// The first tile's `nclx` when the primary image is a grid without an `nclx` of its own and
|
||||
/// its tiles carry one. heic-rs 0.1.4 converts a grid's samples to RGB with the grid item's
|
||||
/// `nclx` alone, and with its BT.709 limited-range default when the grid has none
|
||||
/// (tbraun96/heic-rs#6).
|
||||
fn tile_nclx(ctx: &Context<'_>) -> Option<Nclx> {
|
||||
let primary = ctx.meta.primary;
|
||||
if ctx.props(primary).ok()?.nclx.is_some() {
|
||||
return None;
|
||||
}
|
||||
let (_, tiles) = ctx.grid(primary).ok()??;
|
||||
ctx.props(*tiles.first()?).ok()?.nclx
|
||||
}
|
||||
|
||||
/// The color description in the HEVC stream's video usability information (ITU-T H.265
|
||||
/// E.2.1) of the primary image, or of its grid's first tile, when neither carries an `nclx`
|
||||
/// (a file whose only color box is an ICC profile, or one without a color box). heic-rs 0.1.4
|
||||
/// reads only the container's `nclx` and otherwise converts with BT.709 limited range.
|
||||
fn stream_nclx(ctx: &Context<'_>) -> Option<Nclx> {
|
||||
let primary = ctx.meta.primary;
|
||||
if ctx.props(primary).ok()?.nclx.is_some() {
|
||||
return None;
|
||||
}
|
||||
let coded = match ctx.grid(primary).ok()? {
|
||||
Some((_, tiles)) => *tiles.first()?,
|
||||
None => primary,
|
||||
};
|
||||
let props = ctx.props(coded).ok()?;
|
||||
if props.nclx.is_some() {
|
||||
return None;
|
||||
}
|
||||
let hvcc = props.hvcc?;
|
||||
let data = ctx.item_data(coded).ok()?;
|
||||
let slices = hvcc.split_nals(&data).ok()?;
|
||||
active_sps(&hvcc.parameter_sets(), &slices).and_then(sps_signal)
|
||||
}
|
||||
|
||||
/// The SPS the first slice of `slices` uses: the one its PPS names (ITU-T H.265 7.4.3.3.1).
|
||||
pub(in super::super) fn active_sps<'a>(parameter_sets: &[&'a [u8]], slices: &[&[u8]]) -> Option<&'a [u8]> {
|
||||
let slice = slices.iter().find(|nal| nal_type(nal).is_some_and(|t| t < 32))?;
|
||||
let bits = &mut Bits { data: &payload(slice), at: 0 };
|
||||
// first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag in an IRAP picture (types 16
|
||||
// to 23), slice_pic_parameter_set_id.
|
||||
bits.skip(1)?;
|
||||
if nal_type(slice).is_some_and(|t| (16..=23).contains(&t)) {
|
||||
bits.skip(1)?;
|
||||
}
|
||||
let pps_id = bits.exp_golomb()?;
|
||||
// pps_pic_parameter_set_id, pps_seq_parameter_set_id.
|
||||
let pps_ids = |nal: &[u8]| {
|
||||
let bits = &mut Bits { data: &payload(nal), at: 0 };
|
||||
Some((bits.exp_golomb()?, bits.exp_golomb()?))
|
||||
};
|
||||
let sps_id = parameter_sets.iter().filter(|nal| nal_type(nal) == Some(PPS)).find_map(|nal| pps_ids(nal).filter(|(id, _)| *id == pps_id))?.1;
|
||||
let sps_ids = |nal: &[u8]| {
|
||||
let rbsp = sps_payload(nal)?;
|
||||
sps_head(&mut Bits { data: &rbsp, at: 0 }).map(|(_, id, ..)| id)
|
||||
};
|
||||
parameter_sets.iter().copied().find(|nal| sps_ids(nal) == Some(sps_id))
|
||||
}
|
||||
|
||||
/// The primary image decoded as heic-rs 0.1.4 decodes it (a grid's tiles one after another),
|
||||
/// with its samples converted to RGBA with `nclx`, the alpha image applied and the image's
|
||||
/// rotation, mirror and crop applied.
|
||||
fn decode_with_nclx(ctx: &Context<'_>, nclx: Nclx, max_pixels: u64) -> heic_rs::Result<heic_rs::Image> {
|
||||
use heic_rs::hevc::Frame;
|
||||
|
||||
fn coded(ctx: &Context<'_>, id: u32) -> heic_rs::Result<Frame> {
|
||||
let props = ctx.props(id)?;
|
||||
let hvcc = props.hvcc.as_ref().ok_or(Error::MissingBox("hvcC"))?;
|
||||
let data = ctx.item_data(id)?;
|
||||
let frame = heic_rs::hevc::decode_still(&hvcc.parameter_sets(), &hvcc.split_nals(&data)?)?;
|
||||
frame.validate()?;
|
||||
Ok(frame)
|
||||
}
|
||||
fn item(ctx: &Context<'_>, id: u32, max_pixels: u64) -> heic_rs::Result<Frame> {
|
||||
match ctx.grid(id)? {
|
||||
Some((grid, tiles)) => {
|
||||
// The tiles decode in parallel on native, as heic-rs's own decode does.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let frames = {
|
||||
use rayon::prelude::*;
|
||||
tiles.par_iter().map(|&t| coded(ctx, t)).collect::<heic_rs::Result<Vec<_>>>()?
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let frames = tiles.iter().map(|&t| coded(ctx, t)).collect::<heic_rs::Result<Vec<_>>>()?;
|
||||
heic_rs::grid::compose(&grid, &frames, max_pixels)
|
||||
}
|
||||
None => coded(ctx, id),
|
||||
}
|
||||
}
|
||||
|
||||
let primary = ctx.meta.primary;
|
||||
let props = ctx.props(primary)?;
|
||||
let frame = item(ctx, primary, max_pixels)?;
|
||||
let alpha = ctx.alpha_item(primary)?.map(|a| item(ctx, a, max_pixels)).transpose()?;
|
||||
// `None`: rayon's global pool on native, where heic-rs is built with `parallel`.
|
||||
let image = heic_rs::color::convert(&frame, alpha.as_ref(), nclx, PixelLayout::Rgba8, max_pixels, None)?;
|
||||
heic_rs::transform::apply_all(image, &props.transforms)
|
||||
}
|
||||
|
||||
/// The bytes heic-rs 0.1.4 allocates for the coded pictures of `bytes` it decodes (see
|
||||
/// [`picture_bytes_in`]); `None` when they can't be read.
|
||||
#[cfg(test)]
|
||||
pub(in super::super) fn picture_bytes(bytes: &[u8]) -> Option<u64> {
|
||||
picture_bytes_in(&Context::open(bytes).ok()?)
|
||||
}
|
||||
|
||||
/// The bytes heic-rs 0.1.4 allocates for the coded pictures it decodes: the primary image's,
|
||||
/// or each tile of its grid, and its alpha image's the same way. Each picture is sized by the
|
||||
/// largest of its sequence parameter sets (the size the decoder allocates, rounded up to whole
|
||||
/// 64-sample coding blocks), not by the container, and takes three sets of 16-bit planes: the
|
||||
/// picture, a filtered copy and the frame returned. `None` when an item's sizes can't be read.
|
||||
fn picture_bytes_in(ctx: &Context<'_>) -> Option<u64> {
|
||||
let mut total = 0u64;
|
||||
for item in primary_and_alpha(ctx)? {
|
||||
let coded = match ctx.grid(item).ok()? {
|
||||
Some((_, tiles)) => tiles,
|
||||
None => vec![item],
|
||||
};
|
||||
for id in coded {
|
||||
let props = ctx.props(id).ok()?;
|
||||
// An item without `hvcC` isn't decoded: heic-rs refuses the file.
|
||||
let Some(hvcc) = props.hvcc else { continue };
|
||||
// The slices pick their SPS through the PPS, so the largest one is counted. Every
|
||||
// SPS must be read.
|
||||
let mut largest = None;
|
||||
for nal in hvcc.parameter_sets().into_iter().filter(|nal| nal_type(nal) == Some(SPS)) {
|
||||
let (width, height, chroma) = sps_size(nal)?;
|
||||
let blocks = |n: u64| n.div_ceil(64) * 64;
|
||||
// Bytes a sample position takes in one set of planes: luma and the two chroma
|
||||
// planes.
|
||||
let planes = match chroma {
|
||||
0 => 2,
|
||||
1 => 3,
|
||||
2 => 4,
|
||||
_ => 6,
|
||||
};
|
||||
let picture = blocks(width).checked_mul(blocks(height))?.checked_mul(planes * 3)?;
|
||||
largest = largest.max(Some(picture));
|
||||
}
|
||||
total = total.checked_add(largest?)?;
|
||||
}
|
||||
}
|
||||
Some(total)
|
||||
}
|
||||
|
||||
/// The NAL unit type of an HEVC sequence parameter set.
|
||||
const SPS: u8 = 33;
|
||||
|
||||
/// The type of an HEVC NAL unit, from its header.
|
||||
fn nal_type(nal: &[u8]) -> Option<u8> {
|
||||
nal.first().map(|b| (b >> 1) & 0x3f)
|
||||
}
|
||||
|
||||
/// The NAL unit type of an HEVC picture parameter set.
|
||||
const PPS: u8 = 34;
|
||||
|
||||
/// A NAL unit's payload, without its two-byte header and the emulation prevention bytes (the 03
|
||||
/// of 00 00 03), up to its first 4,096 bytes.
|
||||
fn payload(nal: &[u8]) -> Vec<u8> {
|
||||
let mut rbsp = Vec::with_capacity(256);
|
||||
let mut zeros = 0;
|
||||
for &b in nal.get(2..).unwrap_or_default().iter().take(4096) {
|
||||
if b == 3 && zeros >= 2 {
|
||||
zeros = 0;
|
||||
continue;
|
||||
}
|
||||
zeros = if b == 0 { zeros + 1 } else { 0 };
|
||||
rbsp.push(b);
|
||||
}
|
||||
rbsp
|
||||
}
|
||||
|
||||
/// An SPS NAL unit's [`payload`]; `None` for another NAL unit.
|
||||
fn sps_payload(nal: &[u8]) -> Option<Vec<u8>> {
|
||||
(nal_type(nal) == Some(SPS)).then(|| payload(nal))
|
||||
}
|
||||
|
||||
/// The fields of an SPS (ITU-T H.265 7.3.2.2) up to the picture height:
|
||||
/// `sps_max_sub_layers_minus1`, `sps_seq_parameter_set_id`, the width, the height and
|
||||
/// `chroma_format_idc`.
|
||||
fn sps_head(bits: &mut Bits<'_>) -> Option<(u64, u64, u64, u64, u64)> {
|
||||
// sps_video_parameter_set_id, sps_max_sub_layers_minus1, sps_temporal_id_nesting_flag.
|
||||
bits.skip(4)?;
|
||||
let sub_layers = bits.read(3)?;
|
||||
bits.skip(1)?;
|
||||
// profile_tier_level (7.3.3): the general profile, tier and level, then the sub-layers'.
|
||||
bits.skip(96)?;
|
||||
let mut present = Vec::new();
|
||||
for _ in 0..sub_layers {
|
||||
present.push((bits.read(1)?, bits.read(1)?));
|
||||
}
|
||||
if sub_layers > 0 {
|
||||
bits.skip(2 * (8 - sub_layers as usize))?;
|
||||
}
|
||||
for (profile, level) in present {
|
||||
bits.skip(88 * profile as usize + 8 * level as usize)?;
|
||||
}
|
||||
let id = bits.exp_golomb()?;
|
||||
let chroma = bits.exp_golomb()?;
|
||||
if chroma == 3 {
|
||||
bits.skip(1)?;
|
||||
}
|
||||
let width = bits.exp_golomb()?;
|
||||
let height = bits.exp_golomb()?;
|
||||
Some((sub_layers, id, width, height, chroma))
|
||||
}
|
||||
|
||||
/// The picture width, height and `chroma_format_idc` of an HEVC sequence parameter set NAL
|
||||
/// unit, before its conformance window; `None` for another NAL unit.
|
||||
pub(in super::super) fn sps_size(nal: &[u8]) -> Option<(u64, u64, u64)> {
|
||||
let rbsp = sps_payload(nal)?;
|
||||
let (_, _, width, height, chroma) = sps_head(&mut Bits { data: &rbsp, at: 0 })?;
|
||||
Some((width, height, chroma))
|
||||
}
|
||||
|
||||
/// The video signal type of an HEVC sequence parameter set NAL unit's VUI (ITU-T H.265 E.2.1)
|
||||
/// as an `nclx`: the full-range flag and, when the VUI describes them, the color primaries,
|
||||
/// transfer characteristics and matrix coefficients (otherwise 2, unspecified). `None` when the
|
||||
/// SPS has no VUI, the VUI has no video signal type, or the SPS can't be read that far.
|
||||
pub(in super::super) fn sps_signal(nal: &[u8]) -> Option<Nclx> {
|
||||
let rbsp = sps_payload(nal)?;
|
||||
let bits = &mut Bits { data: &rbsp, at: 0 };
|
||||
let (sub_layers, ..) = sps_head(bits)?;
|
||||
skip_to_vui(bits, sub_layers)?;
|
||||
// vui_parameters_present_flag, then aspect_ratio_info_present_flag (an Extended_SAR
|
||||
// aspect_ratio_idc of 255 adds its 32-bit ratio) and overscan_info_present_flag.
|
||||
if bits.read(1)? == 0 {
|
||||
return None;
|
||||
}
|
||||
if bits.read(1)? == 1 && bits.read(8)? == 255 {
|
||||
bits.skip(32)?;
|
||||
}
|
||||
if bits.read(1)? == 1 {
|
||||
bits.skip(1)?;
|
||||
}
|
||||
// video_signal_type_present_flag: video_format, video_full_range_flag and the color
|
||||
// description.
|
||||
if bits.read(1)? == 0 {
|
||||
return None;
|
||||
}
|
||||
bits.skip(3)?;
|
||||
let range = if bits.read(1)? == 1 { Range::Full } else { Range::Limited };
|
||||
let (primaries, transfer, matrix) = if bits.read(1)? == 1 { (bits.read(8)?, bits.read(8)?, bits.read(8)?) } else { (2, 2, 2) };
|
||||
let code = |v: u64| u16::try_from(v).ok();
|
||||
let matrix_code = code(matrix)?;
|
||||
Some(Nclx { primaries: code(primaries)?, transfer: code(transfer)?, matrix: MatrixCoefficients::from_code(matrix_code), matrix_code, range })
|
||||
}
|
||||
|
||||
/// Skips the fields of an SPS after [`sps_head`], up to `vui_parameters_present_flag`.
|
||||
fn skip_to_vui(bits: &mut Bits<'_>, sub_layers: u64) -> Option<()> {
|
||||
// conformance_window_flag and its four offsets.
|
||||
if bits.read(1)? == 1 {
|
||||
for _ in 0..4 {
|
||||
bits.exp_golomb()?;
|
||||
}
|
||||
}
|
||||
// bit_depth_luma_minus8, bit_depth_chroma_minus8.
|
||||
bits.exp_golomb()?;
|
||||
bits.exp_golomb()?;
|
||||
let poc_bits = bits.exp_golomb()?.checked_add(4).filter(|&n| n <= 16)?;
|
||||
// sps_sub_layer_ordering_info_present_flag, then three values for each sub-layer given.
|
||||
let ordered = if bits.read(1)? == 1 { sub_layers + 1 } else { 1 };
|
||||
for _ in 0..ordered * 3 {
|
||||
bits.exp_golomb()?;
|
||||
}
|
||||
// The coding and transform block sizes and the transform hierarchy depths.
|
||||
for _ in 0..6 {
|
||||
bits.exp_golomb()?;
|
||||
}
|
||||
// scaling_list_enabled_flag, sps_scaling_list_data_present_flag.
|
||||
if bits.read(1)? == 1 && bits.read(1)? == 1 {
|
||||
skip_scaling_lists(bits)?;
|
||||
}
|
||||
// amp_enabled_flag, sample_adaptive_offset_enabled_flag.
|
||||
bits.skip(2)?;
|
||||
// pcm_enabled_flag: the PCM sample depths, block sizes and loop filter flag.
|
||||
if bits.read(1)? == 1 {
|
||||
bits.skip(8)?;
|
||||
bits.exp_golomb()?;
|
||||
bits.exp_golomb()?;
|
||||
bits.skip(1)?;
|
||||
}
|
||||
skip_reference_picture_sets(bits)?;
|
||||
// long_term_ref_pics_present_flag: each picture's POC bits and used flag.
|
||||
if bits.read(1)? == 1 {
|
||||
let count = bits.exp_golomb()?;
|
||||
if count > 32 {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..count {
|
||||
bits.skip(poc_bits as usize + 1)?;
|
||||
}
|
||||
}
|
||||
// sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag.
|
||||
bits.skip(2)
|
||||
}
|
||||
|
||||
/// Skips `scaling_list_data()` (ITU-T H.265 7.3.4).
|
||||
fn skip_scaling_lists(bits: &mut Bits<'_>) -> Option<()> {
|
||||
for size in 0..4 {
|
||||
// The 32 × 32 lists are given for matrices 0 and 3 only.
|
||||
for _ in 0..if size == 3 { 2 } else { 6 } {
|
||||
if bits.read(1)? == 0 {
|
||||
// scaling_list_pred_matrix_id_delta.
|
||||
bits.exp_golomb()?;
|
||||
} else {
|
||||
// scaling_list_dc_coef_minus8, then each scaling_list_delta_coef (se(v) codes,
|
||||
// as long as ue(v) codes).
|
||||
if size > 1 {
|
||||
bits.exp_golomb()?;
|
||||
}
|
||||
for _ in 0..if size == 0 { 16 } else { 64 } {
|
||||
bits.exp_golomb()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Skips `num_short_term_ref_pic_sets` and each `st_ref_pic_set()` (ITU-T H.265 7.3.7) of an
|
||||
/// SPS. A set predicted from the one before it has one or two flags for each of that set's
|
||||
/// pictures and one more.
|
||||
fn skip_reference_picture_sets(bits: &mut Bits<'_>) -> Option<()> {
|
||||
let sets = bits.exp_golomb()?;
|
||||
if sets > 64 {
|
||||
return None;
|
||||
}
|
||||
// NumDeltaPocs of each set read so far.
|
||||
let mut pictures: Vec<u64> = Vec::new();
|
||||
for index in 0..sets {
|
||||
let predicted = index != 0 && bits.read(1)? == 1;
|
||||
let count = if predicted {
|
||||
// delta_rps_sign, abs_delta_rps_minus1.
|
||||
bits.skip(1)?;
|
||||
bits.exp_golomb()?;
|
||||
let mut count = 0;
|
||||
for _ in 0..=*pictures.last()? {
|
||||
// used_by_curr_pic_flag, and use_delta_flag when it is 0.
|
||||
if bits.read(1)? == 1 || bits.read(1)? == 1 {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
} else {
|
||||
let (negative, positive) = (bits.exp_golomb()?, bits.exp_golomb()?);
|
||||
if negative > 16 || positive > 16 {
|
||||
return None;
|
||||
}
|
||||
// Each picture's delta_poc_s0_minus1 or delta_poc_s1_minus1 and its used flag.
|
||||
for _ in 0..negative + positive {
|
||||
bits.exp_golomb()?;
|
||||
bits.skip(1)?;
|
||||
}
|
||||
negative + positive
|
||||
};
|
||||
pictures.push(count);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// A big-endian bit reader over an RBSP.
|
||||
struct Bits<'a> {
|
||||
data: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Bits<'_> {
|
||||
fn bit(&mut self) -> Option<u64> {
|
||||
let byte = self.data.get(self.at / 8)?;
|
||||
let bit = (byte >> (7 - self.at % 8)) & 1;
|
||||
self.at += 1;
|
||||
Some(u64::from(bit))
|
||||
}
|
||||
|
||||
fn read(&mut self, n: u32) -> Option<u64> {
|
||||
(0..n).try_fold(0u64, |v, _| Some(v << 1 | self.bit()?))
|
||||
}
|
||||
|
||||
fn skip(&mut self, n: usize) -> Option<()> {
|
||||
self.at = self.at.checked_add(n)?;
|
||||
(self.at <= self.data.len() * 8).then_some(())
|
||||
}
|
||||
|
||||
/// An unsigned Exp-Golomb code, ue(v), of at most 32 leading zeros.
|
||||
fn exp_golomb(&mut self) -> Option<u64> {
|
||||
let mut zeros = 0;
|
||||
while self.bit()? == 0 {
|
||||
zeros += 1;
|
||||
if zeros > 32 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some((1u64 << zeros) - 1 + self.read(zeros)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// `nclx` color primaries for Display P3 (SMPTE EG 432-1) and transfer characteristics for
|
||||
/// the sRGB curve (IEC 61966-2-1), ITU-T H.273.
|
||||
const P3_PRIMARIES: u16 = 12;
|
||||
const SRGB_TRANSFER: u16 = 13;
|
||||
|
||||
/// The profile the decoded RGB values are in when it isn't sRGB: the primary item's RGB ICC
|
||||
/// profile, else Display P3 when its `nclx` names P3 primaries with the sRGB curve. A grid
|
||||
/// without its own `colr` takes its first tile's, as cameras write it on the tiles. A profile
|
||||
/// that can't be read, or isn't RGB, is left out and the values are read as sRGB. Without any
|
||||
/// `colr`, the HEVC stream's color description ([`stream_nclx`]) is read the same way.
|
||||
fn source_profile(ctx: &Context<'_>) -> Option<vectorcraft_color::cms::IccProfile> {
|
||||
use vectorcraft_color::cms::{self, IccProfile, ProfileKind};
|
||||
|
||||
let id = ctx.meta.primary;
|
||||
let own = ctx.props(id).ok()?;
|
||||
let described = |p: &heic_rs::props::ItemProps<'_>| p.icc.is_some() || p.nclx.is_some();
|
||||
let tile = || ctx.grid(id).ok().flatten().and_then(|(_, tiles)| tiles.first().and_then(|&t| ctx.props(t).ok())).filter(described);
|
||||
let props = if described(&own) { Some(own) } else { tile() };
|
||||
if let Some(icc) = props.as_ref().and_then(|p| p.icc) {
|
||||
return IccProfile::from_bytes(None, icc).ok().filter(|p| p.kind == ProfileKind::Rgb);
|
||||
}
|
||||
let nclx = match props {
|
||||
Some(props) => props.nclx?,
|
||||
None => stream_nclx(ctx)?,
|
||||
};
|
||||
(nclx.primaries == P3_PRIMARIES && nclx.transfer == SRGB_TRANSFER).then(|| cms::icc::builtin_rgb(cms::DISPLAY_P3)).flatten()
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub struct Loaded {
|
||||
/// A PDF, or a `.ai` or `.ait` that holds a PDF, read through the editor's own copy of its art
|
||||
/// that it carries (its layers), not from its PDF part alone.
|
||||
pub editing_data: bool,
|
||||
/// Whether the native source declared a PDF; other formats carry no native save preference.
|
||||
pub native_pdf_compatible: Option<bool>,
|
||||
}
|
||||
|
||||
impl Loaded {
|
||||
@@ -103,6 +105,9 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> {
|
||||
if super::jp2read::is_jpeg2000(bytes) {
|
||||
return format("jpeg2000");
|
||||
}
|
||||
if super::heifread::is_heif(bytes) {
|
||||
return format("heif");
|
||||
}
|
||||
if let Some(f) = image::guess_format(bytes).ok().and_then(image_format) {
|
||||
return Some(f);
|
||||
}
|
||||
@@ -338,6 +343,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let mut converted = false;
|
||||
let mut preview_only = false;
|
||||
let mut editing_data = false;
|
||||
let mut native_pdf_compatible = None;
|
||||
let (mut doc, mut warnings, restored) = match format.id {
|
||||
// EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read.
|
||||
_ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => {
|
||||
@@ -350,6 +356,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
"vectorcraft" | "template" => {
|
||||
let (d, info, warnings) = native_file(bytes)?;
|
||||
native_pdf_compatible = Some(info.pdf_compatible);
|
||||
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
|
||||
(d, warnings, false)
|
||||
}
|
||||
@@ -475,11 +482,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
}
|
||||
// Threaded type read from a file flows through its frames (the threaded type of a restored
|
||||
// document keeps its text as saved), and every frame of a thread takes its first frame's
|
||||
// Optical Margin Alignment setting.
|
||||
// Optical Margin Alignment setting and writing direction. When that changes the direction of a
|
||||
// frame of a restored document, the story flows through that frame's thread again. Threaded
|
||||
// frames keep their size: Auto Size is off for them.
|
||||
if !doc.text_threads.is_empty() && !restored {
|
||||
crate::cmd::threads::reflow(&Document::new(1.0, 1.0), &mut doc);
|
||||
} else if !doc.text_threads.is_empty() {
|
||||
crate::cmd::threads::keep_frame_sizes(&mut doc);
|
||||
crate::cmd::threads::share_optical_margin(&mut doc);
|
||||
crate::cmd::threads::share_orientation(&mut doc);
|
||||
// A frame whose first paragraph continues from the frame before draws it without the
|
||||
// paragraph's first-line indent and list marker.
|
||||
crate::cmd::threads::mark_continued(&mut doc);
|
||||
@@ -493,7 +504,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
doc.title = title;
|
||||
}
|
||||
warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes)));
|
||||
Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data })
|
||||
Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data, native_pdf_compatible })
|
||||
}
|
||||
|
||||
/// Import SVG text, reading the files its images link to (relative links from `folder`, the SVG's
|
||||
@@ -586,7 +597,7 @@ pub fn open_template(s: &mut Session, name: &str, bytes: &[u8], path: Option<&st
|
||||
/// Make a loaded file the new active document; `links` is what became of its linked files, and
|
||||
/// `opts` are the options it was read with.
|
||||
fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<String>, opts: &LoadOptions, as_template: bool) -> Result<Value> {
|
||||
let Loaded { mut doc, format, warnings, restored, converted, .. } = loaded.with_grid_prefs(&s.prefs);
|
||||
let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = loaded.with_grid_prefs(&s.prefs);
|
||||
// EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing
|
||||
// fallbacks must ask before overwriting the richer source they could not fully read.
|
||||
let losses: Vec<String> = warnings
|
||||
@@ -623,6 +634,9 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
let converted = saves_back && converted && s.prefs.append_converted;
|
||||
let index = s.add_document(doc, path);
|
||||
let st = s.doc_mut()?;
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
st.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
if saves_back {
|
||||
st.format = format.id;
|
||||
// An SVG that reopened as the full document saves as one again: Save keeps Preserve
|
||||
@@ -722,6 +736,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// [`super::pcxread::decode`], which refuses an image past [`MAX_RASTER_ALLOC`] before decoding.
|
||||
/// A Pixar picture file is recognized by its magic number ([`super::pxrread::is_pxr`]) and read by
|
||||
/// [`super::pxrread::decode`], which does the same.
|
||||
/// A HEIC or HEIF file is recognized by its `ftyp` brands ([`super::heifread::is_heif`]) and read
|
||||
/// by [`super::heifread::decode`], which does the same.
|
||||
/// A Targa file, which starts with no signature, is recognized by its header
|
||||
/// ([`super::tgaread::is_targa`]) and becomes RGBA with the transparency it stores
|
||||
/// ([`super::tgaread::fix_alpha`]). An image stored as PNG whose decoded samples, or whose pixels
|
||||
@@ -740,6 +756,11 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
|
||||
if super::jp2read::is_jpeg2000(bytes) {
|
||||
return as_png(super::jp2read::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
if super::heifread::is_heif(bytes) {
|
||||
// The EXIF resolution describes the stored pixels; a quarter turn swaps its axes.
|
||||
let ppi = ppi.map(|(x, y)| if super::heifread::quarter_turned(bytes) { (y, x) } else { (x, y) });
|
||||
return as_png(super::heifread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
if super::pxrread::is_pxr(bytes) {
|
||||
return as_png(super::pxrread::decode(bytes, MAX_RASTER_ALLOC).map_err(err)?, ppi);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
//! 3D objects as mesh files, for a 3D asset of Window › Asset Export (`assets.export3D`): OBJ with
|
||||
//! its MTL materials, glTF 2.0 (one `.gltf` file, its buffer embedded as a data URI), USDA and
|
||||
//! USDZ (the USDA layer in an uncompressed ZIP, its data on a 64-byte boundary).
|
||||
//!
|
||||
//! Each solid of the object ([`vectorcraft_render::effects::three_d_meshes`]) is its own mesh, with a
|
||||
//! material in the color it is painted (solids of one color share it). Positions are y up and
|
||||
//! about the point the object turns about: in points in OBJ and USD (whose layer says how many
|
||||
//! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear,
|
||||
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
|
||||
//! an open solid or a turned plane is seen from both sides.
|
||||
//!
|
||||
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
|
||||
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects::SolidMesh;
|
||||
|
||||
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
|
||||
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
|
||||
/// The format a new 3D asset exports to.
|
||||
pub const DEFAULT_FORMAT_3D: &str = "usda";
|
||||
/// The meters in a point (1/72 inch).
|
||||
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
|
||||
|
||||
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
|
||||
pub fn format_3d_label(format: &str) -> &'static str {
|
||||
match format {
|
||||
"usdz" => "USDZ",
|
||||
"gltf" => "glTF",
|
||||
"obj" => "OBJ",
|
||||
_ => "USDA",
|
||||
}
|
||||
}
|
||||
|
||||
/// `stem` as an OBJ file name: whitespace and `#` become `_`, so the `mtllib` line names the MTL
|
||||
/// file as one word.
|
||||
fn obj_stem(stem: &str) -> String {
|
||||
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
|
||||
}
|
||||
|
||||
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
|
||||
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
|
||||
match format {
|
||||
"obj" => {
|
||||
let stem = obj_stem(stem);
|
||||
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
|
||||
}
|
||||
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
|
||||
_ => {
|
||||
let key = "format";
|
||||
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
|
||||
/// OBJ with its MTL after it.
|
||||
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let names = mesh_file_names(stem, format)?;
|
||||
let bytes = match format {
|
||||
"obj" => {
|
||||
let (obj, mtl) = obj(&obj_stem(stem), parts);
|
||||
vec![obj.into_bytes(), mtl.into_bytes()]
|
||||
}
|
||||
"gltf" => vec![gltf(stem, parts).into_bytes()],
|
||||
"usda" => vec![usda(stem, parts).into_bytes()],
|
||||
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
|
||||
};
|
||||
Ok(names.into_iter().zip(bytes).collect())
|
||||
}
|
||||
|
||||
/// The distinct colors of `parts` in order, and each part's index among them.
|
||||
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
|
||||
let mut colors: Vec<[f32; 4]> = vec![];
|
||||
let index = parts
|
||||
.iter()
|
||||
.map(|p| {
|
||||
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
|
||||
colors.push(p.color);
|
||||
colors.len() - 1
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(colors, index)
|
||||
}
|
||||
|
||||
/// An sRGB channel (0..1) as linear light.
|
||||
fn linear(c: f32) -> f32 {
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// A number as text: the shortest decimal that reads back as the same value.
|
||||
fn num(v: f64) -> String {
|
||||
format!("{v}")
|
||||
}
|
||||
|
||||
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
|
||||
let (colors, material) = materials(parts);
|
||||
let mut o = String::new();
|
||||
let _ = writeln!(o, "mtllib {stem}.mtl");
|
||||
let _ = writeln!(o, "o {stem}");
|
||||
for p in parts {
|
||||
for v in &p.mesh.positions {
|
||||
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
|
||||
}
|
||||
}
|
||||
for p in parts {
|
||||
for n in &p.mesh.normals {
|
||||
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
|
||||
}
|
||||
}
|
||||
let mut base = 1usize;
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let _ = writeln!(o, "g Solid_{}", k + 1);
|
||||
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
|
||||
for t in &p.mesh.triangles {
|
||||
let [a, b, c] = t.map(|i| i as usize + base);
|
||||
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
|
||||
}
|
||||
base += p.mesh.positions.len();
|
||||
}
|
||||
let mut m = String::new();
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
let _ = writeln!(m, "newmtl Material_{}", k + 1);
|
||||
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
|
||||
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
|
||||
let _ = writeln!(m, "illum 1");
|
||||
}
|
||||
(o, m)
|
||||
}
|
||||
|
||||
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
let mut buffer: Vec<u8> = vec![];
|
||||
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
|
||||
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
|
||||
views.push(json!({ "buffer": 0, "byteOffset": buffer.len(), "byteLength": bytes.len(), "target": target }));
|
||||
buffer.extend(bytes);
|
||||
views.len() - 1
|
||||
};
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let floats = |v: &[[f64; 3]], scale: f64| v.iter().flatten().flat_map(|x| ((x * scale) as f32).to_le_bytes()).collect::<Vec<u8>>();
|
||||
let (lo, hi) = p.mesh.bounds().unwrap_or_default();
|
||||
let positions = view(&mut buffer, floats(&p.mesh.positions, METERS_PER_POINT), 34962);
|
||||
let normals = view(&mut buffer, floats(&p.mesh.normals, 1.0), 34962);
|
||||
let indices = view(&mut buffer, p.mesh.triangles.iter().flatten().flat_map(|i| i.to_le_bytes()).collect(), 34963);
|
||||
let count = p.mesh.positions.len();
|
||||
let at = accessors.len();
|
||||
accessors.push(json!({
|
||||
"bufferView": positions, "componentType": 5126, "count": count, "type": "VEC3",
|
||||
"min": lo.map(|v| (v * METERS_PER_POINT) as f32), "max": hi.map(|v| (v * METERS_PER_POINT) as f32),
|
||||
}));
|
||||
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
|
||||
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
|
||||
primitives.push(json!({
|
||||
"attributes": { "POSITION": at, "NORMAL": at + 1 },
|
||||
"indices": at + 2,
|
||||
"material": material.get(k).copied().unwrap_or(0),
|
||||
}));
|
||||
}
|
||||
let materials: Vec<Value> = colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(k, c)| {
|
||||
let mut m = json!({
|
||||
"name": format!("Material_{}", k + 1),
|
||||
"pbrMetallicRoughness": {
|
||||
"baseColorFactor": [linear(c[0]), linear(c[1]), linear(c[2]), c[3]],
|
||||
"metallicFactor": 0.0,
|
||||
"roughnessFactor": 1.0,
|
||||
},
|
||||
"doubleSided": true,
|
||||
});
|
||||
if c[3] < 1.0 {
|
||||
m["alphaMode"] = json!("BLEND");
|
||||
}
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
let doc = json!({
|
||||
"asset": { "version": "2.0", "generator": "VectorCraft" },
|
||||
"scene": 0,
|
||||
"scenes": [{ "nodes": [0] }],
|
||||
"nodes": [{ "name": stem, "mesh": 0 }],
|
||||
"meshes": [{ "name": stem, "primitives": primitives }],
|
||||
"materials": materials,
|
||||
"buffers": [{
|
||||
"byteLength": buffer.len(),
|
||||
"uri": format!("data:application/octet-stream;base64,{}", vectorcraft_format::base64_encode(&buffer)),
|
||||
}],
|
||||
"bufferViews": views,
|
||||
"accessors": accessors,
|
||||
});
|
||||
serde_json::to_string_pretty(&doc).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `name` as a USD prim name: letters, digits and `_`, not starting with a digit.
|
||||
fn prim_name(name: &str) -> String {
|
||||
let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
out.insert(0, '_');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
|
||||
let (colors, material) = materials(parts);
|
||||
let root = prim_name(stem);
|
||||
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
|
||||
let list = |items: Vec<String>| items.join(", ");
|
||||
let mut u = String::new();
|
||||
let _ = writeln!(u, "#usda 1.0");
|
||||
let _ = writeln!(u, "(\n defaultPrim = \"{root}\"\n metersPerUnit = {}\n upAxis = \"Y\"\n)\n", METERS_PER_POINT);
|
||||
let _ = writeln!(u, "def Xform \"{root}\"\n{{");
|
||||
for (k, p) in parts.iter().enumerate() {
|
||||
let (lo, hi) = p.mesh.bounds().unwrap_or_default();
|
||||
let m = material.get(k).copied().unwrap_or(0) + 1;
|
||||
let _ = writeln!(u, " def Mesh \"Solid_{}\" (\n prepend apiSchemas = [\"MaterialBindingAPI\"]\n )\n {{", k + 1);
|
||||
let _ = writeln!(u, " uniform bool doubleSided = 1");
|
||||
let _ = writeln!(u, " float3[] extent = [{}, {}]", triple(lo), triple(hi));
|
||||
let _ = writeln!(u, " int[] faceVertexCounts = [{}]", list(vec!["3".to_string(); p.mesh.triangles.len()]));
|
||||
let _ = writeln!(u, " int[] faceVertexIndices = [{}]", list(p.mesh.triangles.iter().flatten().map(u32::to_string).collect()));
|
||||
let _ = writeln!(u, " rel material:binding = </{root}/Materials/Material_{m}>");
|
||||
let _ = writeln!(
|
||||
u,
|
||||
" normal3f[] normals = [{}] (\n interpolation = \"vertex\"\n )",
|
||||
list(p.mesh.normals.iter().map(|n| triple(*n)).collect())
|
||||
);
|
||||
let _ = writeln!(u, " point3f[] points = [{}]", list(p.mesh.positions.iter().map(|v| triple(*v)).collect()));
|
||||
let c = p.color;
|
||||
let _ = writeln!(
|
||||
u,
|
||||
" color3f[] primvars:displayColor = [({}, {}, {})] (\n interpolation = \"constant\"\n )",
|
||||
linear(c[0]),
|
||||
linear(c[1]),
|
||||
linear(c[2])
|
||||
);
|
||||
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
|
||||
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
|
||||
}
|
||||
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
|
||||
for (k, c) in colors.iter().enumerate() {
|
||||
let m = k + 1;
|
||||
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
|
||||
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
|
||||
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
|
||||
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
|
||||
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
|
||||
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
|
||||
let _ = writeln!(u, " float inputs:roughness = 1");
|
||||
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
|
||||
}
|
||||
let _ = writeln!(u, " }}\n}}");
|
||||
u
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,130 @@
|
||||
use serde_json::Value;
|
||||
use vectorcraft_render::effects::{Mesh, SolidMesh};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A 10 × 10 square facing the viewer: two triangles, each with corners of its own.
|
||||
fn square(color: [f32; 4]) -> SolidMesh {
|
||||
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
|
||||
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
|
||||
SolidMesh { mesh, color }
|
||||
}
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 0.5];
|
||||
|
||||
fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
|
||||
let (_, bytes) = files.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no {name}"));
|
||||
String::from_utf8(bytes.clone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_numbers_corners_across_solids_and_names_its_materials() {
|
||||
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
|
||||
let obj = text(&files, "Box.obj");
|
||||
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18);
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18);
|
||||
// The third solid's last triangle uses corners 13 to 18; red solids share Material_1.
|
||||
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18"));
|
||||
assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::<Vec<_>>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]);
|
||||
let mtl = text(&files, "Box.mtl");
|
||||
assert_eq!(mtl.matches("newmtl").count(), 2);
|
||||
assert!(mtl.contains("newmtl Material_2\nKd 0 0 1\nd 0.5\n"), "{mtl}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
|
||||
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
|
||||
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
|
||||
assert_eq!(g["asset"]["version"], "2.0");
|
||||
let uri = g["buffers"][0]["uri"].as_str().unwrap();
|
||||
let data = vectorcraft_format::base64_decode(uri.strip_prefix("data:application/octet-stream;base64,").unwrap()).unwrap();
|
||||
assert_eq!(g["buffers"][0]["byteLength"].as_u64(), Some(data.len() as u64));
|
||||
for v in g["bufferViews"].as_array().unwrap() {
|
||||
assert!(v["byteOffset"].as_u64().unwrap() + v["byteLength"].as_u64().unwrap() <= data.len() as u64);
|
||||
assert_eq!(v["byteOffset"].as_u64().unwrap() % 4, 0);
|
||||
}
|
||||
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
|
||||
assert_eq!(prims.len(), 2);
|
||||
assert_eq!((prims[0]["material"].as_u64(), prims[1]["material"].as_u64()), (Some(0), Some(1)));
|
||||
// Positions are meters: the 10 pt square is 10/72 inch across.
|
||||
let pos = &g["accessors"][prims[0]["attributes"]["POSITION"].as_u64().unwrap() as usize];
|
||||
let width = pos["max"][0].as_f64().unwrap() - pos["min"][0].as_f64().unwrap();
|
||||
assert!((width - 10.0 * 0.0254 / 72.0).abs() < 1e-7, "{width}");
|
||||
let index = &g["accessors"][prims[0]["indices"].as_u64().unwrap() as usize];
|
||||
assert_eq!((index["componentType"].as_u64(), index["count"].as_u64()), (Some(5125), Some(6)));
|
||||
// Translucent paint blends; colors are linear.
|
||||
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
|
||||
assert!(g["materials"][0].get("alphaMode").is_none());
|
||||
assert_eq!(g["materials"][0]["doubleSided"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
|
||||
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
|
||||
let u = text(&files, "My Box.usda");
|
||||
assert!(u.starts_with("#usda 1.0\n"));
|
||||
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
|
||||
assert!(u.contains(&format!("metersPerUnit = {}", 0.0254 / 72.0)));
|
||||
assert_eq!(u.matches("def Mesh").count(), 2);
|
||||
assert_eq!(u.matches("def Material").count(), 2);
|
||||
assert!(u.contains("int[] faceVertexCounts = [3, 3]"));
|
||||
assert!(u.contains("rel material:binding = </My_Box/Materials/Material_2>"));
|
||||
// sRGB 0.5 is about 0.214 linear.
|
||||
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
|
||||
assert_eq!(u.matches('{').count(), u.matches('}').count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
|
||||
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
|
||||
let (name, zip) = &files[0];
|
||||
assert_eq!(name, "Box.usdz");
|
||||
// The local header: 30 bytes, the name, then the extra field.
|
||||
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
|
||||
assert_eq!(&zip[..4], &[0x50, 0x4b, 0x03, 0x04]);
|
||||
assert_eq!(u16_at(8), 0, "stored, not deflated");
|
||||
let start = 30 + u16_at(26) + u16_at(28);
|
||||
assert_eq!(start % 64, 0);
|
||||
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
|
||||
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
|
||||
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
|
||||
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
|
||||
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
|
||||
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
|
||||
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
|
||||
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
|
||||
let mut part = square(RED);
|
||||
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
|
||||
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
|
||||
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
|
||||
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
|
||||
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
|
||||
assert!(usda.contains("(20000001, 0, 0)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_format_is_refused() {
|
||||
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
|
||||
assert!(mesh_file_names("Box", "").is_err());
|
||||
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prim_names_are_usd_identifiers() {
|
||||
assert_eq!(prim_name("Logo 2"), "Logo_2");
|
||||
assert_eq!(prim_name("3D"), "_3D");
|
||||
assert_eq!(prim_name(""), "_");
|
||||
assert_eq!(prim_name("é/x"), "__x");
|
||||
}
|
||||
@@ -48,7 +48,7 @@ pub const OPTIONS: &[FormatOption] = &[
|
||||
FormatOption {
|
||||
name: "pdfCompatible",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
default: "true",
|
||||
description: "also carry a PDF of every artboard, for apps that read PDF (a larger file)",
|
||||
},
|
||||
];
|
||||
@@ -109,7 +109,7 @@ pub const AI_OPTIONS: &[FormatOption] = &[
|
||||
name: "editingData",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, and linked images as placed files with a preview, with type, other patterns, symbols, other clipping objects and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
|
||||
description: "also carry an editing copy of the artwork in the form other apps that open .ai files read: layers and sublayers, groups, compound paths, paths, fills and strokes, colors, linear and radial gradients, patterns on a grid of tiles, swatches, artboards and which one is active, the transparency of objects and layers, objects' opacity masks, clipping groups and layers clipped by a path, embedded images with their pixels, linked images as placed files with a preview, point type, area type and type on a path as text, and symbols and their instances, with other type, other patterns, other clipping objects, other symbol instances and live objects as plain filled and stroked paths, freeform gradients, gradients along or across a stroke and gradients of more than 256 stops as their average color, gradients that dither or mix perceptually as classic ones, and gradient stops linked to global process colors as their colors (written only with every artboard, as Preserve Editing is)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "aiVersion",
|
||||
@@ -146,7 +146,7 @@ struct NativeOptions {
|
||||
precision: Option<Value>,
|
||||
include_linked: bool,
|
||||
embed_profiles: Option<bool>,
|
||||
pdf_compatible: bool,
|
||||
pdf_compatible: Option<bool>,
|
||||
}
|
||||
|
||||
/// What [`save_options`] leaves to [`encode`] (rendering and encoding take time).
|
||||
@@ -171,7 +171,9 @@ pub(super) fn save_options(cmd: &str, f: &Format, doc: &Document, p: &Value) ->
|
||||
so.profiles = embedded_profiles(doc);
|
||||
}
|
||||
so.check().map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok((so, Extras { preview: o.preview, pdf: o.pdf_compatible }))
|
||||
let pdf = o.pdf_compatible.unwrap_or(true);
|
||||
so.pdf_compatible = Some(pdf);
|
||||
Ok((so, Extras { preview: o.preview, pdf }))
|
||||
}
|
||||
|
||||
/// The `precision` option `v`: a whole number of decimal places, 0 to
|
||||
@@ -213,9 +215,11 @@ pub(super) fn encode_to(cmd: &str, f: &Format, doc: &Document, p: &Value, w: imp
|
||||
if extras.preview {
|
||||
so.preview = preview_png(&drawn)?;
|
||||
}
|
||||
if extras.pdf {
|
||||
// Every artboard as PDF pages (no editing data: the file is the native document).
|
||||
so.pdf = Some(super::pdf::encode(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }))?.0);
|
||||
if extras.pdf && !drawn.artboards.is_empty() {
|
||||
// Every artboard as PDF pages (no editing data: the file is the native document), dated by
|
||||
// the document's File Info, so the same document and dates give the same bytes.
|
||||
let at = drawn.metadata.modified.or(drawn.metadata.created);
|
||||
so.pdf = Some(super::pdf::encode_at(cmd, &drawn, &json!({ "range": "all", "preserveEditing": false }), at)?.0);
|
||||
}
|
||||
drop(drawn);
|
||||
let native = match full {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,7 +7,7 @@ use vectorcraft_doc::{ColorMode, Document};
|
||||
use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs};
|
||||
|
||||
use super::super::colormgmt::Grays;
|
||||
use super::super::{Result, Session, bad, f64_or, parse_range, str_param};
|
||||
use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param};
|
||||
use super::{err, source};
|
||||
|
||||
/// The `document.open` options besides the file. The PDF ones (pages, box, password, text,
|
||||
@@ -75,16 +75,17 @@ impl LoadOptions {
|
||||
Some(Value::Number(n)) => Some(n.to_string()),
|
||||
Some(v) => return Err(bad(cmd, format!("pages must be a range such as \"2-3\" or a page number, not {v}"))),
|
||||
};
|
||||
let crop = choice(cmd, "cropTo", str_param(p, "cropTo").or_else(|| str_param(p, "crop")))?;
|
||||
let password = str_param(p, "password").filter(|s| !s.is_empty()).map(str::to_string);
|
||||
let color_mode = match str_param(p, "colorMode").map(str::to_ascii_lowercase).as_deref() {
|
||||
let (crop_to, crop_alias) = (text_param(p, "cropTo", cmd)?, text_param(p, "crop", cmd)?);
|
||||
let crop = choice(cmd, "cropTo", crop_to.or(crop_alias))?;
|
||||
let password = text_param(p, "password", cmd)?.filter(|s| !s.is_empty()).map(str::to_string);
|
||||
let color_mode = match text_param(p, "colorMode", cmd)?.map(str::to_ascii_lowercase).as_deref() {
|
||||
None => None,
|
||||
Some("rgb") => Some(ColorMode::Rgb),
|
||||
Some("cmyk") => Some(ColorMode::Cmyk),
|
||||
Some(m) => return Err(bad(cmd, format!("colorMode must be rgb or cmyk, not `{m}`"))),
|
||||
};
|
||||
let grays = Grays::param(cmd, p)?;
|
||||
let text_as = choice(cmd, "textAs", str_param(p, "textAs"))?;
|
||||
let text_as = choice(cmd, "textAs", text_param(p, "textAs", cmd)?)?;
|
||||
let layers = match p.get("layers").filter(|v| !v.is_null()) {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
|
||||
@@ -172,6 +173,7 @@ const INFO: &str = "document.pdfInfo";
|
||||
pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bytes = source(p, INFO)?.bytes;
|
||||
let o = LoadOptions::from_params(INFO, p)?;
|
||||
check_numbers(p, &["thumbnailSize"], INFO)?;
|
||||
// Programs whose header is only `%!` are PostScript too, as `clipboard.importEps` reads them.
|
||||
if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) {
|
||||
return postscript_info(&bytes, p);
|
||||
@@ -229,7 +231,7 @@ fn postscript_info(bytes: &[u8], p: &Value) -> Result<Value> {
|
||||
/// A PNG of `doc`'s first artboard, `thumbnailSize` px (default 160, from 16 to 1024) on its longer
|
||||
/// side, base64.
|
||||
fn thumbnail(doc: &Document, p: &Value) -> Result<String> {
|
||||
let size = f64_or(p, "thumbnailSize", 160.0).clamp(16.0, 1024.0);
|
||||
let size = number_or(p, "thumbnailSize", 160.0, INFO)?.clamp(16.0, 1024.0);
|
||||
let r = doc.artboards.first().map(|a| a.rect).ok_or_else(|| err("the page has no area"))?;
|
||||
let png = super::encode(doc, "png", &json!({"scale": size / r.width().max(r.height()).max(1.0)}))?;
|
||||
Ok(vectorcraft_format::base64_encode(&png))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Image resolution metadata (pixels per inch): PNG `pHYs`, JPEG JFIF density or EXIF, TIFF and
|
||||
//! WebP EXIF resolution tags, BMP pixels per metre, a Photoshop document's ResolutionInfo, a PCX
|
||||
//! header's HDpi and VDpi, or JP2 capture and display resolution boxes. Place
|
||||
//! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF
|
||||
//! resolution tags. Place
|
||||
//! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it
|
||||
//! as a `pHYs` chunk.
|
||||
|
||||
@@ -26,6 +27,8 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
super::pcxread::resolution(bytes)
|
||||
} else if super::jp2read::is_jpeg2000(bytes) {
|
||||
jp2(bytes)
|
||||
} else if super::heifread::is_heif(bytes) {
|
||||
super::heifread::with_exif(bytes, tiff)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use vectorcraft_doc::cancel::{self, CancelToken, ProgressSink};
|
||||
|
||||
@@ -26,6 +26,9 @@ pub struct Progress {
|
||||
total: AtomicU64,
|
||||
/// The steps are files (Export for Screens), not artboards.
|
||||
files: bool,
|
||||
/// The last report came from a plug-in ([`vectorcraft_plugins::host::PROGRESS_STEP`]): its
|
||||
/// steps are its own, shown as a share of the work.
|
||||
share: AtomicBool,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
@@ -43,6 +46,11 @@ impl Progress {
|
||||
self.files
|
||||
}
|
||||
|
||||
/// Are the steps a plug-in's own, which only a share of the work done describes?
|
||||
pub fn counts_share(&self) -> bool {
|
||||
self.share.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// `(steps done, steps in all)`; `total` is 0 while the export can't say (one file made in one go).
|
||||
pub fn counts(&self) -> (u64, u64) {
|
||||
let total = self.total.load(Ordering::Relaxed);
|
||||
@@ -68,7 +76,8 @@ impl Progress {
|
||||
/// Run `f` with `progress`'s token in effect on this thread and the steps reported to it.
|
||||
pub fn scope<R>(progress: &Arc<Progress>, f: impl FnOnce() -> R) -> R {
|
||||
let to = Arc::clone(progress);
|
||||
let sink: ProgressSink = Rc::new(move |done, total, _| {
|
||||
let sink: ProgressSink = Rc::new(move |done, total, what| {
|
||||
to.share.store(what == vectorcraft_plugins::host::PROGRESS_STEP, Ordering::Relaxed);
|
||||
to.total.store(total, Ordering::Relaxed);
|
||||
to.done.store(done, Ordering::Relaxed);
|
||||
});
|
||||
@@ -94,4 +103,14 @@ mod tests {
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{:?}", r.err());
|
||||
assert!(!cancel::is_cancelled(), "the scope ended");
|
||||
}
|
||||
|
||||
/// A plug-in's reports count as a share of the work, not as artboards or files.
|
||||
#[test]
|
||||
fn a_plugin_s_reports_count_as_a_share_of_the_work() {
|
||||
let p = Progress::new();
|
||||
scope(&p, || cancel::progress(1, 4, "artboard"));
|
||||
assert_eq!((p.counts(), p.counts_share()), ((1, 4), false));
|
||||
scope(&p, || cancel::progress(3, 8, vectorcraft_plugins::host::PROGRESS_STEP));
|
||||
assert_eq!((p.counts(), p.counts_share()), ((3, 8), true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,7 +270,18 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
|
||||
}
|
||||
}
|
||||
// None given: the ones the document was last saved with in this format.
|
||||
let options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given };
|
||||
let mut options = if given.is_empty() && format.id == st.format { remembered_save_options(st) } else { given };
|
||||
// Remember the effective choice, including the encoder's default, so another document's
|
||||
// later save cannot change what this one writes. Invalid non-null values still reach validation.
|
||||
if matches!(format.id, "vectorcraft" | "template") {
|
||||
let pdf = match options.get("pdfCompatible") {
|
||||
None | Some(Value::Null) => Some(native_pdf_preference(s, Some(st)).unwrap_or(true)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(pdf) = pdf {
|
||||
options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
}
|
||||
// Save writes the document's own file; the other modes only where they are told to.
|
||||
let path =
|
||||
path.or_else(|| (mode == SaveMode::Save && !st.converted && !st.recovered && format.id == st.format).then(|| st.path.clone()).flatten());
|
||||
@@ -336,6 +347,15 @@ fn same_value(a: &Value, b: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Native documents and templates share only their PDF choice. Other source formats use the
|
||||
/// application's last native choice, keeping an AI file's separate PDF option out of it.
|
||||
fn native_pdf_preference(s: &Session, st: Option<&DocState>) -> Option<bool> {
|
||||
st.filter(|d| matches!(d.format, "vectorcraft" | "template"))
|
||||
.and_then(|d| d.save_options.get("pdfCompatible"))
|
||||
.and_then(Value::as_bool)
|
||||
.or_else(|| s.prefs.native_save_options.get("pdfCompatible").and_then(Value::as_bool))
|
||||
}
|
||||
|
||||
/// The options `st` was last saved with, their artboards (`artboard`, `artboards` and `range`)
|
||||
/// following the artboards they named ([`DocState::save_artboards`]): an artboard deleted since is
|
||||
/// left out, and one that moved is named by its new number. When none of the artboards the save
|
||||
@@ -1028,12 +1048,15 @@ fn can_revert(s: &Session) -> std::result::Result<(), String> {
|
||||
fn revert(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let index = s.active_index().ok_or(crate::EngineError::NoDocument)?;
|
||||
let path = s.doc()?.path.clone().ok_or_else(|| bad("file.revert", "the document has never been saved"))?;
|
||||
let Loaded { mut doc, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs);
|
||||
let Loaded { mut doc, native_pdf_compatible, .. } = load(&path, &read_file(&path)?)?.with_grid_prefs(&s.prefs);
|
||||
doc.template = false;
|
||||
// Back to the saved file: its recovery copy has nothing left to recover.
|
||||
let uid = s.doc()?.uid;
|
||||
crate::cmd::recovery::forget(s, uid);
|
||||
s.replace_document(index, doc);
|
||||
if let Some(pdf) = native_pdf_compatible {
|
||||
s.doc_mut()?.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
Ok(json!({ "path": path }))
|
||||
}
|
||||
|
||||
@@ -1053,11 +1076,17 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.or_else(|| (f.id == "vectorcraft" && !s.prefs.native_save_options.is_empty()).then(|| s.prefs.native_save_options.clone()));
|
||||
// A native save compresses as Use Compression says, unless told otherwise.
|
||||
let prefs = with_compression_pref(&s.prefs, &json!({}));
|
||||
let native_pdf = matches!(f.id, "vectorcraft" | "template").then(|| native_pdf_preference(s, st)).flatten();
|
||||
let mut v = f.to_json();
|
||||
if let Some(options) = v["options"].as_object_mut() {
|
||||
for (name, o) in options.iter_mut() {
|
||||
let default = prefs.get(name).filter(|_| matches!(f.id, "vectorcraft" | "template")).unwrap_or(&o["default"]);
|
||||
o["value"] = saved.as_ref().and_then(|m| m.get(name)).unwrap_or(default).clone();
|
||||
if name == "pdfCompatible"
|
||||
&& let Some(pdf) = native_pdf
|
||||
{
|
||||
o["value"] = json!(pdf);
|
||||
}
|
||||
}
|
||||
}
|
||||
v["saveFormats"] =
|
||||
@@ -1072,7 +1101,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: false for native (also carry a PDF of every artboard) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file: a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS saves the chosen artboard (first by default), retaining its page margins and the whole editable document; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -670,7 +670,7 @@ fn find_preset(s: &Session, name: &str) -> Option<ScreenExportPreset> {
|
||||
}
|
||||
|
||||
/// `p` over the settings of its `exportPreset`, when it names one (its own keys win).
|
||||
fn with_preset(s: &Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn with_preset(s: &Session, p: &Value) -> Result<Value> {
|
||||
let Some(name) = str_param(p, "exportPreset") else { return Ok(p.clone()) };
|
||||
let preset = find_preset(s, name).ok_or_else(|| bad(C, format!("no export preset `{name}` (see document.exportPresets.list)")))?;
|
||||
let mut merged = preset.settings;
|
||||
@@ -1019,11 +1019,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
let mut out = Output::default();
|
||||
// The encoders' warnings for every file, each once.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
|
||||
// written on a page of their own bounds, which it doesn't grow.
|
||||
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
|
||||
for w in notes {
|
||||
if !warnings.contains(&w) {
|
||||
if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
@@ -1207,6 +1210,9 @@ fn items(
|
||||
let mut pieces = vec![];
|
||||
for id in ids {
|
||||
let a = doc.asset(*id).ok_or_else(|| bad(C, format!("no asset {id} (see assets.list)")))?;
|
||||
if a.format_3d.is_some() {
|
||||
return Err(bad(C, format!("asset {id} is a 3D asset: assets.export3D writes it")));
|
||||
}
|
||||
let (d, r) = alone(&a.nodes, &a.name).ok_or_else(|| bad(C, format!("asset `{}` has no art to export", a.name)))?;
|
||||
pieces.push((a.name.clone(), d, Some(0), r));
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
chosen.then(|| boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect());
|
||||
let overflow = crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, regions.as_deref());
|
||||
// Render effects SVG cannot represent faithfully, including source-model Darkness shadows.
|
||||
let flat = crate::cmd::rasterfx::flatten_pixel_effects(doc);
|
||||
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() };
|
||||
for artboard in boards {
|
||||
|
||||
@@ -680,7 +680,9 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
for (name, compress) in [("a.vectorcraft", false), ("b.vectorcraft", true), ("c.vctemplate", true)] {
|
||||
let path = d.join(name).to_string_lossy().to_string();
|
||||
let p = json!({"path": path, "compress": compress});
|
||||
// A PDF-compatible file's PDF is dated to the second it is written, so the byte comparison
|
||||
// uses files without one.
|
||||
let p = json!({"path": path, "compress": compress, "pdfCompatible": false});
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
let written = std::fs::read(&path).unwrap();
|
||||
assert_eq!(r["bytes"], written.len(), "{r}");
|
||||
@@ -690,6 +692,17 @@ fn a_native_save_streams_the_bytes_the_encoder_makes() {
|
||||
assert_eq!(written, job.encode().unwrap().files[0].1, "{name}");
|
||||
assert_eq!(vectorcraft_format::load(&written).unwrap().template, name.ends_with("vctemplate"));
|
||||
}
|
||||
// A save with the default options streams a file that carries its PDF.
|
||||
let path = d.join("d.vectorcraft").to_string_lossy().to_string();
|
||||
let p = json!({"path": path});
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
let written = std::fs::read(&path).unwrap();
|
||||
assert_eq!(r["bytes"], written.len(), "{r}");
|
||||
assert!(vectorcraft_format::pdf_content(&written).is_some());
|
||||
let plan = save_plan(&s, SaveMode::Copy, &p).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
assert!(job.streams());
|
||||
assert!(vectorcraft_format::pdf_content(&job.encode().unwrap().files[0].1).is_some());
|
||||
// A writer that fails: the save fails with its error.
|
||||
let plan = save_plan(&s, SaveMode::Copy, &json!({"path": "/x/y.vectorcraft"})).unwrap();
|
||||
let job = save_job(&mut s, plan).unwrap();
|
||||
|
||||
@@ -98,7 +98,9 @@ fn templates_and_libraries_cannot_silently_extract_preview_content() {
|
||||
let original = s.doc().unwrap().doc.clone();
|
||||
for name in ["test.af", "renamed.svg"] {
|
||||
let p = json!({"name":name, "dataBase64":vectorcraft_format::base64_encode(&file(&png()))});
|
||||
for cmd in ["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary"] {
|
||||
for cmd in
|
||||
["file.newFromTemplate", "swatch.library.load", "graphicStyle.loadLibrary", "charStyle.load", "paraStyle.load", "textStyle.loadAll"]
|
||||
{
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("File › Open"), "{cmd}: {e}");
|
||||
}
|
||||
|
||||
@@ -63,6 +63,32 @@ fn export_writes_dxf_of_the_chosen_version() {
|
||||
assert_eq!(header(&text(&ser), "$INSUNITS").as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cnc_preset_sets_the_options_that_are_not_given() {
|
||||
let mut s = two_boards();
|
||||
let cnc = text(&s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap());
|
||||
assert_eq!(header(&cnc, "$ACADVER").as_deref(), Some("AC1015"));
|
||||
assert_eq!(header(&cnc, "$INSUNITS").as_deref(), Some("4"));
|
||||
// document.export takes it too, beside a PDF preset's name.
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc"})).unwrap();
|
||||
assert_eq!(header(&text(&r), "$ACADVER").as_deref(), Some("AC1015"));
|
||||
let o = dxf::options(&json!({"dxfPreset": "CNC", "unit": "in"})).unwrap();
|
||||
assert_eq!(
|
||||
(o.version, o.unit, o.colors, o.preserve, o.alter_paths, o.outline_text),
|
||||
(
|
||||
vectorcraft_cad::DxfVersion::R2000,
|
||||
vectorcraft_doc::Unit::Inches,
|
||||
vectorcraft_cad::ColorDepth::Aci256,
|
||||
vectorcraft_cad::Preserve::Editability,
|
||||
false,
|
||||
true
|
||||
)
|
||||
);
|
||||
assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default");
|
||||
let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string();
|
||||
assert!(e.contains("custom or cnc"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn use_artboards_writes_one_drawing_per_artboard() {
|
||||
let mut s = two_boards();
|
||||
|
||||
@@ -0,0 +1,620 @@
|
||||
//! HEIC and HEIF Open, Place, pixel, color and resolution regressions using original synthetic
|
||||
//! fixtures (quadrants of four colors, lossy HEVC, so colors are compared within a tolerance).
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
use serde_json::json;
|
||||
|
||||
use super::heifread::is_heif;
|
||||
use super::*;
|
||||
|
||||
const QUADRANTS: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants.heic");
|
||||
const ALPHA: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants-alpha.heic");
|
||||
const TEN_BIT: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants-10bit.heic");
|
||||
const GRID: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants-grid.heic");
|
||||
const GRID16: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants-grid16.heic");
|
||||
const PPI300: &[u8] = include_bytes!("../../../tests/fixtures/heif/quadrants-300ppi.heic");
|
||||
const ROTATED: &[u8] = include_bytes!("../../../tests/fixtures/heif/wide-rotated.heic");
|
||||
const ROTATED_300X150: &[u8] = include_bytes!("../../../tests/fixtures/heif/wide-rotated-300x150.heic");
|
||||
const TONES: &[u8] = include_bytes!("../../../tests/fixtures/heif/tones.heic");
|
||||
const TONES_P3_NCLX: &[u8] = include_bytes!("../../../tests/fixtures/heif/tones-p3-nclx.heic");
|
||||
const TONES_P3_ICC: &[u8] = include_bytes!("../../../tests/fixtures/heif/tones-p3-icc.heic");
|
||||
const TONES_P3_ICC_ONLY: &[u8] = include_bytes!("../../../tests/fixtures/heif/tones-p3-icc-only.heic");
|
||||
|
||||
const EVERY_FIXTURE: [&[u8]; 12] =
|
||||
[QUADRANTS, ALPHA, TEN_BIT, GRID, GRID16, PPI300, ROTATED, ROTATED_300X150, TONES, TONES_P3_NCLX, TONES_P3_ICC, TONES_P3_ICC_ONLY];
|
||||
|
||||
/// Red, green, blue and white: the top-left, top-right, bottom-left and bottom-right quadrants.
|
||||
#[cfg(feature = "heif")]
|
||||
const COLORS: [[u8; 4]; 4] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]];
|
||||
|
||||
/// The centers of the four quadrants of a square image `side` pixels wide.
|
||||
#[cfg(feature = "heif")]
|
||||
fn centers(side: u32) -> [(u32, u32); 4] {
|
||||
let (a, b) = (side / 4, side * 3 / 4);
|
||||
[(a, a), (b, a), (a, b), (b, b)]
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn decoded(bytes: &[u8]) -> image::RgbaImage {
|
||||
let raster = load::raster_image(bytes).unwrap();
|
||||
image::load_from_memory(&raster.blob.bytes).unwrap().to_rgba8()
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn close(got: [u8; 4], want: [u8; 4], tolerance: u8) -> bool {
|
||||
got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= tolerance)
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn assert_quadrants(img: &image::RgbaImage, side: u32, what: &str) {
|
||||
assert_eq!(img.dimensions(), (side, side), "{what}");
|
||||
for ((x, y), want) in centers(side).into_iter().zip(COLORS) {
|
||||
let got = img.get_pixel(x, y).0;
|
||||
assert!(close(got, want, 8), "{what} at ({x}, {y}): {got:?} != {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn quadrants_open_and_place_as_their_pixels() {
|
||||
assert_quadrants(&decoded(QUADRANTS), 32, "quadrants.heic");
|
||||
for name in ["photo.heic", "photo.heif", "unknown.bin"] {
|
||||
let mut s = Session::new();
|
||||
let encoded = vectorcraft_format::base64_encode(QUADRANTS);
|
||||
let opened = s.execute("document.open", &json!({"name": name, "dataBase64": encoded})).unwrap();
|
||||
assert_eq!(opened["format"], "heif", "{name}");
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(32.0, 32.0));
|
||||
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
|
||||
assert_quadrants(&image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), 32, name);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let placed = s.execute("file.place", &json!({"name": name, "dataBase64": encoded})).unwrap();
|
||||
assert_eq!(placed["format"], "heif", "{name}");
|
||||
}
|
||||
assert!(load::texture_image(QUADRANTS).is_ok());
|
||||
// The general brand alone, without `heic`.
|
||||
let mut general = QUADRANTS.to_vec();
|
||||
assert_eq!(&QUADRANTS[8..28], b"heic\0\0\0\0mif1heicmiaf");
|
||||
general[8..12].copy_from_slice(b"mif1");
|
||||
general[20..24].copy_from_slice(b"miaf");
|
||||
assert_quadrants(&decoded(&general), 32, "mif1 only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signatures_and_every_extension() {
|
||||
for bytes in EVERY_FIXTURE {
|
||||
assert!(is_heif(bytes));
|
||||
assert_eq!(load::detect("unknown.bin", bytes).map(|f| f.id), Some("heif"));
|
||||
}
|
||||
for ext in ["heic", "heif"] {
|
||||
assert_eq!(load::detect(&format!("a.{ext}"), b"invalid").map(|f| f.id), Some("heif"));
|
||||
assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}");
|
||||
}
|
||||
// A brand only among the compatible ones counts, and so do the general brands alone.
|
||||
assert!(is_heif(b"\0\0\0\x14ftypabcd\0\0\0\0heic"));
|
||||
assert!(is_heif(b"\0\0\0\x18ftypmif1\0\0\0\0mif1heix"));
|
||||
assert!(is_heif(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc"));
|
||||
assert!(is_heif(b"\0\0\0\x18ftypmif1\0\0\0\0mif1miaf"));
|
||||
// A 64-bit box size (ISO/IEC 14496-12 4.2).
|
||||
assert!(is_heif(b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18heic\0\0\0\0"));
|
||||
let mut extended = b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18heic\0\0\0\0".to_vec();
|
||||
extended.extend_from_slice(&QUADRANTS[QUADRANTS.windows(4).position(|w| w == b"meta").unwrap() - 4..]);
|
||||
assert_eq!(load::detect("unknown.bin", &extended).map(|f| f.id), Some("heif"));
|
||||
// AVIF, with its brand major or compatible, and brands heic-rs doesn't read.
|
||||
assert!(!is_heif(b"\0\0\0\x18ftypavif\0\0\0\0mif1miaf"));
|
||||
assert!(!is_heif(b"\0\0\0\x1cftypmif1\0\0\0\0mif1avifmiaf"));
|
||||
assert!(!is_heif(b"\0\0\0\x1cftypheic\0\0\0\0mif1heicavis"));
|
||||
assert!(!is_heif(b"\0\0\0\x18ftyphevx\0\0\0\0hevxiso8"));
|
||||
assert!(!is_heif(b"\0\0\0\x18ftypisom\0\0\0\0isomavc1"));
|
||||
// A box shorter than its brands, longer than the file, or of another type.
|
||||
assert!(!is_heif(b"\0\0\0\x0cftypheic"));
|
||||
assert!(!is_heif(b"\0\0\0\x40ftypheic\0\0\0\0mif1"));
|
||||
assert!(!is_heif(b"\0\0\0\x14styphei\0\0\0\0\0heic"));
|
||||
assert!(!is_heif(b""));
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn alpha_10_bit_and_grid_images_keep_their_pixels() {
|
||||
let alpha = decoded(ALPHA);
|
||||
assert_eq!(alpha.dimensions(), (32, 32));
|
||||
for ((x, y), want) in centers(32).into_iter().zip(COLORS) {
|
||||
let got = alpha.get_pixel(x, y).0;
|
||||
// The left half is opaque; the right half is transparent.
|
||||
if x < 16 {
|
||||
assert!(close(got, want, 8), "({x}, {y}): {got:?} != {want:?}");
|
||||
} else {
|
||||
assert!(got[3] <= 8, "({x}, {y}): {got:?}");
|
||||
}
|
||||
}
|
||||
assert_quadrants(&decoded(TEN_BIT), 32, "10-bit");
|
||||
// Four 64 × 64 tiles, one for each quadrant.
|
||||
assert_quadrants(&decoded(GRID), 128, "2 × 2 grid");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn a_grid_of_cropped_tiles_is_refused() {
|
||||
// 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each coded 64 × 64 and cropped back
|
||||
// with its own clap, which heic-rs 0.1.4 leaves out when it composes the grid.
|
||||
let error = load::raster_image(GRID16).err().unwrap().to_string();
|
||||
assert!(error.contains("kind of image that can't be read"), "{error}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn a_grid_without_its_own_color_box_uses_its_tiles() {
|
||||
// The grid item's associations (ipma) list ispe (1), pixi (5) and colr (3); the tiles carry
|
||||
// the same colr. Pointing the grid's third association at its ispe leaves the grid without one.
|
||||
let mut tiles_only = GRID.to_vec();
|
||||
assert_eq!(&GRID[565..571], &[0, 1, 3, 1, 0x85, 3], "item 1 with three associations, the last colr");
|
||||
tiles_only[570] = 1;
|
||||
assert_quadrants(&decoded(&tiles_only), 128, "colr on the tiles only");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn the_containers_rotation_is_applied() {
|
||||
// A 32 × 16 image, red then blue, stored with a quarter turn clockwise.
|
||||
let img = decoded(ROTATED);
|
||||
assert_eq!(img.dimensions(), (16, 32));
|
||||
assert!(close(img.get_pixel(8, 4).0, [255, 0, 0, 255], 8), "{:?}", img.get_pixel(8, 4));
|
||||
assert!(close(img.get_pixel(8, 27).0, [0, 0, 255, 255], 8), "{:?}", img.get_pixel(8, 27));
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(ROTATED)})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(16.0, 32.0));
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn the_containers_mirror_and_crop_are_applied() {
|
||||
// The rotated image's irot (property 6) turned to no rotation, and to an imir of the same
|
||||
// size: mirrored left to right (ISO/IEC 23008-12 6.5.12, axis 0).
|
||||
assert_eq!(&ROTATED[384..393], b"\0\0\0\x09irot\x03");
|
||||
let mut stored = ROTATED.to_vec();
|
||||
stored[392] = 0;
|
||||
let mut mirrored = ROTATED.to_vec();
|
||||
mirrored[388..393].copy_from_slice(b"imir\0");
|
||||
let (stored, mirrored) = (decoded(&stored), decoded(&mirrored));
|
||||
assert_eq!((stored.dimensions(), mirrored.dimensions()), ((32, 16), (32, 16)));
|
||||
let red = [255, 0, 0, 255];
|
||||
assert!(close(stored.get_pixel(8, 8).0, red, 8) && !close(stored.get_pixel(24, 8).0, red, 8), "{:?}", stored.get_pixel(8, 8));
|
||||
for (x, y) in [(4, 4), (8, 8), (20, 12), (27, 3)] {
|
||||
assert!(close(mirrored.get_pixel(x, y).0, stored.get_pixel(31 - x, y).0, 8), "({x}, {y})");
|
||||
}
|
||||
// The quadrants' clap (property 4) takes the top-left 32 × 32 of the 64 × 64 coded picture.
|
||||
// Rewritten to its top-left 16 × 16: a center offset of -24 (ISO/IEC 14496-12 12.1.4) leaves
|
||||
// the red quadrant alone. Its edge next to green is left out, as lossy chroma blends there.
|
||||
assert_eq!(&QUADRANTS[329..337], b"\0\0\0\x28clap");
|
||||
let mut cropped = QUADRANTS.to_vec();
|
||||
let clap: Vec<u8> = [16u32, 1, 16, 1, (-48i32).cast_unsigned(), 2, (-48i32).cast_unsigned(), 2].iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
cropped[337..369].copy_from_slice(&clap);
|
||||
let cropped = decoded(&cropped);
|
||||
assert_eq!(cropped.dimensions(), (16, 16));
|
||||
for (x, y) in [(0, 0), (8, 8), (12, 0), (0, 12), (12, 12)] {
|
||||
assert!(close(cropped.get_pixel(x, y).0, red, 8), "({x}, {y}): {:?}", cropped.get_pixel(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn exif_resolution_sizes_the_image_and_72_ppi_without_it() {
|
||||
let got = ppi::resolution(PPI300).unwrap();
|
||||
assert!((got.0 - 300.0).abs() < 0.01 && (got.1 - 300.0).abs() < 0.01, "{got:?}");
|
||||
assert_eq!(ppi::resolution(QUADRANTS), None);
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(PPI300)})).unwrap();
|
||||
let size = s.doc().unwrap().doc.artboards[0].rect.size();
|
||||
assert!((size.width - 7.68).abs() < 0.001 && (size.height - 7.68).abs() < 0.001, "{size:?}");
|
||||
let blob = s.doc().unwrap().doc.images.values().next().unwrap();
|
||||
let stored = ppi::resolution(&blob.bytes).unwrap();
|
||||
assert!((stored.0 - 300.0).abs() < 0.01 && (stored.1 - 300.0).abs() < 0.01);
|
||||
// 32 × 16 pixels at 300 ppi across and 150 down, turned a quarter: 16 × 32 pixels at 150 ppi
|
||||
// across and 300 down, the same 7.68 × 7.68 pt either way.
|
||||
assert_eq!(ppi::resolution(ROTATED_300X150), Some((300.0, 150.0)), "as stored");
|
||||
let img = load::raster_image(ROTATED_300X150).unwrap();
|
||||
assert_eq!((img.width, img.height, img.ppi), (16, 32, Some((150.0, 300.0))));
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "a.heic", "dataBase64": vectorcraft_format::base64_encode(ROTATED_300X150)})).unwrap();
|
||||
let size = s.doc().unwrap().doc.artboards[0].rect.size();
|
||||
assert!((size.width - 7.68).abs() < 0.001 && (size.height - 7.68).abs() < 0.001, "{size:?}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn display_p3_images_are_converted_to_srgb() {
|
||||
use vectorcraft_color::cms::{DISPLAY_P3, Intent, icc::builtin_rgb};
|
||||
let p3 = builtin_rgb(DISPLAY_P3).unwrap();
|
||||
let plain = decoded(TONES);
|
||||
// The ICC-only file's samples are full-range BT.601, which only its HEVC stream says.
|
||||
for (what, bytes) in [("nclx", TONES_P3_NCLX), ("ICC", TONES_P3_ICC), ("ICC only", TONES_P3_ICC_ONLY)] {
|
||||
let converted = decoded(bytes);
|
||||
for (x, y) in centers(32) {
|
||||
let [r, g, b, a] = plain.get_pixel(x, y).0;
|
||||
let rgb = p3.to_srgb_into(&[r, g, b].map(|v| f32::from(v) / 255.0), Intent::RelativeColorimetric).unwrap();
|
||||
let [r, g, b] = rgb.map(|v| (v * 255.0).round() as u8);
|
||||
let got = converted.get_pixel(x, y).0;
|
||||
assert!(close(got, [r, g, b, a], 2), "{what} at ({x}, {y}): {got:?} != {:?}", [r, g, b, a]);
|
||||
}
|
||||
}
|
||||
// The orange quadrant changes, so the conversion ran.
|
||||
assert!(!close(decoded(TONES_P3_NCLX).get_pixel(8, 8).0, plain.get_pixel(8, 8).0, 4));
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn display_p3_named_by_the_stream_alone_is_converted_to_srgb() {
|
||||
// The nclx file's item associates hvcC, colr (property 2), ispe, pixi and clap. Pointing the
|
||||
// colr association at the ispe leaves the item without a color box, and its HEVC stream's
|
||||
// video signal type, which names Display P3 with the sRGB curve, describes the samples.
|
||||
let ipma = TONES_P3_NCLX.windows(4).position(|w| w == b"ipma").unwrap();
|
||||
let at = ipma + 4 + 4 + 4 + 2 + 1 + 1;
|
||||
assert_eq!(&TONES_P3_NCLX[at - 4..at + 4], &[0, 1, 5, 0x81, 2, 3, 5, 0x84], "item 1 with five associations, the second colr");
|
||||
let mut stream_only = TONES_P3_NCLX.to_vec();
|
||||
stream_only[at] = 3;
|
||||
let want = decoded(TONES_P3_NCLX);
|
||||
let got = decoded(&stream_only);
|
||||
for (x, y) in centers(32) {
|
||||
assert!(close(got.get_pixel(x, y).0, want.get_pixel(x, y).0, 2), "at ({x}, {y}): {:?} != {:?}", got.get_pixel(x, y), want.get_pixel(x, y));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn two_quarter_turns_keep_the_resolution_axes() {
|
||||
// The rotated image's ipma lists its irot once; a second association with the same irot turns
|
||||
// it a half turn, so the EXIF resolution keeps its axes.
|
||||
let ipma = ROTATED_300X150.windows(4).position(|w| w == b"ipma").unwrap();
|
||||
let count = ipma + 4 + 4 + 4 + 2;
|
||||
let irot = ROTATED_300X150.windows(4).position(|w| w == b"irot").unwrap();
|
||||
let ipco = ROTATED_300X150.windows(4).position(|w| w == b"ipco").unwrap();
|
||||
// The irot's property index: its place among the boxes of ipco, counted from 1.
|
||||
let mut index = 1u8;
|
||||
let mut at = ipco + 4;
|
||||
while at < irot - 4 {
|
||||
index += 1;
|
||||
at += u32::from_be_bytes(ROTATED_300X150[at..at + 4].try_into().unwrap()) as usize;
|
||||
}
|
||||
assert_eq!(at, irot - 4, "irot is a box of ipco");
|
||||
let n = usize::from(ROTATED_300X150[count]);
|
||||
assert!(ROTATED_300X150[count + 1..count + 1 + n].contains(&(0x80 | index)), "the item's irot association, essential");
|
||||
let mut twice = ROTATED_300X150.to_vec();
|
||||
twice[count] += 1;
|
||||
twice.insert(count + 1 + n, 0x80 | index);
|
||||
// The ipma, iprp and meta boxes each grow by one byte, and the iloc offsets move with them.
|
||||
let grow = |bytes: &mut Vec<u8>, name: &[u8; 4]| {
|
||||
let at = bytes.windows(4).position(|w| w == name).unwrap() - 4;
|
||||
let size = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap()) + 1;
|
||||
bytes[at..at + 4].copy_from_slice(&size.to_be_bytes());
|
||||
};
|
||||
for name in [b"ipma", b"iprp", b"meta"] {
|
||||
grow(&mut twice, name);
|
||||
}
|
||||
let iloc = twice.windows(4).position(|w| w == b"iloc").unwrap();
|
||||
assert_eq!(&twice[iloc + 4..iloc + 8], &[0, 0, 0, 0], "iloc version 0");
|
||||
let sizes = twice[iloc + 8];
|
||||
assert_eq!((sizes >> 4, sizes & 0xf), (4, 4), "4-byte offsets and lengths");
|
||||
assert_eq!(twice[iloc + 9] >> 4, 4, "4-byte base offsets");
|
||||
let items = u16::from_be_bytes([twice[iloc + 10], twice[iloc + 11]]);
|
||||
// Each item: its id, data reference index and base offset, which moves, then its extents.
|
||||
let mut at = iloc + 12;
|
||||
for _ in 0..items {
|
||||
at += 2 + 2;
|
||||
let offset = u32::from_be_bytes(twice[at..at + 4].try_into().unwrap()) + 1;
|
||||
twice[at..at + 4].copy_from_slice(&offset.to_be_bytes());
|
||||
at += 4;
|
||||
let extents = u16::from_be_bytes([twice[at], twice[at + 1]]);
|
||||
at += 2 + 8 * usize::from(extents);
|
||||
}
|
||||
let img = load::raster_image(&twice).unwrap();
|
||||
assert_eq!((img.width, img.height, img.ppi), (32, 16, Some((300.0, 150.0))), "a half turn keeps the stored axes");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn damaged_unsupported_and_oversized_files_are_refused() {
|
||||
let error = |bytes: &[u8]| load::raster_image(bytes).err().unwrap().to_string();
|
||||
for cut in [16, 40, QUADRANTS.len() / 2, QUADRANTS.len() - 5] {
|
||||
assert!(load::raster_image(&QUADRANTS[..cut]).is_err(), "{cut}");
|
||||
}
|
||||
// An ftyp and nothing else, as an image sequence starts (its `moov` would follow).
|
||||
assert!(error(b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc").contains("kind of image that can't be read"));
|
||||
assert!(error(b"\0\0\0\x18ftypheic\0\0\0\0mif1heic\0\0\0\x08free").contains("HEIC or HEIF file"));
|
||||
// The primary item's type (infe) turned from HEVC to AV1, with its hvcC kept, and with its
|
||||
// hvcC turned into an av1C.
|
||||
let mut av1 = QUADRANTS.to_vec();
|
||||
assert_eq!((&QUADRANTS[137..141], &QUADRANTS[176..180]), (&b"hvc1"[..], &b"hvcC"[..]));
|
||||
av1[137..141].copy_from_slice(b"av01");
|
||||
assert!(error(&av1).contains("kind of image that can't be read"), "{}", error(&av1));
|
||||
av1[176..180].copy_from_slice(b"av1C");
|
||||
assert!(error(&av1).contains("kind of image that can't be read"), "{}", error(&av1));
|
||||
// The image spatial extents (`ispe`) claim 60,000 × 60,000 pixels.
|
||||
let mut huge = QUADRANTS.to_vec();
|
||||
let at = huge.windows(4).position(|w| w == b"ispe").unwrap() + 8;
|
||||
huge[at..at + 4].copy_from_slice(&60_000u32.to_be_bytes());
|
||||
huge[at + 4..at + 8].copy_from_slice(&60_000u32.to_be_bytes());
|
||||
assert!(error(&huge).contains("60000 × 60000 pixels is too large to draw"), "{}", error(&huge));
|
||||
// A single 64 × 64 coded picture (cropped to 32 × 32) takes its RGBA output and copy,
|
||||
// 64 × 64 × 8, and its planes, 64 × 64 × 9: no composed frame is counted.
|
||||
assert!(super::heifread::decode(QUADRANTS, 64 * 64 * 17).is_ok());
|
||||
assert!(super::heifread::decode(QUADRANTS, 64 * 64 * 17 - 1).unwrap_err().contains("too large to draw"));
|
||||
// The same picture with an ispe of 32 × 32 (its crop's size): its stream still decodes
|
||||
// 64 × 64, and that size is counted.
|
||||
let mut small = QUADRANTS.to_vec();
|
||||
let at = small.windows(4).position(|w| w == b"ispe").unwrap() + 8;
|
||||
assert_eq!(&small[at..at + 8], b"\0\0\0\x40\0\0\0\x40");
|
||||
small[at..at + 4].copy_from_slice(&32u32.to_be_bytes());
|
||||
small[at + 4..at + 8].copy_from_slice(&32u32.to_be_bytes());
|
||||
let refused = super::heifread::decode(&small, 64 * 64 * 17 - 1).map(|img| img.dimensions());
|
||||
assert!(refused.as_ref().is_err_and(|e| e.contains("too large to draw")), "{refused:?}");
|
||||
// A 128 × 128 grid of four 64 × 64 tiles adds its composed frame, 128 × 128 × 6.
|
||||
let grid = 128 * 128 * (8 + 6) + 4 * 64 * 64 * 9;
|
||||
assert!(super::heifread::decode(GRID, grid).is_ok());
|
||||
assert!(super::heifread::decode(GRID, grid - 1).unwrap_err().contains("too large to draw"));
|
||||
// The grid's ispe (property 1) claims 16 × 16 pixels; its grid data still composes 128 × 128,
|
||||
// and that size is counted.
|
||||
let mut understated = GRID.to_vec();
|
||||
assert_eq!(&GRID[358..370], b"ispe\0\0\0\0\0\0\0\x80", "property 1 is the grid's 128 × 128 ispe");
|
||||
understated[366..370].copy_from_slice(&16u32.to_be_bytes());
|
||||
understated[370..374].copy_from_slice(&16u32.to_be_bytes());
|
||||
assert!(super::heifread::decode(&understated, grid - 1).unwrap_err().contains("too large to draw"));
|
||||
}
|
||||
|
||||
/// Appends `value` as `n` bits, most significant first.
|
||||
#[cfg(feature = "heif")]
|
||||
fn put(bits: &mut Vec<bool>, value: u64, n: u32) {
|
||||
bits.extend((0..n).rev().map(|i| i < 64 && value >> i & 1 == 1));
|
||||
}
|
||||
|
||||
/// Appends `value` as an unsigned Exp-Golomb code.
|
||||
#[cfg(feature = "heif")]
|
||||
fn put_ue(bits: &mut Vec<bool>, value: u64) {
|
||||
let len = 64 - (value + 1).leading_zeros();
|
||||
put(bits, 0, len - 1);
|
||||
put(bits, value + 1, len);
|
||||
}
|
||||
|
||||
/// The fields of SPS 0 of `width` × `height` 4:2:0 samples with `sub_layers` sub-layers, each
|
||||
/// with its profile and level, up to its height.
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps_head(width: u64, height: u64, sub_layers: u64) -> Vec<bool> {
|
||||
sps_head_with_id(width, height, sub_layers, 0)
|
||||
}
|
||||
|
||||
/// [`sps_head`] for SPS `id`.
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps_head_with_id(width: u64, height: u64, sub_layers: u64, id: u64) -> Vec<bool> {
|
||||
let mut bits = Vec::new();
|
||||
put(&mut bits, 0, 4);
|
||||
put(&mut bits, sub_layers, 3);
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 0, 96);
|
||||
for _ in 0..sub_layers {
|
||||
put(&mut bits, 0b11, 2);
|
||||
}
|
||||
if sub_layers > 0 {
|
||||
put(&mut bits, 0, 2 * (8 - sub_layers as u32));
|
||||
}
|
||||
for _ in 0..sub_layers {
|
||||
put(&mut bits, 0, 88 + 8);
|
||||
}
|
||||
put_ue(&mut bits, id);
|
||||
put_ue(&mut bits, 1);
|
||||
put_ue(&mut bits, width);
|
||||
put_ue(&mut bits, height);
|
||||
bits
|
||||
}
|
||||
|
||||
/// An SPS NAL unit of `bits` (see [`nal`]).
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps_nal(bits: Vec<bool>) -> Vec<u8> {
|
||||
nal(33, bits)
|
||||
}
|
||||
|
||||
/// A NAL unit of type `kind` holding `bits`, with its stop bit, and emulation prevention bytes
|
||||
/// inserted as a stream carries them.
|
||||
#[cfg(feature = "heif")]
|
||||
fn nal(kind: u8, mut bits: Vec<bool>) -> Vec<u8> {
|
||||
put(&mut bits, 1, 1);
|
||||
while !bits.len().is_multiple_of(8) {
|
||||
bits.push(false);
|
||||
}
|
||||
let rbsp: Vec<u8> = bits.chunks(8).map(|b| b.iter().fold(0u8, |v, &bit| v << 1 | u8::from(bit))).collect();
|
||||
let mut nal = vec![kind << 1, 1];
|
||||
let mut zeros = 0;
|
||||
for b in rbsp {
|
||||
if zeros >= 2 && b <= 3 {
|
||||
nal.push(3);
|
||||
zeros = 0;
|
||||
}
|
||||
zeros = if b == 0 { zeros + 1 } else { 0 };
|
||||
nal.push(b);
|
||||
}
|
||||
nal
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps(width: u64, height: u64, sub_layers: u64) -> Vec<u8> {
|
||||
sps_nal(sps_head(width, height, sub_layers))
|
||||
}
|
||||
|
||||
/// A 64 × 64 SPS that uses every optional part before the VUI's video signal type: a conformance
|
||||
/// window, sub-layer ordering for two sub-layers, explicit scaling lists, PCM, a reference picture
|
||||
/// set predicted from another and a long-term picture, then an Extended_SAR aspect ratio and
|
||||
/// overscan information. `signal` is the full-range flag and the color description, if any.
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps_with_vui(signal: Option<(u64, Option<[u64; 3]>)>) -> Vec<u8> {
|
||||
sps_with_vui_and_id(signal, 0)
|
||||
}
|
||||
|
||||
/// [`sps_with_vui`] for SPS `id`.
|
||||
#[cfg(feature = "heif")]
|
||||
fn sps_with_vui_and_id(signal: Option<(u64, Option<[u64; 3]>)>, id: u64) -> Vec<u8> {
|
||||
let mut bits = sps_head_with_id(64, 64, 1, id);
|
||||
put(&mut bits, 1, 1);
|
||||
for offset in [0, 2, 0, 2] {
|
||||
put_ue(&mut bits, offset);
|
||||
}
|
||||
put_ue(&mut bits, 0);
|
||||
put_ue(&mut bits, 0);
|
||||
// 8 bits of picture order count.
|
||||
put_ue(&mut bits, 4);
|
||||
put(&mut bits, 1, 1);
|
||||
for _ in 0..2 * 3 {
|
||||
put_ue(&mut bits, 1);
|
||||
}
|
||||
for value in [0, 3, 0, 3, 1, 1] {
|
||||
put_ue(&mut bits, value);
|
||||
}
|
||||
// Scaling lists: matrix 1 of each size given explicitly, the others copied.
|
||||
put(&mut bits, 0b11, 2);
|
||||
for size in 0..4 {
|
||||
for matrix in 0..if size == 3 { 2 } else { 6 } {
|
||||
if matrix == 1 {
|
||||
put(&mut bits, 1, 1);
|
||||
if size > 1 {
|
||||
put_ue(&mut bits, 5);
|
||||
}
|
||||
for _ in 0..if size == 0 { 16 } else { 64 } {
|
||||
put_ue(&mut bits, 3);
|
||||
}
|
||||
} else {
|
||||
put(&mut bits, 0, 1);
|
||||
put_ue(&mut bits, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// AMP off, SAO on, PCM with its depths, block sizes and loop filter flag.
|
||||
put(&mut bits, 0b01, 2);
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 0x77, 8);
|
||||
put_ue(&mut bits, 0);
|
||||
put_ue(&mut bits, 1);
|
||||
put(&mut bits, 0, 1);
|
||||
// Two short-term sets: one negative and one positive picture, then a set predicted from it
|
||||
// with three entries (unused with use_delta_flag, used, unused).
|
||||
put_ue(&mut bits, 2);
|
||||
put_ue(&mut bits, 1);
|
||||
put_ue(&mut bits, 1);
|
||||
for _ in 0..2 {
|
||||
put_ue(&mut bits, 0);
|
||||
put(&mut bits, 1, 1);
|
||||
}
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 0, 1);
|
||||
put_ue(&mut bits, 0);
|
||||
put(&mut bits, 0b01100, 5);
|
||||
// One long-term picture: 8 bits of picture order count and its used flag.
|
||||
put(&mut bits, 1, 1);
|
||||
put_ue(&mut bits, 1);
|
||||
put(&mut bits, 0xab, 8);
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 0b11, 2);
|
||||
// VUI: Extended_SAR 1:1 and overscan information.
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 255, 8);
|
||||
put(&mut bits, 0x0001_0001, 32);
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 0, 1);
|
||||
match signal {
|
||||
Some((full, description)) => {
|
||||
put(&mut bits, 1, 1);
|
||||
put(&mut bits, 5, 3);
|
||||
put(&mut bits, full, 1);
|
||||
put(&mut bits, u64::from(description.is_some()), 1);
|
||||
for code in description.into_iter().flatten() {
|
||||
put(&mut bits, code, 8);
|
||||
}
|
||||
}
|
||||
None => put(&mut bits, 0, 1),
|
||||
}
|
||||
// No chroma location, field or display window information, timing or restrictions.
|
||||
put(&mut bits, 0, 8);
|
||||
sps_nal(bits)
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn picture_sizes_come_from_the_sequence_parameter_sets() {
|
||||
use super::heifread::{picture_bytes, sps_size};
|
||||
for sub_layers in [0, 1, 6] {
|
||||
for (w, h) in [(32, 32), (4032, 3024), (65535, 65535)] {
|
||||
let nal = sps(w, h, sub_layers);
|
||||
assert!(nal.windows(3).any(|w| w == [0, 0, 3]), "the profile's zeros need emulation prevention");
|
||||
assert_eq!(sps_size(&nal), Some((w, h, 1)), "{w} × {h}, {sub_layers} sub-layers");
|
||||
}
|
||||
}
|
||||
let mut vps = sps(32, 32, 0);
|
||||
vps[0] = 32 << 1;
|
||||
assert_eq!(sps_size(&vps), None);
|
||||
assert_eq!(sps_size(&sps(32, 32, 0)[..8]), None);
|
||||
// 4:2:0 is 3 bytes a sample position in each of three sets of planes, in 64-sample blocks.
|
||||
assert_eq!(picture_bytes(QUADRANTS), Some(64 * 64 * 9));
|
||||
assert_eq!(picture_bytes(GRID), Some(4 * 64 * 64 * 9));
|
||||
assert!(picture_bytes(ALPHA).unwrap() > 64 * 64 * 9, "the alpha image is counted");
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn the_color_description_comes_from_the_streams_video_signal_type() {
|
||||
use super::heifread::{sps_signal, sps_size};
|
||||
use heic_rs::{MatrixCoefficients, Range};
|
||||
let signal = |nal: &[u8]| sps_signal(nal).map(|n| (n.primaries, n.transfer, n.matrix, n.matrix_code, n.range));
|
||||
let described = sps_with_vui(Some((1, Some([12, 13, 6]))));
|
||||
assert_eq!(sps_size(&described), Some((64, 64, 1)));
|
||||
assert_eq!(signal(&described), Some((12, 13, MatrixCoefficients::Bt601, 6, Range::Full)));
|
||||
assert_eq!(signal(&sps_with_vui(Some((0, None)))), Some((2, 2, MatrixCoefficients::Unspecified, 2, Range::Limited)));
|
||||
assert_eq!(signal(&sps_with_vui(None)), None);
|
||||
assert_eq!(signal(&sps(64, 64, 0)), None, "cut short before its VUI");
|
||||
// The ICC-only fixture's stream: heif-enc writes full-range BT.601.
|
||||
let ctx = heic_rs::context::Context::open(TONES_P3_ICC_ONLY).unwrap();
|
||||
let props = ctx.props(ctx.meta.primary).unwrap();
|
||||
assert!(props.nclx.is_none() && props.icc.is_some());
|
||||
let sets = props.hvcc.unwrap().parameter_sets();
|
||||
let nal = sets.into_iter().find(|nal| nal[0] >> 1 & 0x3f == 33).unwrap();
|
||||
assert_eq!(sps_signal(nal).map(|n| (n.matrix, n.range)), Some((MatrixCoefficients::Bt601, Range::Full)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
#[test]
|
||||
fn the_slices_picture_parameter_set_picks_the_sps() {
|
||||
use super::heifread::{active_sps, sps_signal};
|
||||
use heic_rs::Range;
|
||||
let full = sps_with_vui_and_id(Some((1, Some([1, 13, 6]))), 0);
|
||||
let limited = sps_with_vui_and_id(Some((0, Some([1, 13, 1]))), 1);
|
||||
let pps = |id: u64, sps: u64| {
|
||||
let mut bits = Vec::new();
|
||||
put_ue(&mut bits, id);
|
||||
put_ue(&mut bits, sps);
|
||||
nal(34, bits)
|
||||
};
|
||||
// first_slice_segment_in_pic_flag, no_output_of_prior_pics_flag for an IDR picture (type 19),
|
||||
// slice_pic_parameter_set_id.
|
||||
let slice = |kind: u8, pps: u64| {
|
||||
let mut bits = vec![true];
|
||||
if kind == 19 {
|
||||
bits.push(false);
|
||||
}
|
||||
put_ue(&mut bits, pps);
|
||||
nal(kind, bits)
|
||||
};
|
||||
let (pps0, pps3) = (pps(0, 0), pps(3, 1));
|
||||
let sets = [full.as_slice(), limited.as_slice(), pps0.as_slice(), pps3.as_slice()];
|
||||
let (idr3, trail0, idr5) = (slice(19, 3), slice(1, 0), slice(19, 5));
|
||||
assert_eq!(active_sps(&sets, &[&idr3]), Some(limited.as_slice()));
|
||||
assert_eq!(active_sps(&sets, &[&trail0]), Some(full.as_slice()));
|
||||
assert_eq!(active_sps(&sets, &[&idr5]), None, "no PPS 5");
|
||||
assert_eq!(active_sps(&sets, &[&pps0]), None, "no slice");
|
||||
assert_eq!(active_sps(&sets, &[&idr3]).and_then(sps_signal).map(|n| (n.matrix_code, n.range)), Some((1, Range::Limited)));
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "heif"))]
|
||||
#[test]
|
||||
fn a_build_without_the_decoder_refuses_heif_files_with_a_message() {
|
||||
for bytes in EVERY_FIXTURE {
|
||||
assert_eq!(load::detect("unknown.bin", bytes).map(|f| f.id), Some("heif"));
|
||||
let error = load::raster_image(bytes).err().unwrap().to_string();
|
||||
assert!(error.contains("can't be opened in this build"), "{error}");
|
||||
}
|
||||
assert_eq!(ppi::resolution(PPI300), None);
|
||||
}
|
||||
@@ -488,7 +488,7 @@ fn an_ai_file_opens_from_its_vectorcraft_document_when_the_editing_copy_differs(
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [id]})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [id]})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "ai"})).unwrap();
|
||||
assert!(r["warnings"].to_string().contains("live effects"), "{r}");
|
||||
let bytes = b64(&r);
|
||||
|
||||
@@ -147,6 +147,76 @@ fn load_options_read_pages_crop_and_password() {
|
||||
assert_eq!(LoadOptions::from_params("x", &Value::Null).unwrap(), LoadOptions::default());
|
||||
}
|
||||
|
||||
/// `cropTo` (and `crop`), `password`, `colorMode` and `textAs` given as anything but a string are an
|
||||
/// error naming the param: `document.open` opens nothing and `file.place` places nothing and records
|
||||
/// no undo step. Null is the same as leaving the param out.
|
||||
#[test]
|
||||
fn pdf_options_of_the_wrong_type_are_refused() {
|
||||
let bytes = three_pages();
|
||||
let wrong = [
|
||||
("cropTo", json!(5)),
|
||||
("crop", json!(true)),
|
||||
("password", json!(123)),
|
||||
("colorMode", json!(5)),
|
||||
("textAs", json!(true)),
|
||||
("textAs", json!(["outlines"])),
|
||||
];
|
||||
let one = |key: &str, v: &Value| {
|
||||
let mut p = json!({});
|
||||
p[key] = v.clone();
|
||||
p
|
||||
};
|
||||
let mut s = Session::new();
|
||||
for (key, v) in &wrong {
|
||||
let e = open(&mut s, &bytes, one(key, v)).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}");
|
||||
assert!(s.active().is_none(), "{key}: nothing opened");
|
||||
}
|
||||
// A wrong `cropTo` is refused even when `crop` is a box, and a wrong `crop` when `cropTo` is.
|
||||
let e = open(&mut s, &bytes, json!({"cropTo": 2, "crop": "art"})).unwrap_err().to_string();
|
||||
assert!(e.contains("`cropTo` must be a string"), "{e}");
|
||||
let e = open(&mut s, &bytes, json!({"cropTo": "art", "crop": 2})).unwrap_err().to_string();
|
||||
assert!(e.contains("`crop` must be a string"), "{e}");
|
||||
assert!(s.active().is_none(), "nothing opened");
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let nodes = s.doc().unwrap().doc.node_count();
|
||||
for (key, v) in &wrong {
|
||||
let mut p = json!({"name": "pages.pdf", "dataBase64": b64(&bytes)});
|
||||
p[*key] = v.clone();
|
||||
let e = s.execute("file.place", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("`{key}` must be a string")), "{key}: {e}");
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.node_count()), (undo, nodes), "{key}: nothing placed");
|
||||
}
|
||||
// Null is left out; valid strings read as before.
|
||||
let nulls = json!({"cropTo": null, "crop": null, "password": null, "colorMode": null, "textAs": null});
|
||||
assert_eq!(LoadOptions::from_params("x", &nulls).unwrap(), LoadOptions::default());
|
||||
let o = LoadOptions::from_params("x", &json!({"cropTo": null, "crop": "Bleed", "colorMode": "CMYK", "textAs": "outlines"})).unwrap();
|
||||
assert_eq!(
|
||||
(o.crop, o.color_mode, o.text_as),
|
||||
(vectorcraft_pdf::CropTo::Bleed, Some(vectorcraft_doc::ColorMode::Cmyk), vectorcraft_pdf::TextAs::Outlines)
|
||||
);
|
||||
}
|
||||
|
||||
/// `document.pdfInfo`'s `thumbnailSize` given as anything but a number is an error, with or without
|
||||
/// a `thumbnail`; null is 160 px.
|
||||
#[test]
|
||||
fn pdf_info_refuses_a_thumbnail_size_that_is_not_a_number() {
|
||||
let bytes = three_pages();
|
||||
let mut s = Session::new();
|
||||
for v in [json!("100"), json!(true)] {
|
||||
for p in [json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": v}), json!({"dataBase64": b64(&bytes), "thumbnailSize": v})] {
|
||||
let e = s.execute("document.pdfInfo", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("`thumbnailSize` must be a number"), "{v}: {e}");
|
||||
}
|
||||
}
|
||||
let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "colorMode": 1})).unwrap_err().to_string();
|
||||
assert!(e.contains("`colorMode` must be a string"), "{e}");
|
||||
let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(&bytes), "thumbnail": 1, "thumbnailSize": null})).unwrap();
|
||||
let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(image::load_from_memory(&png).unwrap().width(), 160);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_postscript_ai_file_says_it_cannot_be_opened_yet() {
|
||||
// PostScript opens through the EPS reader now (tests_epsimport.rs): a program it can't read,
|
||||
|
||||
@@ -90,6 +90,55 @@ fn choosing_a_pdfx_standard_sets_its_version_and_turns_off_what_it_forbids() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF/X file without the bleed the document sets exports as asked and warns; the presets and
|
||||
/// options that take the document's bleed, and files that aren't PDF/X files, don't warn.
|
||||
#[test]
|
||||
fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() {
|
||||
let left_out = |w: &Vec<String>| w.iter().any(|w| w == super::pdf::BLEED_LEFT_OUT);
|
||||
let mut s = session();
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
for standard in ["pdfX1a", "pdfX3", "pdfX4"] {
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": standard}));
|
||||
// First: the status bar shows the first warning, and PDF/X-1a and PDF/X-3 add the flattening note.
|
||||
assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{standard}: {warnings:?}");
|
||||
// The page has no bleed, as asked.
|
||||
let v = s.execute("document.exportPdf", &json!({"standard": standard})).unwrap();
|
||||
let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap();
|
||||
let boxes = &info["pageInfo"][0]["boxes"];
|
||||
assert!(boxes["media"].is_array() && boxes["media"] == boxes["trim"] && boxes["media"] == boxes["bleed"], "{standard}: {info}");
|
||||
}
|
||||
let v = s.execute("document.export", &json!({"format": "pdf", "standard": "pdfX4"})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}");
|
||||
// A side the settings leave out warns, and sides they all keep don't.
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 6, "bottom": 6, "left": 6}}));
|
||||
assert!(left_out(&warnings), "{warnings:?}");
|
||||
for p in [
|
||||
json!({"preset": "PDF/X-1a:2001"}),
|
||||
json!({"preset": "PDF/X-3:2002"}),
|
||||
json!({"preset": "PDF/X-4:2010"}),
|
||||
json!({"standard": "pdfX4", "bleed": {"useDocument": true}}),
|
||||
json!({"standard": "pdfX4", "bleed": {"top": 1, "bottom": 1, "left": 1, "right": 1}}),
|
||||
json!({}),
|
||||
json!({"standard": "pdfA2b"}),
|
||||
] {
|
||||
let (_, warnings) = pdf(&mut s, p.clone());
|
||||
assert!(!left_out(&warnings), "{p}: {warnings:?}");
|
||||
}
|
||||
// The dialog's Summary exports in memory, so it lists the warning too.
|
||||
let v = s.execute("document.pdfSettings", &json!({"standard": "pdfX4", "includeDocument": true})).unwrap();
|
||||
assert!(v["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT), "{v}");
|
||||
// A bleed on the top alone: only that side counts.
|
||||
s.execute("document.setup", &json!({"bleed": [6, 0, 0, 0]})).unwrap();
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 1}}));
|
||||
assert!(!left_out(&warnings), "{warnings:?}");
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"bottom": 1}}));
|
||||
assert!(left_out(&warnings), "{warnings:?}");
|
||||
// A document without a bleed has nothing to leave out.
|
||||
s.execute("document.setup", &json!({"bleed": 0})).unwrap();
|
||||
let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4"}));
|
||||
assert!(!left_out(&warnings), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there).
|
||||
fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> {
|
||||
fn visit(n: &vectorcraft_doc::Node, out: &mut Vec<vectorcraft_doc::ImageObject>) {
|
||||
|
||||
@@ -526,6 +526,20 @@ fn include_bleed_grows_each_artboard() {
|
||||
assert_eq!(size(&files(&r)[0].1), (40, 30), "without it, the artboard alone");
|
||||
}
|
||||
|
||||
/// Include Bleed puts the bleed on a PDF/X row's page, so the row doesn't warn that it leaves the bleed out.
|
||||
#[test]
|
||||
fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() {
|
||||
let mut s = session(1);
|
||||
s.execute("document.setup", &json!({"bleed": 6})).unwrap();
|
||||
let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| w == super::pdf::BLEED_LEFT_OUT);
|
||||
let row = json!([{"format": "pdf", "standard": "pdfX4"}]);
|
||||
assert!(warned(&export(&mut s, json!({"formats": row}))));
|
||||
assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row}))));
|
||||
// A selection is written on a page of its own bounds, which Include Bleed doesn't grow.
|
||||
s.execute("shape.rectangle", &json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row}))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_8_rows_write_indexed_colour() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -224,7 +224,11 @@ fn save_writes_svg_and_remembers_its_options() {
|
||||
let native = dir.join("doc.vectorcraft").to_string_lossy().to_string();
|
||||
s.execute("document.save", &json!({"path": native})).unwrap();
|
||||
assert!(vectorcraft_format::sniff(&std::fs::read(&native).unwrap()));
|
||||
assert!(s.doc().unwrap().save_options.is_empty(), "a native save remembers no options");
|
||||
assert_eq!(
|
||||
Value::Object(s.doc().unwrap().save_options.clone()),
|
||||
json!({"pdfCompatible":true}),
|
||||
"a native save retains its PDF choice without SVG options"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,13 @@ pub const DEFLATE_CHUNK: usize = 1 << 20;
|
||||
/// The archive of `files` (`(name, bytes)`; `/` separates folders in a name), stored without
|
||||
/// compression. Fails past the limits of a ZIP without its 64-bit extension (65534 files, 4 GB; 65535 is the ZIP64 marker).
|
||||
pub fn store<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)]) -> Result<Vec<u8>, String> {
|
||||
store_aligned(files, 1)
|
||||
}
|
||||
|
||||
/// [`store`], with each file's data starting at a multiple of `align` bytes from the start of the
|
||||
/// archive (USDZ asks for 64): a padding block in the local header's extra field (header id
|
||||
/// 0x1986) moves it there.
|
||||
pub fn store_aligned<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)], align: usize) -> Result<Vec<u8>, String> {
|
||||
let too_big = || "too much to zip: at most 65534 files and 4 GB".to_string();
|
||||
let count = u16::try_from(files.len()).ok().filter(|&c| c != u16::MAX).ok_or_else(too_big)?;
|
||||
let mut out = Vec::with_capacity(files.iter().map(|(n, b)| 76 + 2 * n.as_ref().len() + b.as_ref().len()).sum::<usize>() + 22);
|
||||
@@ -47,8 +54,21 @@ pub fn store<N: AsRef<str>, B: AsRef<[u8]>>(files: &[(N, B)]) -> Result<Vec<u8>,
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&VERSION.to_le_bytes());
|
||||
out.extend_from_slice(&shared);
|
||||
out.extend_from_slice(&0u16.to_le_bytes()); // extra field length
|
||||
// The data would start after the header (30 bytes) and the name; a padding block of at
|
||||
// least its own 4-byte header moves it to the boundary.
|
||||
let start = out.len() + 2 + name.len();
|
||||
let mut pad = if align > 1 { (align - start % align) % align } else { 0 };
|
||||
if pad > 0 && pad < 4 {
|
||||
pad += align;
|
||||
}
|
||||
let pad_len = u16::try_from(pad).map_err(|_| format!("cannot align zip entries to {align} bytes"))?;
|
||||
out.extend_from_slice(&pad_len.to_le_bytes()); // extra field length
|
||||
out.extend_from_slice(name);
|
||||
if pad > 0 {
|
||||
out.extend_from_slice(&0x1986u16.to_le_bytes());
|
||||
out.extend_from_slice(&(pad_len - 4).to_le_bytes());
|
||||
out.resize(out.len() + pad - 4, 0);
|
||||
}
|
||||
out.extend_from_slice(bytes);
|
||||
// Central directory record.
|
||||
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
|
||||
|
||||
@@ -49,6 +49,8 @@ mod presets;
|
||||
mod report;
|
||||
|
||||
pub(crate) use analysis::{outlined_text, see_through_images};
|
||||
#[cfg(test)]
|
||||
pub(crate) use apply::with_every_region;
|
||||
pub(crate) use apply::{expand_transparent_tile_images, flatten_document, flatten_expanded, has_transparent_tile_images};
|
||||
pub use commands::specs;
|
||||
pub use options::FlattenOptions;
|
||||
|
||||
@@ -150,9 +150,15 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg
|
||||
}
|
||||
// An unclipped full raster needs no regions.
|
||||
let whole = o.balance <= 0.0 && !o.clip_complex_regions;
|
||||
let regions = if whole { vec![] } else { po::regions(&b.shapes) };
|
||||
// Nor does one that splits into more regions than the balance allows: the build stops at the
|
||||
// first region past the limit.
|
||||
let (regions, over) = match o.region_limit().filter(|_| !every_region()) {
|
||||
_ if whole => (vec![], false),
|
||||
Some(limit) => po::regions_within(&b.shapes, limit).map_or((vec![], true), |r| (r, false)),
|
||||
None => (po::regions(&b.shapes), false),
|
||||
};
|
||||
// An arrangement that failed (degenerate geometry) leaves only rasterizing.
|
||||
let all = regions.is_empty() || o.rasterize_all(regions.len());
|
||||
let all = over || regions.is_empty() || o.rasterize_all(regions.len());
|
||||
let mut vector: Vec<(usize, RegionFill)> = vec![];
|
||||
let mut complex: Vec<usize> = vec![];
|
||||
let mut gradients_only = !all;
|
||||
@@ -195,6 +201,32 @@ fn flatten_group(plain: &[&Node], o: &FlattenOptions, cmyk: bool) -> Option<(Reg
|
||||
Some((vector, area))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Groups flattened on this thread build all of their regions ([`with_every_region`]).
|
||||
static EVERY_REGION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Whether groups build all of their regions, past the balance's limit too.
|
||||
#[cfg(test)]
|
||||
fn every_region() -> bool {
|
||||
EVERY_REGION.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn every_region() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// `f` with every group it flattens building all of its regions, past the balance's limit too.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_every_region<T>(f: impl FnOnce() -> T) -> T {
|
||||
EVERY_REGION.with(|e| e.set(true));
|
||||
let out = f();
|
||||
EVERY_REGION.with(|e| e.set(false));
|
||||
out
|
||||
}
|
||||
|
||||
/// The flat colour of a region covered by `sources` (CMYK in a `cmyk` document); `None` where
|
||||
/// nothing paints it.
|
||||
fn region_fill(elems: &[Elem], sources: &[usize], o: &FlattenOptions, cmyk: bool) -> Option<RegionFill> {
|
||||
|
||||
@@ -169,9 +169,16 @@ impl FlattenOptions {
|
||||
}
|
||||
|
||||
/// Whether a group that splits into `regions` atomic regions is rasterized whole.
|
||||
pub(super) fn rasterize_all(&self, regions: usize) -> bool {
|
||||
pub(crate) fn rasterize_all(&self, regions: usize) -> bool {
|
||||
self.balance <= 0.0 || (self.balance < 100.0 && regions as f64 > 10f64.powf(self.balance / 20.0))
|
||||
}
|
||||
|
||||
/// The most atomic regions a group can split into without being rasterized whole, when a group
|
||||
/// with more needs none of its regions: `None` at a balance of 0 or 100, and with Clip Complex
|
||||
/// Regions (a group rasterized whole is clipped to all of its regions).
|
||||
pub(crate) fn region_limit(&self) -> Option<usize> {
|
||||
(!self.clip_complex_regions && self.balance > 0.0 && self.balance < 100.0).then(|| 10f64.powf(self.balance / 20.0).floor() as usize)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -92,8 +92,12 @@ impl Session {
|
||||
|
||||
/// The freeform gradient behind the Fill (`stroke` false) or Stroke proxy, its points in
|
||||
/// document coordinates, and the length its spreads are fractions of there (see
|
||||
/// [`Node::proxy_freeform`]).
|
||||
/// [`Node::proxy_freeform`]). `None` while an object of a symbol instance is selected
|
||||
/// ([`vectorcraft_doc::Selection::symbol_part`]): its points are in the symbol's coordinates.
|
||||
pub fn proxy_freeform(&self, stroke: bool) -> Option<(Freeform, f64)> {
|
||||
if self.active()?.selection.symbol_part.is_some() {
|
||||
return None;
|
||||
}
|
||||
let (n, item) = self.proxy_source(stroke)?;
|
||||
n.proxy_freeform(stroke, item)
|
||||
}
|
||||
|
||||
@@ -354,8 +354,10 @@ fn close(a: f64, b: f64) -> bool {
|
||||
}
|
||||
|
||||
/// The members a Global Edit started on the one selected object would take, with `o`: that
|
||||
/// object first, then the others in paint order.
|
||||
/// object first, then the others in paint order. Refused while an object of a dynamic symbol
|
||||
/// instance's art is selected.
|
||||
fn matches(s: &Session, o: &Options) -> Result<Vec<(NodeId, Affine)>> {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let [id] = st.selection.objects.as_slice() else { return Err(bad(C, "select one object")) };
|
||||
@@ -423,6 +425,7 @@ fn can_toggle(s: &Session) -> std::result::Result<(), String> {
|
||||
if st.global_edit.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
super::edit::no_symbol_part(s)?;
|
||||
let [id] = st.selection.objects.as_slice() else {
|
||||
return Err(if st.selection.is_empty() { "nothing selected" } else { "select one object" }.into());
|
||||
};
|
||||
@@ -765,10 +768,12 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
|
||||
let mut placed = model.clone();
|
||||
placed.transform(*xf * back, Scaling::default());
|
||||
give(was, &model, placed, &mut n, d);
|
||||
super::object::keep_pixel_aligned(&mut n, Scaling::default());
|
||||
if let Some(slot) = d.node_mut(*id) {
|
||||
*slot = n;
|
||||
edited.push(*id);
|
||||
}
|
||||
super::object::keep_compound_aligned(d, *id, Scaling::default());
|
||||
}
|
||||
edited
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Gradient Stop",
|
||||
[],
|
||||
None,
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on → {index}",
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected → {index}",
|
||||
always,
|
||||
select_stop
|
||||
),
|
||||
@@ -59,6 +59,10 @@ pub(crate) fn active_gradient(s: &Session) -> Option<GradientPaint> {
|
||||
|
||||
fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "gradient.selectStop";
|
||||
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
|
||||
if s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
None => return Err(bad(C, "missing `index` (a stop index, or null to clear)")),
|
||||
Some(Value::Null) => None,
|
||||
|
||||
@@ -42,7 +42,7 @@ use data::{fmt_value, parse_csv, to_csv};
|
||||
use generate::generate;
|
||||
#[cfg(test)]
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{capture_label_styles, capture_series_opacity, capture_series_paints, paint_targets};
|
||||
pub(crate) use series::{capture_label_styles, capture_series_opacity, capture_series_paints, capture_series_top_paints, paint_targets, shown_paint};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::Value;
|
||||
use super::{GraphSpec, Value};
|
||||
|
||||
pub(super) const LABEL_SIZE: f64 = 9.0;
|
||||
|
||||
@@ -32,6 +32,11 @@ pub(super) fn nice_axis(lo: f64, hi: f64, ticks: usize) -> (f64, f64, f64) {
|
||||
((lo / step).floor() * step, (hi / step).ceil() * step, step)
|
||||
}
|
||||
|
||||
/// The value axis of a radar graph: from 0 to the largest value of any series.
|
||||
pub(super) fn radar_axis(g: &GraphSpec) -> (f64, f64, f64) {
|
||||
value_axis(g.ticks, g.axis_min, g.axis_max, 0.0, g.rows.iter().flatten().copied().fold(0.0, f64::max))
|
||||
}
|
||||
|
||||
/// A value axis: with both `min` and `max` set (Graph Type › Tick Values › Override Calculated Values), exactly that
|
||||
/// range split into `ticks` divisions (5 when automatic); otherwise a nice axis around the data, using whichever bound
|
||||
/// was given.
|
||||
|
||||
@@ -58,12 +58,16 @@ pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The graph `id` names (or the graph containing it), else the selected graph (or the graph
|
||||
/// containing the selection).
|
||||
/// containing the selection). Refused while an object of a dynamic symbol instance's art is
|
||||
/// selected.
|
||||
pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let st = s.doc()?;
|
||||
let start = match named_id(p)? {
|
||||
Some(id) => vec![id],
|
||||
None => st.selection.objects.clone(),
|
||||
None => {
|
||||
crate::cmd::edit::refuse_symbol_part(s)?;
|
||||
st.selection.objects.clone()
|
||||
}
|
||||
};
|
||||
for id in start {
|
||||
let mut cur = Some(id);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::axis::{LABEL_SIZE, MAX_CATEGORY_TICKS, MAX_TICK_MARKS, one_line, tick_values, value_axis};
|
||||
use super::axis::{LABEL_SIZE, MAX_CATEGORY_TICKS, MAX_TICK_MARKS, one_line, radar_axis, tick_values, value_axis};
|
||||
use super::columns::{Allowance, ColumnArt, column_art, column_designs};
|
||||
use super::data::fmt_value;
|
||||
use super::labels::{
|
||||
FILLED_LINE_BUDGET, Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, label_size, label_width, polyline, recolour_text, runs, shadow_of,
|
||||
Gen, Role, SHADOW_BUDGET, SHADOW_OPACITY, blank_label, filled_lines_on, label_size, label_width, polyline, recolour_text, runs, shadow_of,
|
||||
};
|
||||
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
|
||||
use super::series::{series_marks, with_series_opacity};
|
||||
@@ -264,7 +264,7 @@ impl<'a> Plot<'a> {
|
||||
right_edge: g.rect.x1,
|
||||
wedge_labels: vec![],
|
||||
on_top: vec![],
|
||||
filled: g.filled_lines && g.rows.len().saturating_mul(nser) <= FILLED_LINE_BUDGET,
|
||||
filled: filled_lines_on(g, nser),
|
||||
bars_reach: None,
|
||||
shadowed: vec![],
|
||||
series: vec![vec![]; nser],
|
||||
@@ -422,7 +422,7 @@ impl<'a> Plot<'a> {
|
||||
let (g, r, ncat, cs) = (self.g, self.r, self.ncat, self.cs);
|
||||
let centre = r.center();
|
||||
let rad = (r.width().min(r.height()) / 2.0).max(1.0);
|
||||
let (lo, hi, step) = value_axis(g.ticks, g.axis_min, g.axis_max, 0.0, g.rows.iter().flatten().copied().fold(0.0, f64::max));
|
||||
let (lo, hi, step) = radar_axis(g);
|
||||
let at = |c: usize, v: f64| {
|
||||
let a = -std::f64::consts::FRAC_PI_2 + std::f64::consts::TAU * c as f64 / ncat as f64;
|
||||
centre + vectorcraft_geom::Vec2::new(a.cos(), a.sin()) * (rad * ((v - lo) / (hi - lo)).clamp(0.0, 1.0))
|
||||
|
||||
@@ -90,9 +90,10 @@ impl Gen<'_> {
|
||||
};
|
||||
// A run the outline can't be made for (its points all in one place) stays a thin line.
|
||||
if !band.is_empty() {
|
||||
// The band takes the series' colour, set as a fill or, on a thin line, as its stroke; a thin black outline.
|
||||
// The band takes the series' color, set as a fill or, on a thin line, as a stroke with paint; a thin black outline.
|
||||
let slot = g.series_paints.get(s);
|
||||
let fill = slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone())).unwrap_or_else(|| default_series_paint(s));
|
||||
let fill =
|
||||
slot.and_then(|p| p.fill.clone().or_else(|| p.stroke.clone().filter(|st| !st.is_none()))).unwrap_or_else(|| default_series_paint(s));
|
||||
return self.path(band, fill, Paint::solid(Color::BLACK), 0.25);
|
||||
}
|
||||
let (fill, stroke, w) = series_marks(g, s, false, default_series_paint(s), 1.0);
|
||||
@@ -140,7 +141,12 @@ pub(super) const SHADOW_OPACITY: f32 = 0.35;
|
||||
/// Draw Filled Lines: how wide a filled line is.
|
||||
const FILLED_LINE_WIDTH: f64 = 3.0;
|
||||
|
||||
pub(super) const FILLED_LINE_BUDGET: usize = 20_000;
|
||||
const FILLED_LINE_BUDGET: usize = 20_000;
|
||||
|
||||
/// Does graph `g`, with `series` series, draw Filled Lines (up to FILLED_LINE_BUDGET data points)?
|
||||
pub(super) fn filled_lines_on(g: &GraphSpec, series: usize) -> bool {
|
||||
g.filled_lines && g.rows.len().saturating_mul(series) <= FILLED_LINE_BUDGET
|
||||
}
|
||||
|
||||
/// Most marks a graph draws shadows for (each is a copy).
|
||||
pub(super) const SHADOW_BUDGET: usize = 200_000;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::labels::{Role, label_style};
|
||||
use super::axis::radar_axis;
|
||||
use super::labels::{Role, filled_lines_on, label_style};
|
||||
use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad};
|
||||
|
||||
// ---------- generation ----------
|
||||
@@ -121,11 +122,82 @@ pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bo
|
||||
let node = doc.node(*id)?;
|
||||
let paint = node.appearance.paint_at(None, fill)?.clone();
|
||||
let width = (!fill).then(|| node.appearance.stroke_width());
|
||||
Some((r.graph, r.index, paint, width))
|
||||
Some((r.graph, r.index, fill, paint, width))
|
||||
})
|
||||
.collect();
|
||||
store_series_paints(doc, captures)
|
||||
}
|
||||
|
||||
/// The paint of the topmost visible fill (`true`) or stroke (`false`) of `node`, and a stroke's weight (0 without paint).
|
||||
/// With no such row: no paint.
|
||||
pub(crate) fn shown_paint(node: &Node, fill: bool) -> (Paint, f64) {
|
||||
match node.appearance.items.iter().rev().find(|it| it.is_fill() == fill && it.visible()) {
|
||||
Some(vectorcraft_doc::AppearanceItem::Stroke(st)) if !st.paint.is_none() => (st.paint.clone(), st.width),
|
||||
Some(it) => (it.paint().clone(), 0.0),
|
||||
None => (Paint::None, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the paint of the topmost visible fill (`true`) or stroke (`false`), and a stroke's weight, of generated series
|
||||
/// art just edited (`edited`: each object with the kind of row, later entries replacing earlier ones) into that series'
|
||||
/// fill or stroke; art left without such a row keeps no paint. A series that draws Filled Lines bands stores no stroke: its
|
||||
/// bands keep their own outline. Called inside the same document edit, so both undo together. Returns whether a series'
|
||||
/// captured fill or stroke changed.
|
||||
pub(crate) fn capture_series_top_paints(doc: &mut Document, edited: &[(NodeId, bool)]) -> bool {
|
||||
if edited.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let members = series_members(doc);
|
||||
if members.is_empty() {
|
||||
return false;
|
||||
}
|
||||
// Each series is checked once: the check reads the graph's whole grid.
|
||||
let mut bands: HashMap<(NodeId, usize), bool> = HashMap::new();
|
||||
let mut captures = Vec::new();
|
||||
for (id, fill) in edited {
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
let Some(r) = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group)) else { continue };
|
||||
let Some(node) = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. })) else { continue };
|
||||
let drawn = || doc.node(r.graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| series_draws_bands(g, r.index));
|
||||
if !*fill && *bands.entry((r.graph, r.index)).or_insert_with(drawn) {
|
||||
continue;
|
||||
}
|
||||
let (paint, width) = shown_paint(node, *fill);
|
||||
captures.push((r.graph, r.index, *fill, paint, (!*fill).then_some(width)));
|
||||
}
|
||||
store_series_paints(doc, captures)
|
||||
}
|
||||
|
||||
/// Does series `i` draw any Filled Lines band? A line needs two neighboring values, a scatter series two neighboring points
|
||||
/// in different places (its index counts pairs of columns), and a radar series two categories with a value plotted away
|
||||
/// from the center.
|
||||
fn series_draws_bands(g: &GraphSpec, i: usize) -> bool {
|
||||
let series = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
|
||||
if !g.connect_points || !filled_lines_on(g, series) {
|
||||
return false;
|
||||
}
|
||||
let cells = g.cells();
|
||||
let cell = |row: &[Option<f64>], s: usize| row.get(s).copied().flatten();
|
||||
match g.series_kind(i) {
|
||||
GraphKind::Line => cells.windows(2).any(|w| w.iter().all(|row| cell(row, i).is_some())),
|
||||
GraphKind::Radar => {
|
||||
let (lo, hi, _) = radar_axis(g);
|
||||
cells.len() > 1 && cells.iter().any(|row| (cell(row, i).unwrap_or(0.0) - lo) / (hi - lo) > 0.0)
|
||||
}
|
||||
GraphKind::Scatter => {
|
||||
let s = i.saturating_mul(2);
|
||||
let point = |row: &[Option<f64>]| Some((cell(row, s)?, cell(row, s.saturating_add(1))?));
|
||||
cells.windows(2).any(|w| matches!(w, [a, b] if point(a).is_some() && point(b).is_some() && point(a) != point(b)))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Store each capture (graph, series index, fill or stroke, paint, stroke weight) in its series. Returns whether a
|
||||
/// series' captured fill or stroke changed.
|
||||
fn store_series_paints(doc: &mut Document, captures: Vec<(NodeId, usize, bool, Paint, Option<f64>)>) -> bool {
|
||||
let mut changed = false;
|
||||
for (graph, index, paint, width) in captures {
|
||||
for (graph, index, fill, paint, width) in captures {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
let was = spec.series_paints.clone();
|
||||
// `index` is below the graph's series count (`series_members`).
|
||||
@@ -144,7 +216,7 @@ pub(crate) fn capture_series_paints(doc: &mut Document, ids: &[NodeId], fill: bo
|
||||
changed
|
||||
}
|
||||
|
||||
/// Copy the opacity of the topmost fill (`true`) or stroke (`false`) of generated series art just edited (`edited`:
|
||||
/// Copy the opacity of the topmost visible fill (`true`) or stroke (`false`) of generated series art just edited (`edited`:
|
||||
/// each object with the kind of row) into that series' fill or stroke opacity; art left without a row of that kind
|
||||
/// keeps none. Called inside the same document edit, so both undo together. Returns whether a series' kept opacity
|
||||
/// changed.
|
||||
@@ -162,7 +234,8 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
|
||||
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
|
||||
let opacity = node.appearance.items.iter().rev().find(|it| it.is_fill() == *fill).map_or(1.0, vectorcraft_doc::AppearanceItem::opacity);
|
||||
let row = node.appearance.items.iter().rev().find(|it| it.is_fill() == *fill && it.visible());
|
||||
let opacity = row.map_or(1.0, vectorcraft_doc::AppearanceItem::opacity);
|
||||
Some((r.graph, r.index, *fill, (opacity < 1.0).then_some(opacity)))
|
||||
})
|
||||
.collect();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -76,8 +76,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
// ---------- predicates ----------
|
||||
|
||||
/// The Intertwine groups of the selection: selected ones, and those around a selected object.
|
||||
/// None while an object of a dynamic symbol instance's art is selected.
|
||||
fn selected_groups(s: &Session) -> Vec<NodeId> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
let group = st.doc.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| st.doc.node(*a).is_some_and(is_intertwine));
|
||||
@@ -92,6 +93,7 @@ fn selected_groups(s: &Session) -> Vec<NodeId> {
|
||||
|
||||
fn has_intertwine(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
super::edit::no_symbol_part(s)?;
|
||||
if selected_groups(s).is_empty() { Err("select an Intertwine group".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
@@ -378,11 +380,14 @@ fn arrange(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
id
|
||||
}
|
||||
None => match selected_groups(s).as_slice() {
|
||||
[g] => *g,
|
||||
[] => return Err(bad(C, "select an Intertwine group")),
|
||||
_ => return Err(bad(C, "select one Intertwine group")),
|
||||
},
|
||||
None => {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
match selected_groups(s).as_slice() {
|
||||
[g] => *g,
|
||||
[] => return Err(bad(C, "select an Intertwine group")),
|
||||
_ => return Err(bad(C, "select one Intertwine group")),
|
||||
}
|
||||
}
|
||||
};
|
||||
let at = match p.get("at") {
|
||||
Some(_) => Some(point_param(p, "at").filter(|q| q.x.is_finite() && q.y.is_finite()).ok_or_else(|| bad(C, "at must be [x, y]"))?),
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Artboard, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::{
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)",
|
||||
"{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the size of artboard `beside`, 20 pt from that side of it; refused with x, y, width or height), beside?: n (the artboard `side` places it by; default the last)} (default place: right of the last)",
|
||||
has_doc,
|
||||
artboard_new
|
||||
),
|
||||
@@ -869,6 +869,17 @@ fn artboard_str<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard command's `side` param: None when absent or null, else the side it names. Any other
|
||||
/// value is an error that names the four sides.
|
||||
pub(crate) fn artboard_side(p: &Value, cmd: &str) -> Result<Option<ArtboardSide>> {
|
||||
let bad_side = || bad(cmd, "`side` must be \"left\", \"right\", \"top\" or \"bottom\"");
|
||||
match p.get("side") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(v)) => ArtboardSide::parse(v).map(Some).ok_or_else(bad_side),
|
||||
Some(_) => Err(bad_side()),
|
||||
}
|
||||
}
|
||||
|
||||
/// An artboard command's `videoRulerPixelAspectRatio` param: None when absent, else a number within
|
||||
/// [`vectorcraft_doc::VIDEO_PIXEL_ASPECT_RANGE`].
|
||||
fn video_pixel_aspect(p: &Value, cmd: &str) -> Result<Option<f64>> {
|
||||
@@ -886,10 +897,24 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d0 = &s.doc()?.doc;
|
||||
let last = d0.artboards.last().map(|a| a.rect).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0));
|
||||
let def = Rect::new(last.x1 + 20.0, last.y0, last.x1 + 20.0 + last.width(), last.y1);
|
||||
let r = rect_from(p, def);
|
||||
let color = artboard_color(p, "artboard.new")?.flatten();
|
||||
check_switches(p, &["showCenterMark", "showCrossHairs", "showVideoSafeAreas"], "artboard.new")?;
|
||||
check_numbers(p, &["x", "y", "width", "height"], "artboard.new")?;
|
||||
let r = match artboard_side(p, "artboard.new")? {
|
||||
Some(side) => {
|
||||
if ["x", "y", "width", "height"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
return Err(bad("artboard.new", "`side` places the artboard: leave out x, y, width and height"));
|
||||
}
|
||||
let beside = match p.get("beside") {
|
||||
None | Some(Value::Null) => d0.artboards.len().saturating_sub(1),
|
||||
Some(_) => super::appearance::index_param(p, "beside", "artboard.new")?,
|
||||
};
|
||||
let src = d0.artboards.get(beside).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
src + side.offset(src)
|
||||
}
|
||||
None if p.get("beside").is_some_and(|v| !v.is_null()) => return Err(bad("artboard.new", "`beside` needs `side`")),
|
||||
None => rect_from(p, def),
|
||||
};
|
||||
let given = artboard_str(p, "name", "artboard.new")?.map(str::trim).filter(|n| !n.is_empty());
|
||||
let (show_center_mark, show_cross_hairs) = (bool_or(p, "showCenterMark", false), bool_or(p, "showCrossHairs", false));
|
||||
let show_video_safe_areas = bool_or(p, "showVideoSafeAreas", false);
|
||||
@@ -1100,6 +1125,7 @@ fn artboard_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &e.art {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(xf, sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
}
|
||||
} else if !e.resized {
|
||||
|
||||
@@ -10,7 +10,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::layer::{NewLayers, row_roots, rows_param};
|
||||
use super::{CommandSpec, Result, Session, bad, checked_id, cmd, has_doc, id_param, ok, switch_or};
|
||||
use super::{CommandSpec, Result, Session, bad, checked_id, cmd, has_doc, object_param, ok, switch_or};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -336,7 +336,7 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.releaseToLayers";
|
||||
let build = switch_or(p, "build", false, C)?;
|
||||
let st = s.doc()?;
|
||||
let id = match id_param(p, "id") {
|
||||
let id = match object_param(p, "id", C)? {
|
||||
Some(id) => id,
|
||||
None => match st.highlighted_rows().as_slice() {
|
||||
[id] => *id,
|
||||
@@ -434,8 +434,9 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn locate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = object_param(p, "id", "layer.locate")?;
|
||||
let st = s.doc_mut()?;
|
||||
let id = id_param(p, "id").or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?;
|
||||
let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![id];
|
||||
st.revision += 1;
|
||||
|
||||
+452
-83
@@ -24,14 +24,15 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::links::{Align, Preserve, hash_bytes};
|
||||
use vectorcraft_doc::{Appearance, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, PathData, Rect, shapes};
|
||||
|
||||
use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, id_param, ids_param, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -49,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Update Links",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. One undo step → {updated: [ids], missing: [ids]}",
|
||||
"{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. The images and placed documents inside symbols, graph designs, patterns and opacity masks that show the same content are read again too (by default also those only that art shows); they have no ids to list. One undo step → {updated: [ids], missing: [ids]}",
|
||||
has_doc,
|
||||
update
|
||||
),
|
||||
@@ -67,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Relink",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, copy?: false (with path, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy)}",
|
||||
"{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object in the layers linked to the same file as one of them) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy)}",
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
@@ -483,23 +484,183 @@ fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result<Read> {
|
||||
Ok(Read::Document(f.link(&bytes, &g.link), src))
|
||||
}
|
||||
|
||||
/// Objects `ids` show what was read (see [`install`], [`install_document`]).
|
||||
fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option<Preserve>) -> Result<()> {
|
||||
/// Objects `ids` show what was read (see [`install`], [`install_document`]), and with `also`, the
|
||||
/// objects outside the layer tree that show group `also`'s content.
|
||||
fn install_read(d: &mut Document, ids: &[NodeId], read: Read, force: Option<Preserve>, also: Option<&Group>) -> Result<()> {
|
||||
let also = also.map(|g| (g.link.path.as_str(), g.key.as_str()));
|
||||
match read {
|
||||
Read::Image(r) => install(d, ids, r, force),
|
||||
Read::Document(link, src) => install_document(d, ids, &link, &src, force),
|
||||
Read::Image(r) => install(d, ids, r, force, also),
|
||||
Read::Document(link, src) => install_document(d, ids, &link, &src, force, also),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a linked image (or, with `document`, a placed document) of the file at `path` showing
|
||||
/// content `key`?
|
||||
fn shows(n: &Node, (path, key): (&str, &str), document: bool) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) => !document && im.key == key && im.link.as_ref().is_some_and(|l| l.path == path),
|
||||
NodeKind::PlacedDocument(p) => document && p.key == key && p.link.path == path,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The clipping path of `clip`: its room as a rectangle in its frame.
|
||||
fn clip_shape((frame, room): Clip) -> PathData {
|
||||
shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame)
|
||||
}
|
||||
|
||||
/// Remakes the linked objects outside the layer tree (in symbols, graph designs, patterns and
|
||||
/// opacity masks, where [`Document::node`] finds no ids) that `pick` holds for.
|
||||
struct Nested<'a> {
|
||||
pick: &'a dyn Fn(&Node) -> bool,
|
||||
/// The object an object becomes, and the clip it takes ([`placed_xf`]).
|
||||
make: &'a mut dyn FnMut(&Node) -> (Node, Option<Clip>),
|
||||
/// The next node id for a clip group (taken from the document after the walk).
|
||||
next: u64,
|
||||
}
|
||||
|
||||
impl Nested<'_> {
|
||||
/// Every root of `d`: the layers (whose own objects are left alone), then the art of symbols,
|
||||
/// graph designs and patterns.
|
||||
fn run(mut self, d: &mut Document) {
|
||||
let first = d.peek_next_id();
|
||||
self.next = first;
|
||||
for l in d.layers.iter_mut() {
|
||||
self.update(l, false);
|
||||
}
|
||||
for root in d.symbols.iter_mut().map(|s| &mut s.art).chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) {
|
||||
self.root(root);
|
||||
}
|
||||
for root in d.patterns.iter_mut().flat_map(|p| &mut p.art) {
|
||||
self.root(root);
|
||||
}
|
||||
for _ in first..self.next {
|
||||
d.alloc_id();
|
||||
}
|
||||
}
|
||||
|
||||
/// The art at a root outside the layer tree (a symbol's, graph design's or pattern's art, or
|
||||
/// mask art).
|
||||
fn root(&mut self, n: &mut Arc<Node>) {
|
||||
if !(self.pick)(n) {
|
||||
return self.update(n, true);
|
||||
}
|
||||
let (new, clip) = (self.make)(n);
|
||||
let mut new = Arc::new(new);
|
||||
self.update(&mut new, true);
|
||||
*n = match clip {
|
||||
Some(clip) => Arc::new(self.clip_group(new, clip)),
|
||||
None => new,
|
||||
};
|
||||
}
|
||||
|
||||
/// `n` (outside the layer tree when `nested`) with the picked objects under it remade; it stays
|
||||
/// the same node when none is there, and only the nodes on the way to one are copied.
|
||||
fn update(&mut self, n: &mut Arc<Node>, nested: bool) {
|
||||
let mask = n.extras().mask.as_ref().and_then(|m| {
|
||||
let mut art = Arc::clone(&m.art);
|
||||
self.root(&mut art);
|
||||
(!Arc::ptr_eq(&art, &m.art)).then_some(art)
|
||||
});
|
||||
let mut slots: Vec<(usize, Arc<Node>)> = vec![];
|
||||
if let Some(children) = n.children() {
|
||||
// A clip group holding just the object: its clipping path changes.
|
||||
let clip_path = match (&n.kind, &children[..]) {
|
||||
(NodeKind::Group { clip: true, .. }, [c, _]) if matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c),
|
||||
_ => None,
|
||||
};
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if !(nested && (self.pick)(c)) {
|
||||
let mut new = Arc::clone(c);
|
||||
self.update(&mut new, nested);
|
||||
if !Arc::ptr_eq(&new, c) {
|
||||
slots.push((i, new));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (new, clip) = (self.make)(c);
|
||||
let mut new = Arc::new(new);
|
||||
self.update(&mut new, true);
|
||||
match (clip, clip_path) {
|
||||
(None, _) => slots.push((i, new)),
|
||||
(Some(clip), Some(path)) if i == 1 => {
|
||||
let mut path = Node::clone(path);
|
||||
if let NodeKind::Path { path: p, .. } = &mut path.kind {
|
||||
*p = clip_shape(clip);
|
||||
}
|
||||
slots.extend([(0, Arc::new(path)), (1, new)]);
|
||||
}
|
||||
(Some(clip), _) => {
|
||||
let group = self.clip_group(new, clip);
|
||||
slots.push((i, Arc::new(group)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if mask.is_none() && slots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = Arc::make_mut(n);
|
||||
if let (Some(art), Some(m)) = (mask, n.extras_if_any().and_then(|e| e.mask.as_mut())) {
|
||||
m.art = art;
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for (i, c) in slots {
|
||||
if let Some(slot) = children.get_mut(i) {
|
||||
*slot = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip group of `object` clipped to `clip`, as [`clip_image`] makes one in the layers.
|
||||
fn clip_group(&mut self, object: Arc<Node>, clip: Clip) -> Node {
|
||||
let (path_id, group_id) = (NodeId(self.next), NodeId(self.next + 1));
|
||||
self.next += 2;
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut path = Node::path(path_id, clip_shape(clip), Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
Node::new(group_id, NodeKind::Group { children: vec![Arc::new(path), object], clip: true })
|
||||
}
|
||||
}
|
||||
|
||||
/// Placed documents `ids` show `src`, read from the file `link` points at, each placed as its
|
||||
/// Placement Options say (`force`: as that Preserve choice says, whatever they say).
|
||||
fn install_document(d: &mut Document, ids: &[NodeId], link: &LinkInfo, src: &super::place::document::Source, force: Option<Preserve>) -> Result<()> {
|
||||
/// Placement Options say (`force`: as that Preserve choice says, whatever they say); with `also`
|
||||
/// (a file's path and the content shown), so do the placed documents outside the layer tree that
|
||||
/// show that content.
|
||||
fn install_document(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
link: &LinkInfo,
|
||||
src: &super::place::document::Source,
|
||||
force: Option<Preserve>,
|
||||
also: Option<(&str, &str)>,
|
||||
) -> Result<()> {
|
||||
let mut clips = vec![];
|
||||
let (w, h) = (src.frame.width(), src.frame.height());
|
||||
let placed = |p: &PlacedDocument| {
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
|
||||
placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o)
|
||||
};
|
||||
if let Some(also) = also {
|
||||
let pick = |n: &Node| shows(n, also, true);
|
||||
let mut make = |n: &Node| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = None;
|
||||
if let NodeKind::PlacedDocument(p) = &mut n.kind {
|
||||
let (xf, c) = placed(p);
|
||||
(p.key, p.width, p.height, p.xf, p.link) = (src.key.clone(), w, h, xf, link.clone());
|
||||
clip = c;
|
||||
}
|
||||
(n, clip)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
for id in ids {
|
||||
let Some(NodeKind::PlacedDocument(p)) = d.node(*id).map(|n| &n.kind) else { continue };
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(p.placement.preserve), ..p.placement };
|
||||
let (xf, clip) = placed_xf(p.xf, (p.width, p.height), (1.0, 1.0), (w, h), (1.0, 1.0), o);
|
||||
let (xf, clip) = placed(p);
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::PlacedDocument(p) = &mut n.kind
|
||||
{
|
||||
@@ -565,8 +726,8 @@ fn placed_xf(xf: Affine, old: (f64, f64), old_pt: (f64, f64), new: (f64, f64), n
|
||||
|
||||
/// Clip image `id` of `d` to `room` in `frame`: the clipping path of the clip group holding just
|
||||
/// it changes, else the image goes into a new clip group.
|
||||
fn clip_image(d: &mut Document, id: NodeId, (frame, room): Clip) -> Result<()> {
|
||||
let path = shapes::rectangle(Rect::new(0.0, 0.0, room.0, room.1)).transformed(frame);
|
||||
fn clip_image(d: &mut Document, id: NodeId, clip: Clip) -> Result<()> {
|
||||
let path = clip_shape(clip);
|
||||
let clip_path = d.parent_of(id).and_then(|p| match &d.node(p)?.kind {
|
||||
NodeKind::Group { children, clip: true } => match &children[..] {
|
||||
[c, im] if im.id == id && matches!(c.kind, NodeKind::Path { clipping: true, .. }) => Some(c.id),
|
||||
@@ -602,14 +763,33 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
let path = fileio::document_path(path, doc_path).map_err(|r| EngineError::Other(format!("the image `{path}` isn't followed: {r}")))?;
|
||||
let bytes = read_file(&path)?;
|
||||
let read = (link_info(&path, &bytes), linked_image(&bytes)?);
|
||||
install(d, &[id], read, Some(Preserve::Bounds))
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// Image objects `ids` show the file read for `link` (`img`), each placed as its Placement
|
||||
/// Options say (`force`: as that Preserve choice says, whatever they say).
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>) -> Result<()> {
|
||||
/// Options say (`force`: as that Preserve choice says, whatever they say); with `also` (a file's
|
||||
/// path and the content shown), so do the images outside the layer tree that show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
let new_pt = super::place::pt_per_px(img.ppi);
|
||||
let mut clips = vec![];
|
||||
if let Some(also) = also {
|
||||
// Every image picked shows content `also.1`, so one resolution serves them all.
|
||||
let old_pt = file_pt(d, also.1);
|
||||
let pick = |n: &Node| shows(n, also, false);
|
||||
let mut make = |n: &Node| {
|
||||
let mut n = n.clone();
|
||||
let mut clip = None;
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
let size = |w: u32, h: u32| (w as f64, h as f64);
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
clip = c;
|
||||
}
|
||||
(n, clip)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
for id in ids {
|
||||
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
|
||||
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
|
||||
@@ -669,23 +849,32 @@ impl Resolved {
|
||||
|
||||
/// The linked files of document `d`, just read from `doc_path`: those found unchanged are read
|
||||
/// again (their images had the preview), modified ones are read again when `update`, links found
|
||||
/// away from their path take the new path. A link nothing is known of whose image shows a preview
|
||||
/// (a file another app wrote kept only that) was never read: its file is read now, into the
|
||||
/// image's bounds, which isn't a change to report. Nothing here is an undo step.
|
||||
/// away from their path take the new path. A link nothing is known of whose image, or placed
|
||||
/// document, shows a preview (a file another app wrote kept only that) was never read: its file is
|
||||
/// read now, into the object's bounds, which isn't a change to report. A placed document whose
|
||||
/// file's bytes are gone isn't showing a preview. Nothing here is an undo step.
|
||||
pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_proxy_eps: bool) -> Resolved {
|
||||
let mut out = Resolved::default();
|
||||
// The image (with its preview) and hash of each file read for a preview here, by path: images
|
||||
// of other keys linking to the same file share them, rather than each reading, decoding and
|
||||
// keeping a copy of its own.
|
||||
let mut read_images: BTreeMap<String, (ImageBlob, String)> = BTreeMap::new();
|
||||
// (the path as it was, the content shown, a placed document?, the link now) of each file found
|
||||
// away from its path or read again.
|
||||
let mut moved: Vec<(String, String, bool, LinkInfo)> = vec![];
|
||||
for g in groups(d, None) {
|
||||
let row = rows(std::iter::once(&g), doc_path);
|
||||
let unread = g.document.is_none() && g.link.hash.is_none() && g.link.size.is_none() && previewing(d, &g.key);
|
||||
let shows_preview = match g.document {
|
||||
None => previewing(d, &g.key),
|
||||
Some(_) => d.images.get(&g.key).is_some_and(ImageBlob::is_proxy),
|
||||
};
|
||||
let unread = g.link.hash.is_none() && g.link.size.is_none() && shows_preview;
|
||||
let eps_preview = keep_eps_preview(low_res_proxy_eps, &g, d);
|
||||
match probe(&g, doc_path) {
|
||||
(Status::Missing, _) => out.missing.extend(row),
|
||||
(Status::Modified, Some(mut f)) if update || unread => {
|
||||
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, unread.then_some(Preserve::Bounds))) {
|
||||
let force = unread.then_some(Preserve::Bounds);
|
||||
match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) {
|
||||
Ok(()) if unread => {}
|
||||
Ok(()) => out.updated.extend(row),
|
||||
Err(_) => out.missing.extend(row),
|
||||
@@ -697,7 +886,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
|
||||
let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None };
|
||||
match read {
|
||||
Some(Ok(read)) => {
|
||||
if install_read(d, &g.ids, read, Some(Preserve::Bounds)).is_err() {
|
||||
if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() {
|
||||
out.missing.extend(row);
|
||||
}
|
||||
}
|
||||
@@ -709,6 +898,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
|
||||
};
|
||||
if link != g.link {
|
||||
set_links(d, &g.ids, &link);
|
||||
moved.push((g.link.path.clone(), g.key.clone(), true, link));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -720,6 +910,7 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
|
||||
let link = f.link_hashed(hash, &g.link);
|
||||
if link != g.link {
|
||||
set_links(d, &g.ids, &link);
|
||||
moved.push((g.link.path.clone(), g.key.clone(), false, link));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -745,11 +936,34 @@ pub fn resolve(d: &mut Document, doc_path: Option<&str>, update: bool, low_res_p
|
||||
};
|
||||
if link != g.link {
|
||||
set_links(d, &g.ids, &link);
|
||||
moved.push((g.link.path.clone(), g.key.clone(), false, link));
|
||||
}
|
||||
}
|
||||
(Status::Ok, None) => {}
|
||||
}
|
||||
}
|
||||
// The objects in symbols, graph designs, patterns and opacity masks that show the same file and
|
||||
// content, which have no ids here, whatever else their links hold.
|
||||
if !moved.is_empty() {
|
||||
let mut by_path: BTreeMap<String, Vec<(String, bool, LinkInfo)>> = BTreeMap::new();
|
||||
for (path, key, document, new) in moved {
|
||||
by_path.entry(path).or_default().push((key, document, new));
|
||||
}
|
||||
let new = |n: &Node| {
|
||||
let (l, key, document) = linked(n)?;
|
||||
let m = by_path.get(&l.path)?;
|
||||
m.iter().find(|(k, doc, _)| k == key && *doc == document.is_some()).map(|(_, _, new)| new)
|
||||
};
|
||||
let pick = |n: &Node| new(n).is_some();
|
||||
let mut make = |n: &Node| {
|
||||
let mut out = n.clone();
|
||||
if let (Some(link), Some(l)) = (new(n), link_mut(&mut out)) {
|
||||
*l = link.clone();
|
||||
}
|
||||
(out, None)
|
||||
};
|
||||
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -772,35 +986,31 @@ fn set_links(d: &mut Document, ids: &[NodeId], link: &LinkInfo) {
|
||||
}
|
||||
|
||||
/// Placed documents of the document saved at `path` (document `saved` of `s`) in the other open
|
||||
/// documents: read again from the new file, each as one Update Links step of its document.
|
||||
/// documents, in the layers, symbols, graph designs, patterns and opacity masks: read again from
|
||||
/// the new file, each as one Update Links step of its document.
|
||||
pub(crate) fn refresh_placed(s: &mut Session, saved: u64, path: &str) {
|
||||
let path = absolute_path(path);
|
||||
let targets: Vec<(usize, Vec<u64>)> = s
|
||||
let targets: Vec<usize> = s
|
||||
.documents()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, st)| st.uid != saved)
|
||||
.filter_map(|(i, st)| {
|
||||
let mut ids = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if let NodeKind::PlacedDocument(p) = &n.kind
|
||||
&& p.link.path == path
|
||||
{
|
||||
ids.push(n.id.0);
|
||||
}
|
||||
});
|
||||
(!ids.is_empty()).then_some((i, ids))
|
||||
.filter(|(_, st)| {
|
||||
let mut placed = false;
|
||||
st.doc.visit_placed(|_, p| placed |= p.link.path == path);
|
||||
placed
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Each document is updated as the active one, without switching tools.
|
||||
let back = s.active;
|
||||
for (i, ids) in targets {
|
||||
for i in targets {
|
||||
s.active = Some(i);
|
||||
// A file that can't be read leaves what its objects show: links.check reports it.
|
||||
let _ = update(s, &json!({ "ids": ids }));
|
||||
let _ = update_where(s, None, Some(&path));
|
||||
}
|
||||
s.active = back;
|
||||
}
|
||||
@@ -826,31 +1036,45 @@ fn relative_path(target: &Path, base: &Path) -> Option<String> {
|
||||
}
|
||||
|
||||
/// `d` as saved to `dest`: the links' paths relative to its folder written in; `None` when they
|
||||
/// are already.
|
||||
/// are already. Links in the layers, symbols, graph designs, patterns and opacity masks are all set.
|
||||
pub fn with_relative_paths(d: &Document, dest: &str) -> Option<Document> {
|
||||
let dest = absolute_path(dest);
|
||||
let dir = Path::new(&dest).parent()?;
|
||||
let mut changes = vec![];
|
||||
d.walk(|n| {
|
||||
if let Some((l, _, _)) = linked(n) {
|
||||
let r = relative_path(Path::new(&l.path), dir);
|
||||
if r != l.relative {
|
||||
changes.push((n.id, r));
|
||||
}
|
||||
}
|
||||
});
|
||||
if changes.is_empty() {
|
||||
let relative = |l: &LinkInfo| relative_path(Path::new(&l.path), dir);
|
||||
let outdated = |l: &LinkInfo| relative(l) != l.relative;
|
||||
let mut changed = false;
|
||||
d.visit_images(|_, im| changed |= im.link.as_ref().is_some_and(outdated));
|
||||
d.visit_placed(|_, p| changed |= outdated(&p.link));
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut d = d.clone();
|
||||
for (id, r) in changes {
|
||||
if let Some(l) = d.node_mut(id).and_then(link_mut) {
|
||||
l.relative = r;
|
||||
}
|
||||
}
|
||||
d.update_links_where(outdated, |l| l.relative = relative(l));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Sets each link of `d`, a copy of the document saved at `doc_path` that has no file of its own,
|
||||
/// to the path where that document finds its file, so the copy finds the same files.
|
||||
/// Links in the layers, symbols, graph designs, patterns and opacity masks are all set.
|
||||
pub(crate) fn with_found_paths(d: &mut Document, doc_path: &str) {
|
||||
// The new path of each link by what `locate` reads of it: its path, relative path and name.
|
||||
let mut found: BTreeMap<(String, Option<String>), Option<String>> = BTreeMap::new();
|
||||
let mut look = |l: &LinkInfo| {
|
||||
found.entry((l.path.clone(), l.relative.clone())).or_insert_with(|| locate(l, Some(doc_path)).map(|f| f.path));
|
||||
};
|
||||
d.visit_images(|_, im| im.link.iter().for_each(&mut look));
|
||||
d.visit_placed(|_, p| look(&p.link));
|
||||
found.retain(|(path, _), f| f.as_ref().is_some_and(|f| f != path));
|
||||
if found.is_empty() {
|
||||
return;
|
||||
}
|
||||
d.update_links(|l| {
|
||||
if let Some(Some(f)) = found.get(&(l.path.clone(), l.relative.clone())) {
|
||||
l.path = f.clone();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -876,28 +1100,92 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
update_where(s, ids_param(p, "ids"), None)
|
||||
}
|
||||
|
||||
/// Update Links in the active document of `s` for objects `ids` (default: the linked files that
|
||||
/// changed or show their preview), or with `path`, for the placed documents of the file at `path`
|
||||
/// whatever their status. The objects in symbols, graph designs, patterns and opacity masks that
|
||||
/// show the same content are read again too, and have no ids to report.
|
||||
fn update_where(s: &mut Session, ids: Option<Vec<NodeId>>, path: Option<&str>) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let ids = ids_param(p, "ids");
|
||||
let (mut reads, mut missing) = (vec![], vec![]);
|
||||
for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| !g.ids.is_empty()) {
|
||||
let asked = ids.is_some() || path.is_some();
|
||||
for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) {
|
||||
match probe(&g, st.path.as_deref()) {
|
||||
(Status::Missing, _) | (_, None) => missing.extend(ids_json(&g.ids)),
|
||||
// Unchanged and showing the file: nothing to read unless asked for by id.
|
||||
(Status::Ok, Some(_)) if ids.is_none() && !stale(&st.doc, &g) => {}
|
||||
// Unchanged and showing the file: nothing to read unless asked for.
|
||||
(Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {}
|
||||
// Unreadable as an image (or a document) counts as missing.
|
||||
(_, Some(mut f)) => match read_for(&mut f, &g, "links.update") {
|
||||
Ok(read) => reads.push((g.ids, read)),
|
||||
Ok(read) => reads.push((g, read)),
|
||||
Err(_) => missing.extend(ids_json(&g.ids)),
|
||||
},
|
||||
}
|
||||
}
|
||||
let updated: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
|
||||
let updated: Vec<u64> = reads.iter().flat_map(|(g, _)| ids_json(&g.ids)).collect();
|
||||
if !reads.is_empty() {
|
||||
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, None)))?;
|
||||
s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(g, read)| install_read(d, &g.ids, read, None, Some(&g))))?;
|
||||
}
|
||||
Ok(json!({ "updated": updated, "missing": missing }))
|
||||
}
|
||||
|
||||
/// Which links `links.relink` points at the new file (the Replace choice of Relink).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Scope {
|
||||
/// Each link its own file (`paths`).
|
||||
Each,
|
||||
/// The objects given or selected.
|
||||
Selected,
|
||||
/// Every object in the layers linked to the same file as one given or selected.
|
||||
All,
|
||||
/// The objects given or selected, then every other missing link whose file name is in the new
|
||||
/// file's folder.
|
||||
MissingInFolder,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
fn from_id(id: &str) -> Option<Self> {
|
||||
match id {
|
||||
"each" => Some(Scope::Each),
|
||||
"selected" => Some(Scope::Selected),
|
||||
"all" => Some(Scope::All),
|
||||
"missingInFolder" => Some(Scope::MissingInFolder),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for `scope` and `paths` given one without the other, or `paths` beside ids, path or
|
||||
/// folder.
|
||||
fn each_mismatch(cmd: &str) -> EngineError {
|
||||
bad(cmd, "scope each and paths go together: paths lists entries of ids and path, in place of ids, path and folder")
|
||||
}
|
||||
|
||||
/// `links.relink {scope: "each", paths}`: each entry's ids with its absolute file, entries naming
|
||||
/// one file merged. A malformed entry, an id in two entries or an empty list is an error.
|
||||
fn each_paths(p: &Value, cmd: &str) -> Result<Vec<(Vec<NodeId>, String)>> {
|
||||
let entries = p.get("paths").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(|| each_mismatch(cmd))?;
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out: Vec<(Vec<NodeId>, String)> = vec![];
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let malformed = || bad(cmd, format!("paths entry {i} needs path and ids (object ids no other entry has)"));
|
||||
let path = e.get("path").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(malformed)?;
|
||||
let ids = e.get("ids").and_then(Value::as_array).filter(|a| !a.is_empty()).ok_or_else(malformed)?;
|
||||
let mut these = vec![];
|
||||
for v in ids {
|
||||
let id = v.as_u64().map(NodeId).filter(|id| seen.insert(*id)).ok_or_else(malformed)?;
|
||||
these.push(id);
|
||||
}
|
||||
let path = absolute_path(path);
|
||||
match out.iter_mut().find(|(_, p)| *p == path) {
|
||||
Some((ids, _)) => ids.extend(these),
|
||||
None => out.push((these, path)),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.relink";
|
||||
// How the new file takes the image's place this time (default: its Placement Options).
|
||||
@@ -905,13 +1193,26 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => None,
|
||||
Some(v) => Some(Preserve::from_id(v).ok_or_else(|| bad(C, format!("preserve `{v}` is not transforms|bounds|fileDimensions|fit|fill")))?),
|
||||
};
|
||||
let scope = match p.get("scope").filter(|v| !v.is_null()) {
|
||||
None => Scope::Selected,
|
||||
Some(v) => v.as_str().and_then(Scope::from_id).ok_or_else(|| bad(C, format!("scope {v} is not each|selected|all|missingInFolder")))?,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let folder_param = str_param(p, "folder");
|
||||
match scope {
|
||||
Scope::Each if p.get("path").is_some() || folder_param.is_some() || p.get("ids").is_some() => return Err(each_mismatch(C)),
|
||||
Scope::Selected | Scope::All | Scope::MissingInFolder if p.get("paths").is_some() => return Err(each_mismatch(C)),
|
||||
Scope::MissingInFolder if folder_param.is_some() => {
|
||||
return Err(bad(C, "scope missingInFolder takes path: the folder of that file is searched for the other missing links"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let each = if scope == Scope::Each { Some(each_paths(p, C)?) } else { None };
|
||||
// With copy: the saved document's folder, which the file is copied into.
|
||||
let copy_to = match (bool_or(p, "copy", false), str_param(p, "path")) {
|
||||
let copy_to = match (bool_or(p, "copy", false), str_param(p, "path").is_some() || each.is_some()) {
|
||||
(false, _) => None,
|
||||
(true, None) => return Err(bad(C, "copy needs path: the file to copy into the document's folder")),
|
||||
(true, Some(_)) => {
|
||||
(true, false) => return Err(bad(C, "copy needs path: the file to copy into the document's folder")),
|
||||
(true, true) => {
|
||||
let doc = st.path.as_deref().map(absolute_path).ok_or_else(|| bad(C, "save the document first: copy puts the file in its folder"))?;
|
||||
Some(Path::new(&doc).parent().map(Path::to_path_buf).ok_or_else(|| bad(C, format!("{doc} has no folder")))?)
|
||||
}
|
||||
@@ -924,9 +1225,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let ids: Vec<NodeId> = match ids_param(p, "ids") {
|
||||
Some(ids) => ids,
|
||||
None => {
|
||||
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids")) {
|
||||
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
|
||||
(None, Some(ids)) => ids,
|
||||
(None, None) => {
|
||||
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
|
||||
match folder_param {
|
||||
Some(_) if selected.is_empty() => {
|
||||
@@ -942,15 +1244,37 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select the images to relink, or pass ids"));
|
||||
}
|
||||
// All Instances: the other objects in the layers linked to the same files.
|
||||
if scope == Scope::All {
|
||||
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
|
||||
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
let mut more = vec![];
|
||||
st.doc.walk(|n| {
|
||||
if let Some((l, _, _)) = linked(n)
|
||||
&& paths.contains(l.path.as_str())
|
||||
&& !given.contains(&n.id)
|
||||
{
|
||||
more.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.extend(more);
|
||||
}
|
||||
if copy_to.is_some() && ids.iter().any(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::PlacedDocument(_)))) {
|
||||
return Err(bad(C, "copy takes images only: relink placed documents where their files are"));
|
||||
}
|
||||
// (ids, the file) per file to read.
|
||||
let mut files: Vec<(Vec<NodeId>, String)> = vec![];
|
||||
let mut not_found = vec![];
|
||||
match (str_param(p, "path"), folder_param) {
|
||||
(Some(path), _) => files.push((ids, absolute_path(path))),
|
||||
(None, Some(dir)) => {
|
||||
match (each, str_param(p, "path"), folder_param) {
|
||||
(Some(each), _, _) => files = each,
|
||||
(None, Some(path), _) if scope == Scope::MissingInFolder => {
|
||||
let path = absolute_path(path);
|
||||
let given: BTreeSet<NodeId> = ids.iter().copied().collect();
|
||||
files.push((ids, path));
|
||||
missing_in_folder(st, &given, copy_to.is_some(), &mut files, &mut not_found);
|
||||
}
|
||||
(None, Some(path), _) => files.push((ids, absolute_path(path))),
|
||||
(None, None, Some(dir)) => {
|
||||
for id in ids {
|
||||
let Some(link) = image(&id).flatten() else { continue };
|
||||
let path = absolute_path(&Path::new(dir).join(link.name()).to_string_lossy());
|
||||
@@ -961,10 +1285,10 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
(None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
|
||||
}
|
||||
let mut reads = vec![];
|
||||
let (mut copied, mut kept) = (vec![], vec![]);
|
||||
// Every file is read and checked before any is copied.
|
||||
let mut checked = vec![];
|
||||
for (ids, path) in files {
|
||||
let bytes = read_file(&path)?;
|
||||
// Images show the file; placed documents each show their artboard or page of it.
|
||||
@@ -988,20 +1312,28 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for ((page, bounding, page_box), ids) in documents {
|
||||
sources.push((page, ids, super::place::document::source(&path, &bytes, Some(&path), page, bounding, page_box, C)?));
|
||||
}
|
||||
let to = match ©_to {
|
||||
Some(dir) => {
|
||||
let (to, new) = copy_into_folder(&path, &bytes, dir)?;
|
||||
// The bytes are kept only to be copied, the file as it was checked.
|
||||
let link = link_info(&path, &bytes);
|
||||
let bytes = copy_to.is_some().then_some(bytes);
|
||||
checked.push((path, link, bytes, images, img, sources));
|
||||
}
|
||||
let mut reads = vec![];
|
||||
let (mut copied, mut kept): (Vec<Value>, Vec<Value>) = (vec![], vec![]);
|
||||
for (path, link, bytes, images, img, sources) in checked {
|
||||
let link = match (©_to, bytes) {
|
||||
(Some(dir), Some(bytes)) => {
|
||||
let (to, new) = copy_or_remove(&path, &bytes, dir, &copied)?;
|
||||
let link = link_info(&to, &bytes);
|
||||
let pair = json!({ "from": path, "to": to });
|
||||
if new {
|
||||
copied.push(pair)
|
||||
} else {
|
||||
kept.push(pair)
|
||||
}
|
||||
to
|
||||
link
|
||||
}
|
||||
None => path,
|
||||
_ => link,
|
||||
};
|
||||
let link = link_info(&to, &bytes);
|
||||
if let Some(img) = img {
|
||||
reads.push((images, Read::Image((link.clone(), img))));
|
||||
}
|
||||
@@ -1011,7 +1343,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let relinked: Vec<u64> = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect();
|
||||
if !reads.is_empty() {
|
||||
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve)))?;
|
||||
s.edit("Relink", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None)))?;
|
||||
}
|
||||
not_found.sort();
|
||||
not_found.dedup();
|
||||
@@ -1023,6 +1355,41 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only
|
||||
/// images when `images_only`, as copy takes), each added to `files` with the file of its name in
|
||||
/// the folder of the first file there; names not there go to `not_found`.
|
||||
fn missing_in_folder(
|
||||
st: &crate::DocState,
|
||||
given: &BTreeSet<NodeId>,
|
||||
images_only: bool,
|
||||
files: &mut Vec<(Vec<NodeId>, String)>,
|
||||
not_found: &mut Vec<String>,
|
||||
) {
|
||||
let Some(dir) = files.first().and_then(|(_, p)| Path::new(p).parent()).map(Path::to_path_buf) else { return };
|
||||
for g in groups(&st.doc, None).into_iter().filter(|g| !(images_only && g.document.is_some())) {
|
||||
let rest: Vec<NodeId> = g.ids.iter().copied().filter(|id| !given.contains(id)).collect();
|
||||
if rest.is_empty() || probe(&g, st.path.as_deref()).0 != Status::Missing {
|
||||
continue;
|
||||
}
|
||||
let found = absolute_path(&dir.join(g.link.name()).to_string_lossy());
|
||||
match files.iter_mut().find(|(_, p)| *p == found) {
|
||||
Some((ids, _)) => ids.extend(rest),
|
||||
None if file_stamp(&found).is_some() => files.push((rest, found)),
|
||||
None => not_found.push(g.link.name().to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`copy_into_folder`]; when it fails, the copies `copied` (`{from, to}`) the same call made
|
||||
/// before are removed, since nothing is relinked.
|
||||
fn copy_or_remove(from: &str, bytes: &[u8], dir: &Path, copied: &[Value]) -> Result<(String, bool)> {
|
||||
copy_into_folder(from, bytes, dir).inspect_err(|_| {
|
||||
for to in copied.iter().filter_map(|pair| pair.get("to").and_then(Value::as_str)) {
|
||||
let _ = std::fs::remove_file(to);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `links.relink {copy}`: put the file at `from` (`bytes`, as just read) into the folder `dir`,
|
||||
/// never replacing a file there ([`fileio::copy_new`]) → where it is now, and whether it was
|
||||
/// copied (`false`: a file there with the same contents, of its name or a numbered one, is used).
|
||||
@@ -1071,7 +1438,9 @@ fn selected_images(st: &crate::DocState, keep: impl Fn(&ImageObject) -> bool) ->
|
||||
|
||||
/// `id`, else the first selected image.
|
||||
fn image_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = id_param(p, "id").or_else(|| selected_images(st, |_| true).first().copied()).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
let id = object_param(p, "id", cmd)?
|
||||
.or_else(|| selected_images(st, |_| true).first().copied())
|
||||
.ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match image_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
@@ -1100,7 +1469,7 @@ fn placement_of(d: &Document, id: NodeId) -> Option<PlacementOptions> {
|
||||
/// `id`, else the first selected image or placed document.
|
||||
fn linked_param(st: &crate::DocState, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let first = || st.selection.objects.iter().copied().find(|id| placement_of(&st.doc, *id).is_some());
|
||||
let id = id_param(p, "id").or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
let id = object_param(p, "id", cmd)?.or_else(first).ok_or_else(|| bad(cmd, "select an image, or pass id"))?;
|
||||
match placement_of(&st.doc, id) {
|
||||
Some(_) => Ok(id),
|
||||
None if st.doc.node(id).is_none() => Err(crate::EngineError::NoNode(id)),
|
||||
@@ -1270,7 +1639,7 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !done.is_empty() || !documents.is_empty() {
|
||||
s.edit("Embed", |d, _| {
|
||||
for (ids, read) in reads {
|
||||
install(d, &ids, read, Some(Preserve::Bounds))?;
|
||||
install(d, &ids, read, Some(Preserve::Bounds), None)?;
|
||||
}
|
||||
for id in &done {
|
||||
if let Some(Node { kind: NodeKind::Image(im), .. }) = d.node_mut(*id) {
|
||||
@@ -1327,7 +1696,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let img = linked_image(&bytes)?;
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds)))?;
|
||||
s.edit("Unembed", |d, _| install(d, &[id], read, Some(Preserve::Bounds), None))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
|
||||
@@ -20,8 +20,8 @@ use super::edit::selected_roots;
|
||||
use super::expand::gradient_sampler;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers,
|
||||
has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi,
|
||||
has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
mod blend;
|
||||
|
||||
@@ -7,7 +7,7 @@ use super::common::{
|
||||
use super::mesh::index_param;
|
||||
use super::{
|
||||
Affine, Anchor, Appearance, Arc, Beside, BlendDefaults, BlendOrientation, BlendSpacing, BlendSpec, Document, EngineError, Node, NodeId, NodeKind,
|
||||
Paint, PathData, Point, Result, Session, Spine, Value, Vec2, bad, f64_req, id_param, json, live, number_or, ok, str_param, switch_or,
|
||||
Paint, PathData, Point, Result, Session, Spine, Value, Vec2, bad, f64_req, json, live, number_or, ok, str_param, switch_or,
|
||||
};
|
||||
|
||||
/// The first blend among `roots`.
|
||||
@@ -160,7 +160,7 @@ fn edit_spine<T>(
|
||||
label: &str,
|
||||
f: impl FnOnce(&mut vectorcraft_geom::SubPath, &mut Vec<usize>, &mut [Arc<Node>]) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let id = match id_param(p, "id") {
|
||||
let id = match crate::cmd::object_param(p, "id", cmd)? {
|
||||
Some(id) => id,
|
||||
None => *selected_of(s, is_blend).first().ok_or_else(|| bad(cmd, "select a blend or give `id`"))?,
|
||||
};
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Warp…",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+Shift+W"),
|
||||
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected) → {id}",
|
||||
"{ids?, style?: arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist (arc), bend?: % -100..100 (50), h?: horizontal distortion % -100..100 (0), v?: vertical distortion % (0), horizontal?: bool (true) | orientation?: horizontal|vertical, horizontalDistortion?: as h, verticalDistortion?: as v} envelope the selected objects with a warp (Envelope Options from object.envelope.options with nothing selected; type maps from its glyph outline bounds) → {id}",
|
||||
has_selection,
|
||||
env_make_warp
|
||||
),
|
||||
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Mesh…",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+M"),
|
||||
"{ids?, rows?: 1..50 (4), cols?: 1..50 (4), columns?: as cols} envelope the selected objects with a mesh of rows × cols patches → {id}",
|
||||
"{ids?, rows?: 1..50 (4), cols?: 1..50 (4), columns?: as cols} envelope the selected objects with a mesh of rows × cols patches over their bounds (type measured by its glyph outlines) → {id}",
|
||||
has_selection,
|
||||
env_make_mesh
|
||||
),
|
||||
@@ -154,7 +154,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Top Object",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+C"),
|
||||
"{ids?} the topmost selected path becomes the envelope of the others → {id}",
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}",
|
||||
has_multi,
|
||||
env_make_top
|
||||
),
|
||||
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset with Mesh…",
|
||||
["Object", "Envelope Distort"],
|
||||
None,
|
||||
"{rows?: 1..50, cols?: 1..50 (unset: a mesh envelope's own, else 4), maintainShape?: bool (true: the mesh follows the current envelope shape; false: a flat grid over the content), columns?: as cols} make the selected envelopes mesh envelopes, keeping their content",
|
||||
"{rows?: 1..50, cols?: 1..50 (unset: a mesh envelope's own, else 4), maintainShape?: bool (true: the mesh follows the current envelope shape; false: a flat grid over the content, type measured by its glyph outlines), columns?: as cols} make the selected envelopes mesh envelopes, keeping their content",
|
||||
has_envelope,
|
||||
env_reset_mesh
|
||||
),
|
||||
|
||||
@@ -33,9 +33,10 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
selected_roots(s)
|
||||
}
|
||||
|
||||
/// Selected nodes of a kind (the selection itself or an ancestor).
|
||||
/// Selected nodes of a kind (the selection itself or an ancestor). None while an object of a
|
||||
/// dynamic symbol instance's art is selected.
|
||||
pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
@@ -64,16 +65,19 @@ pub(super) fn is_mesh(n: &Node) -> bool {
|
||||
|
||||
pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
crate::cmd::edit::no_symbol_part(s)?;
|
||||
if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use super::super::object::choice;
|
||||
use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wrap};
|
||||
use super::mesh::{handle_param, index_param, whole};
|
||||
use super::{
|
||||
Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint,
|
||||
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, check_switches, f64_or, f64_req, id_param, json, live, ok, str_param,
|
||||
switch_or,
|
||||
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, id_param, json, live, ok, switch_or, text_param,
|
||||
};
|
||||
|
||||
// ---------- Envelope ----------
|
||||
@@ -17,7 +17,7 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop
|
||||
if let Some(EnvelopeKind::Warp { style: s0, bend: b0, h: h0, v: v0, horizontal: z0 }) = cur {
|
||||
(style, bend, h, v, horizontal) = (s0.clone(), *b0, *h0, *v0, *z0);
|
||||
}
|
||||
if let Some(s) = str_param(p, "style") {
|
||||
if let Some(s) = text_param(p, "style", cmd)? {
|
||||
let s = s.strip_prefix("warp.").unwrap_or(s);
|
||||
if live::WarpStyle::from_id(s).is_none() {
|
||||
return Err(bad(cmd, format!("unknown warp style `{s}`")));
|
||||
@@ -28,10 +28,9 @@ fn warp_kind(p: &Value, cmd: &str, cur: Option<&EnvelopeKind>) -> Result<Envelop
|
||||
h = f64_or(p, "h", f64_or(p, "horizontalDistortion", h)).clamp(-100.0, 100.0);
|
||||
v = f64_or(p, "v", f64_or(p, "verticalDistortion", v)).clamp(-100.0, 100.0);
|
||||
let given = switch_or(p, "horizontal", horizontal, cmd)?;
|
||||
horizontal = match str_param(p, "orientation") {
|
||||
Some("vertical") => false,
|
||||
Some("horizontal") => true,
|
||||
_ => given,
|
||||
horizontal = match choice(p, cmd, "orientation", &["horizontal", "vertical"])? {
|
||||
Some(o) => o == "horizontal",
|
||||
None => given,
|
||||
};
|
||||
Ok(EnvelopeKind::Warp { style, bend, h, v, horizontal })
|
||||
}
|
||||
@@ -85,7 +84,7 @@ pub(super) fn env_make_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = roots_param(s, p)?;
|
||||
let st = s.doc()?;
|
||||
let nodes: Vec<Arc<Node>> = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).map(Arc::new).collect();
|
||||
let src = live::nodes_bounds(&nodes).ok_or_else(|| bad(C, "selection has no bounds"))?;
|
||||
let src = live::envelope_content_bounds(&nodes).ok_or_else(|| bad(C, "selection has no bounds"))?;
|
||||
let kind = EnvelopeKind::Mesh { rows, cols, points: live::grid_points(src, rows, cols), handles: vec![] };
|
||||
let defaults = envelope_defaults(s);
|
||||
let id = s.edit("Make Envelope", |d, sel| wrap(d, sel, &roots, |id, content| envelope(id, content, kind, defaults)))?;
|
||||
@@ -114,7 +113,7 @@ pub(super) fn env_make_top(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = s.doc()?.doc.node(top).and_then(outline_of).filter(|p| p.bounds().is_some()).ok_or_else(|| bad(C, "the top object must be a path"))?;
|
||||
let defaults = envelope_defaults(s);
|
||||
let id = s.edit("Make Envelope", |d, sel| {
|
||||
let id = wrap(d, sel, &content, |id, content| envelope(id, content, EnvelopeKind::TopObject { path }, defaults))?;
|
||||
let id = wrap(d, sel, &content, |id, content| envelope(id, content, EnvelopeKind::TopObject { path, corners: None }, defaults))?;
|
||||
d.remove(top)?;
|
||||
Ok(id)
|
||||
})?;
|
||||
@@ -185,7 +184,7 @@ fn envelope_options_json(mut v: Value, o: &EnvelopeOptions, fidelity: f64) -> Va
|
||||
|
||||
/// `cur` with the options `p` sets.
|
||||
fn options_param(p: &Value, cmd: &str, cur: EnvelopeOptions) -> Result<EnvelopeOptions> {
|
||||
let preserve_shape = match str_param(p, "preserveShape") {
|
||||
let preserve_shape = match text_param(p, "preserveShape", cmd)? {
|
||||
Some(v) => PreserveShape::parse(v).ok_or_else(|| bad(cmd, "preserveShape must be clippingMask|transparency"))?,
|
||||
None => cur.preserve_shape,
|
||||
};
|
||||
@@ -224,7 +223,7 @@ pub(super) fn env_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn envelope_shape(env: &Node, kind: &EnvelopeKind) -> Option<Node> {
|
||||
let grey = Color::gray(0.25);
|
||||
let (rows, cols) = match kind {
|
||||
EnvelopeKind::TopObject { path } => {
|
||||
EnvelopeKind::TopObject { path, .. } => {
|
||||
return Some(Node::path(NodeId(0), path.clone(), Appearance::basic(Paint::solid(grey), Paint::None, 0.0)));
|
||||
}
|
||||
// The mesh itself, handles and all.
|
||||
@@ -289,8 +288,8 @@ pub(super) fn env_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
pub(super) fn env_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.envelope.options";
|
||||
check_numbers(p, &["fidelity"], C)?;
|
||||
check_numbers(p, WARP_NUMBERS, C)?;
|
||||
check_switches(p, &["horizontal"], C)?;
|
||||
// The warp keys are checked whatever is selected: with nothing or only mesh envelopes, too.
|
||||
warp_kind(p, C, None)?;
|
||||
let fid = p.get("fidelity").and_then(Value::as_f64);
|
||||
if fid.is_some_and(|f| !(0.0..=100.0).contains(&f)) {
|
||||
return Err(bad(C, "fidelity must be 0..100"));
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, MaskEdit, Node, NodeId, NodeKind, Selection};
|
||||
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, id_param, switch_or};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, object_param, switch_or};
|
||||
|
||||
/// Name of the temporary mask-editing layer.
|
||||
pub const MASK_EDIT_LAYER: &str = "Opacity Mask Editing";
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{id?} edit the mask art of `id` (default: the first selected object with a mask) in place, as clicking the mask thumbnail in the Transparency panel does; refused in isolation mode and in pattern editing mode → {layer}",
|
||||
can_edit_mask,
|
||||
can_enter,
|
||||
enter
|
||||
),
|
||||
cmd!(
|
||||
@@ -79,6 +79,13 @@ pub(crate) fn can_edit_mask(s: &Session) -> std::result::Result<(), String> {
|
||||
mask_editing_refused(st).map_or(Ok(()), |why| Err(why.into()))
|
||||
}
|
||||
|
||||
/// Edit Opacity Mask: mask editing can be entered ([`can_edit_mask`]), and outside it no object of a
|
||||
/// dynamic symbol instance's art is selected, since its instance's mask is not edited from it.
|
||||
fn can_enter(s: &Session) -> std::result::Result<(), String> {
|
||||
can_edit_mask(s)?;
|
||||
if s.active().is_some_and(|st| st.doc.mask_edit.is_some()) { Ok(()) } else { super::edit::no_symbol_part(s) }
|
||||
}
|
||||
|
||||
/// A document is open and no opacity mask is being edited: isolation mode and pattern editing mode
|
||||
/// are not entered while an opacity mask is edited.
|
||||
pub(crate) fn outside_mask_editing(s: &Session) -> std::result::Result<(), String> {
|
||||
@@ -117,12 +124,17 @@ fn enter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if st.doc.mask_edit.is_some() {
|
||||
return Err(bad(C, "already editing an opacity mask"));
|
||||
}
|
||||
let id = id_param(p, "id").or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
|
||||
let given = object_param(p, "id", C)?;
|
||||
if given.is_none() {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
}
|
||||
let id = given.or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
|
||||
let layer = start(s, id)?;
|
||||
Ok(json!({ "layer": layer.0 }))
|
||||
}
|
||||
|
||||
/// The first selected object with an opacity mask.
|
||||
/// The first selected object with an opacity mask. Callers refuse first while an object of a
|
||||
/// dynamic symbol instance's art is selected ([`super::edit::refuse_symbol_part`]).
|
||||
fn first_masked(st: &crate::DocState) -> Option<NodeId> {
|
||||
st.selection.subjects().iter().copied().find(|i| st.doc.node(*i).is_some_and(|n| n.extras().mask.is_some()))
|
||||
}
|
||||
@@ -136,6 +148,7 @@ fn start(s: &mut Session, id: NodeId) -> Result<NodeId> {
|
||||
|
||||
fn view_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "transparency.viewOpacityMask";
|
||||
let given = object_param(p, "id", C)?;
|
||||
let st = s.doc()?;
|
||||
let editing = st.doc.mask_edit.map(|m| m.object);
|
||||
if !switch_or(p, "on", st.shown_mask().is_none(), C)? {
|
||||
@@ -144,7 +157,10 @@ fn view_mask(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.revision += 1;
|
||||
return Ok(json!({ "on": false, "id": id.map(|i| i.0) }));
|
||||
}
|
||||
let id = id_param(p, "id").or(editing).or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
|
||||
if given.is_none() && editing.is_none() {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
}
|
||||
let id = given.or(editing).or_else(|| first_masked(st)).ok_or_else(|| bad(C, "select an object with an opacity mask"))?;
|
||||
match editing {
|
||||
Some(e) if e != id => return Err(bad(C, "already editing another object's opacity mask")),
|
||||
Some(_) => {}
|
||||
|
||||
@@ -106,7 +106,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Bounding Box",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{} square the bounding box of the selected objects to the page again after a rotation (their geometry stays; one undo step, none when no box is rotated) → {changed: objects reset}",
|
||||
"{} square the bounding box of the selected objects, and of every object inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks), to the page again after a rotation (their geometry stays; one undo step, none when no box is rotated) → {changed: objects reset, the objects inside included}",
|
||||
has_selection,
|
||||
reset_bounding_box
|
||||
),
|
||||
@@ -223,21 +223,63 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
|
||||
|
||||
// ---------- Reset Bounding Box ----------
|
||||
|
||||
/// Squares each selected object and every object inside it: the children of groups, compound paths,
|
||||
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
|
||||
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let turned: Vec<NodeId> = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| n.bbox_angle != 0.0)).collect();
|
||||
if !turned.is_empty() {
|
||||
let mut changed = 0;
|
||||
let squared: Vec<(NodeId, Node)> = ids
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
let (n, count) = squared(d.node(id)?);
|
||||
changed += count;
|
||||
Some((id, n?))
|
||||
})
|
||||
.collect();
|
||||
if !squared.is_empty() {
|
||||
s.edit("Reset Bounding Box", |d, _| {
|
||||
for id in &turned {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.bbox_angle = 0.0;
|
||||
for (id, n) in squared {
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = n;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "changed": turned.len() }))
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
|
||||
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
|
||||
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
|
||||
/// the nodes on the way to a turned object are copied.
|
||||
fn squared(n: &Node) -> (Option<Node>, usize) {
|
||||
let mut out = (!n.is_layer() && n.bbox_angle != 0.0).then(|| {
|
||||
let mut c = n.clone();
|
||||
c.bbox_angle = 0.0;
|
||||
c
|
||||
});
|
||||
let mut count = usize::from(out.is_some());
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
let (child, k) = squared(c);
|
||||
count += k;
|
||||
if let Some(child) = child
|
||||
&& let Some(slot) = out.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
|
||||
{
|
||||
*slot = Arc::new(child);
|
||||
}
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref().filter(|m| m.linked) {
|
||||
let (art, k) = squared(&m.art);
|
||||
count += k;
|
||||
if let Some(art) = art
|
||||
&& let Some(m) = out.get_or_insert_with(|| n.clone()).extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
{
|
||||
m.art = Arc::new(art);
|
||||
}
|
||||
}
|
||||
(out, count)
|
||||
}
|
||||
|
||||
// ---------- Lock / Hide ----------
|
||||
@@ -578,6 +620,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
super::object::transform_node(n, m, sc, objects);
|
||||
}
|
||||
if objects {
|
||||
super::object::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
}
|
||||
Ok(targets)
|
||||
})?;
|
||||
@@ -1321,6 +1366,7 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, dl) in &art {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(Affine::translate(*dl), sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
}
|
||||
let mut moved = vec![];
|
||||
|
||||
@@ -16,7 +16,7 @@ use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_tra
|
||||
use super::opacitymask::percent;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection,
|
||||
has_selection_or_guides, id_param, ids_param, matrix_param, ok, point_param, str_param, targets,
|
||||
has_selection_or_guides, ids_param, matrix_param, object_param, ok, point_param, str_param, targets,
|
||||
};
|
||||
use crate::{EngineError, LastTransform};
|
||||
|
||||
@@ -25,6 +25,7 @@ mod arrange;
|
||||
mod bounds;
|
||||
mod commands;
|
||||
mod compound;
|
||||
mod pixelgrid;
|
||||
mod props;
|
||||
mod shape;
|
||||
mod spans;
|
||||
@@ -35,5 +36,6 @@ pub(crate) use arrange::group_nodes;
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform};
|
||||
pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
|
||||
@@ -66,7 +66,7 @@ fn measure(s: &Session, p: &Value, cmd: &str) -> Result<Measure> {
|
||||
Ok(Measure { preview, point: s.prefs.align_glyph_bounds_point, area: s.prefs.align_glyph_bounds_area })
|
||||
}
|
||||
|
||||
/// Param `key` of the Align commands, Shear, Unlock All, Show All and `text.setFormat`'s lists: one
|
||||
/// Param `key` of the Align commands, Shear, Unlock All, Show All, a warp's `orientation` and `text.setFormat`'s lists: one
|
||||
/// of `values`, or `None` when it is missing or null. Any other value is an error that lists `values`.
|
||||
pub(crate) fn choice<'a>(p: &'a Value, cmd: &str, key: &str, values: &[&str]) -> Result<Option<&'a str>> {
|
||||
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
@@ -112,7 +112,9 @@ fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: &
|
||||
for (id, dv) in moves {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(Affine::translate(*dv), sc);
|
||||
super::pixelgrid::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
for &(i, pos) in &guides {
|
||||
if let Some(g) = d.guides.get_mut(i) {
|
||||
@@ -330,6 +332,7 @@ fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&st
|
||||
a.translate(target(a.p) - a.p);
|
||||
}
|
||||
}
|
||||
snap_anchor_path(d, *id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -434,11 +437,23 @@ fn distribute_anchors(s: &mut Session, label: &str, horiz: bool, gap: Option<f64
|
||||
a.translate(if horiz { Vec2::new(delta, 0.0) } else { Vec2::new(0.0, delta) });
|
||||
}
|
||||
}
|
||||
for (id, _) in &targets {
|
||||
snap_anchor_path(d, *id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// After anchors of path `id` moved: snap the path, or the compound path that holds it, to the
|
||||
/// pixel grid again when it is pixel-aligned.
|
||||
fn snap_anchor_path(d: &mut Document, id: NodeId) {
|
||||
let top = crate::cmd::path::compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::pixelgrid::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["patterns"], "object.distribute")?;
|
||||
check_numbers(p, &["artboard"], "object.distribute")?;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::align::choice;
|
||||
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, id_param, json, ok, selected_roots};
|
||||
use super::{Document, EngineError, Node, NodeId, NodeKind, Result, Session, Value, bad, json, object_param, ok, selected_roots};
|
||||
|
||||
pub(super) enum Arrange {
|
||||
Front,
|
||||
@@ -293,7 +293,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id")
|
||||
let id = object_param(p, "id", "object.isolate")?
|
||||
.or_else(|| s.active().and_then(|d| d.selection.objects.first().copied()))
|
||||
.ok_or_else(|| bad("object.isolate", "missing id"))?;
|
||||
let guides_locked = s.menu.guides_locked;
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::align::{align, can_distribute, distribute, distribute_spacing};
|
||||
use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all};
|
||||
use super::bounds::set_bounds;
|
||||
use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release};
|
||||
use super::pixelgrid::set_pixel_aligned;
|
||||
use super::props::set_props;
|
||||
use super::shape::{expand_shape, set_live_shape};
|
||||
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
|
||||
@@ -300,5 +301,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
cmd!(
|
||||
"object.setPixelAligned",
|
||||
"Align to Pixel Grid",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, on?: bool (default true)} → {ids (the objects whose property changed)} (Transform panel › Align to Pixel Grid: on, each object's horizontal and vertical straight segments move to whole points, or half points when a visible, painted centered stroke has an odd weight, its stroke weights become whole points (at least 1), and every later move, scale, rotation, reflection, Transform Each, Align move, Transform panel change, move of direct-selected anchors or of one anchor (path.moveAnchor), path.setAnchors, object.setLiveShape, move of a compound path's path on its own, artboard move or resize that carries the art (artboard.move, artboard.setProps) or copies it (artboard.move with copy, Duplicate Artboards), every copy that edit.duplicate or a paste moves and object.slice.move of an object slice snaps them again, as does every stroke.set, stroke.weightUp or stroke.weightDown edit (which also rounds the new weight) and every appearance.setItem, appearance.addStroke, appearance.removeItem, appearance.clear, appearance.reduceToBasic, appearance.showAllHidden, appearance.transfer, appearance.copyFrom, paint.setStroke or graphicStyle.apply edit, and every other command that changes the object; diagonal segments and curves keep their shape apart from the anchors they share with those segments, and coordinates that differ stay at least 1 point apart; a live rectangle, polygon, line or pie moves and scales as a whole to the snapped bounds (a full ellipse, all curves, stays as it is), and a path with Live Corners snaps the outline its corners are cut from; a compound path snaps its paths with its own stroke, Make Compound Path from an aligned path or compound path gives an aligned compound path whose paths drop the property, and Release Compound Path gives each path the compound path's property; off, the object keeps its geometry and stops snapping. Only paths and compound paths can be aligned: type, images, groups, guides, paths inside a compound path and other objects are an error and nothing changes. One undo step; nothing changes and no undo step is made when every object already has the value. Saved in the native file)",
|
||||
has_selection,
|
||||
set_pixel_aligned
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -13,11 +13,15 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
d.node(backmost).ok_or(EngineError::NoNode(backmost))?;
|
||||
let mut units: Vec<Vec<Arc<Node>>> = vec![];
|
||||
let mut appearance = None;
|
||||
// The compound path is pixel-aligned when any of its paths was, or any compound path whose
|
||||
// paths it takes; its paths snap with its stroke, so they do not keep the property themselves.
|
||||
let mut aligned = false;
|
||||
for id in &ids {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Group { .. }) {
|
||||
return Err(EngineError::Other("compound paths can only contain paths".into()));
|
||||
}
|
||||
n.walk(&mut |c| aligned |= c.extras().pixel_aligned);
|
||||
compound_members(n, &mut appearance, &mut units);
|
||||
}
|
||||
let cid = d.alloc_id();
|
||||
@@ -40,6 +44,7 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
for mut p in unit {
|
||||
let pn = Arc::make_mut(&mut p);
|
||||
pn.appearance = Appearance::default().into();
|
||||
pn.extras_mut().pixel_aligned = false;
|
||||
if let NodeKind::Path { path, live, .. } = &mut pn.kind {
|
||||
*live = None;
|
||||
if flip {
|
||||
@@ -49,6 +54,10 @@ pub(super) fn compound_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ch.push(p);
|
||||
}
|
||||
}
|
||||
if aligned {
|
||||
c.extras_mut().pixel_aligned = true;
|
||||
super::pixelgrid::snap_if_aligned(&mut c);
|
||||
}
|
||||
d.wrap(&ids, |_| c)?;
|
||||
sel.set([cid]);
|
||||
Ok(cid)
|
||||
@@ -99,6 +108,10 @@ pub(super) fn compound_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
for c in children {
|
||||
let mut c = (**c).clone();
|
||||
c.appearance = n.appearance.clone();
|
||||
// Each path keeps the compound path's pixel-aligned property.
|
||||
if n.extras().pixel_aligned {
|
||||
c.extras_mut().pixel_aligned = true;
|
||||
}
|
||||
out.push(c.id);
|
||||
parts.push(c);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
|
||||
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Rect, Result, Scaling, Session, Value, Vec2, bad, json,
|
||||
selected_roots,
|
||||
};
|
||||
use crate::cmd::{given_objects, switch_or};
|
||||
|
||||
const C: &str = "object.setPixelAligned";
|
||||
|
||||
/// How far apart two coordinates may be and still count as one, in points: segments this close to
|
||||
/// horizontal or vertical count as horizontal or vertical.
|
||||
const EPS: f64 = 1e-6;
|
||||
|
||||
/// Whether `n` can be aligned to the pixel grid: a path that is not a guide, or a compound path.
|
||||
/// Type, images, groups and other objects cannot.
|
||||
pub(crate) fn can_align(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
|
||||
}
|
||||
|
||||
/// `object.setPixelAligned`: turn the pixel-aligned property of the objects given (or the selected
|
||||
/// objects) on or off. Turning it on snaps them to the pixel grid at once. Every object must be
|
||||
/// one [`can_align`] accepts, else nothing changes. When every object already has the value, the
|
||||
/// document and its undo history stay as they are.
|
||||
pub(super) fn set_pixel_aligned(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = switch_or(p, "on", true, C)?;
|
||||
let ids = match given_objects(s, p, C)? {
|
||||
Some(ids) => ids,
|
||||
None => selected_roots(s)?,
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let mut changed: Vec<NodeId> = vec![];
|
||||
for id in &ids {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
// A path inside a compound path snaps with the compound path, whose property it takes.
|
||||
let in_compound = d.parent_of(*id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
|
||||
if !can_align(n) || in_compound {
|
||||
return Err(bad(C, "only paths and compound paths can be aligned to the pixel grid"));
|
||||
}
|
||||
if n.extras().pixel_aligned != on && !changed.contains(id) {
|
||||
changed.push(*id);
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
s.edit("Align to Pixel Grid", |d, _| {
|
||||
for id in &changed {
|
||||
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
n.extras_mut().pixel_aligned = on;
|
||||
if on {
|
||||
snap_object(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": changed.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// After a transform of `n` with `sc`: snap `n` and every object in it that is pixel-aligned to the
|
||||
/// pixel grid, the art of linked opacity masks included. Objects that are not pixel-aligned stay as
|
||||
/// they are.
|
||||
pub(crate) fn keep_pixel_aligned(n: &mut Node, sc: Scaling) {
|
||||
let mut found = vec![];
|
||||
aligned_within(n, &mut vec![], &mut found);
|
||||
for at in found {
|
||||
if let Some(a) = node_at(n, &at) {
|
||||
snap_object(a, sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One step from an object down to an object it holds: its child at an index, or the art of its
|
||||
/// linked opacity mask.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Step {
|
||||
Child(usize),
|
||||
Mask,
|
||||
}
|
||||
|
||||
/// Add to `out` the steps from the object [`keep_pixel_aligned`] started at to `n` (`at`) and to
|
||||
/// every pixel-aligned object in `n`, in the art of linked opacity masks included, `n` first. One
|
||||
/// walk visits each object once, so nothing is copied that does not snap.
|
||||
fn aligned_within(n: &Node, at: &mut Vec<Step>, out: &mut Vec<Vec<Step>>) {
|
||||
if n.extras().pixel_aligned {
|
||||
out.push(at.clone());
|
||||
}
|
||||
// The paths of a pixel-aligned compound path snap with it, but their opacity masks still need a visit.
|
||||
for (i, c) in n.children().map_or(&[][..], Vec::as_slice).iter().enumerate() {
|
||||
at.push(Step::Child(i));
|
||||
aligned_within(c, at, out);
|
||||
at.pop();
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref()
|
||||
&& m.linked
|
||||
{
|
||||
at.push(Step::Mask);
|
||||
aligned_within(&m.art, at, out);
|
||||
at.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// The object that `steps` lead to from `n`, made unique for editing.
|
||||
fn node_at<'a>(n: &'a mut Node, steps: &[Step]) -> Option<&'a mut Node> {
|
||||
let mut cur = n;
|
||||
for s in steps {
|
||||
cur = match s {
|
||||
Step::Child(i) => Arc::make_mut(cur.children_mut()?.get_mut(*i)?),
|
||||
Step::Mask => Arc::make_mut(&mut cur.extras_if_any()?.mask.as_mut()?.art),
|
||||
};
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
/// After a transform of object `id` with `sc`: when `id` is a path of a pixel-aligned compound path
|
||||
/// (moved on its own, as with Group Selection), snap that compound path to the pixel grid again.
|
||||
/// The compound path holds the property, so [`keep_pixel_aligned`] on the path alone does nothing.
|
||||
pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) {
|
||||
let Some(parent) = d.parent_of(id) else { return };
|
||||
if let Some(n) = d.node_mut(parent)
|
||||
&& matches!(n.kind, NodeKind::Compound { .. })
|
||||
&& n.extras().pixel_aligned
|
||||
{
|
||||
snap_object(n, sc);
|
||||
}
|
||||
}
|
||||
|
||||
/// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added
|
||||
/// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity
|
||||
/// mask, to the pixel grid. Objects the edit did not touch are not visited.
|
||||
pub(crate) fn refresh(before: &Document, doc: &mut Document) {
|
||||
let mut ids = vec![];
|
||||
changed_aligned(&before.layers, &doc.layers, &mut ids);
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
|
||||
/// pixel-aligned objects in them to the pixel grid again.
|
||||
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(holds_aligned)
|
||||
&& let Some(n) = doc.node_mut(*id)
|
||||
{
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
|
||||
/// pixel-aligned or hold pixel-aligned art in a linked opacity mask. Inside such an object the
|
||||
/// walk stops: [`keep_pixel_aligned`] visits what it holds.
|
||||
fn changed_aligned(before: &[Arc<Node>], after: &[Arc<Node>], out: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<std::collections::HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
if a.extras().pixel_aligned || a.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art)) {
|
||||
out.push(a.id);
|
||||
} else if let Some(children) = a.children() {
|
||||
changed_aligned(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// After an edit that replaces object `id`'s geometry: snap it, or the pixel-aligned compound path
|
||||
/// that holds it, to the pixel grid again when it is pixel-aligned.
|
||||
pub(crate) fn resnap(d: &mut Document, id: NodeId) {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
snap_if_aligned(n);
|
||||
}
|
||||
keep_compound_aligned(d, id, Scaling::default());
|
||||
}
|
||||
|
||||
/// After an edit of `n`'s strokes: when `n` is pixel-aligned, round its stroke weights and snap it to
|
||||
/// the pixel grid again, since a new weight or alignment can move where the stroke's edges fall.
|
||||
pub(crate) fn snap_if_aligned(n: &mut Node) {
|
||||
if n.extras().pixel_aligned {
|
||||
snap_object(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` or an object in it, or in the art of a linked opacity mask in it, is pixel-aligned.
|
||||
/// It goes only where a transform of `n` goes: not into unlinked masks.
|
||||
fn holds_aligned(n: &Node) -> bool {
|
||||
n.extras().pixel_aligned
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_aligned(&m.art))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_aligned(c)))
|
||||
}
|
||||
|
||||
/// Snap pixel-aligned object `n` to the pixel grid: its stroke weights become whole points (at
|
||||
/// least 1), and its horizontal and vertical straight segments move to whole points, or to half
|
||||
/// points when a centered stroke has an odd weight, so that the stroke's edges fall on the grid.
|
||||
/// A compound path snaps each of its paths. Placed gradients and linked opacity masks of an object
|
||||
/// whose anchors moved follow it ([`follow_snap`]).
|
||||
fn snap_object(n: &mut Node, sc: Scaling) {
|
||||
let half = round_strokes(n);
|
||||
let before = n.geometric_bounds();
|
||||
let mut moved = false;
|
||||
if let NodeKind::Compound { children, .. } = &mut n.kind {
|
||||
// A path is copied for editing only when the snap moves it.
|
||||
for c in children.iter_mut() {
|
||||
if path_snaps(c, half) {
|
||||
let was = c.geometric_bounds();
|
||||
let anchors = snaps_anchors(c);
|
||||
let snapped = Arc::make_mut(c);
|
||||
snap_path_node(snapped, half, sc);
|
||||
if anchors {
|
||||
follow_snap(snapped, was, sc);
|
||||
}
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
} else if snaps_anchors(n) {
|
||||
moved = snap_path_node(n, half, sc);
|
||||
} else {
|
||||
// A live shape is moved with `Node::transform`, which carries its gradients and mask along.
|
||||
snap_path_node(n, half, sc);
|
||||
}
|
||||
if moved {
|
||||
follow_snap(n, before, sc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a snap moves the anchors of path `n` itself (a plain path, or one with Live Corners)
|
||||
/// rather than transforming it as a whole (another live shape).
|
||||
fn snaps_anchors(n: &Node) -> bool {
|
||||
matches!(&n.kind, NodeKind::Path { live, .. } if live.as_deref().is_none_or(|l| matches!(l, LiveShape::Path { .. })))
|
||||
}
|
||||
|
||||
/// After the anchors of `n` moved in a snap, from bounds `before`: its placed gradients are fitted
|
||||
/// to its new bounds, its patterns move and scale with those bounds when `sc` transforms patterns,
|
||||
/// and the art of its linked opacity mask moves and scales with them (and snaps when it is
|
||||
/// pixel-aligned itself).
|
||||
fn follow_snap(n: &mut Node, before: Option<Rect>, sc: Scaling) {
|
||||
let (Some(f), Some(t)) = (before, n.geometric_bounds()) else { return };
|
||||
if f == t {
|
||||
return;
|
||||
}
|
||||
n.appearance.rebase_gradients(f, t);
|
||||
if sc.patterns {
|
||||
vectorcraft_doc::pattern::transform_pattern_paints(n, rect_to_rect(f, t));
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& m.linked
|
||||
{
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
art.transform(rect_to_rect(f, t), sc);
|
||||
keep_pixel_aligned(art, sc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round the stroke weights of `n` to whole points, at least 1 (strokes without weight stay
|
||||
/// without). Returns whether a visible, painted centered stroke has an odd weight.
|
||||
fn round_strokes(n: &mut Node) -> bool {
|
||||
let rounds = |w: f64| if w > 0.0 { w.round().max(1.0) } else { w };
|
||||
let needs = n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(st) if rounds(st.width) != st.width));
|
||||
if needs {
|
||||
for item in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(st) = item {
|
||||
st.width = rounds(st.width);
|
||||
}
|
||||
}
|
||||
}
|
||||
n.appearance.items.iter().any(|i| {
|
||||
matches!(i, AppearanceItem::Stroke(st) if st.visible
|
||||
&& !matches!(st.paint, Paint::None)
|
||||
&& st.width > 0.0
|
||||
&& st.width % 2.0 == 1.0
|
||||
&& st.align == StrokeAlign::Center)
|
||||
})
|
||||
}
|
||||
|
||||
/// Snap path object `n`'s horizontal and vertical straight segments ([`snap_segments`]). A path
|
||||
/// with Live Corners snaps the outline its corners are cut from. Another live shape is moved and
|
||||
/// scaled as a whole instead, from its path's bounds to the bounds of the snapped path, so that it
|
||||
/// stays a live shape. Returns whether it changed.
|
||||
fn snap_path_node(n: &mut Node, half: bool, sc: Scaling) -> bool {
|
||||
let NodeKind::Path { path, live, .. } = &mut n.kind else { return false };
|
||||
let Some(shape) = live.as_deref_mut() else { return snap_segments(path, half) };
|
||||
if let LiveShape::Path { base, .. } = shape {
|
||||
if !snap_segments(base, half) {
|
||||
return false;
|
||||
}
|
||||
*path = shape.to_path();
|
||||
return true;
|
||||
}
|
||||
let mut snapped = path.clone();
|
||||
if !snap_segments(&mut snapped, half) {
|
||||
return false;
|
||||
}
|
||||
let (Some(from), Some(to)) = (path.bounds(), snapped.bounds()) else { return false };
|
||||
n.transform(rect_to_rect(from, to), Scaling { keep_corners: true, patterns: sc.patterns, ..Scaling::default() });
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether [`snap_path_node`] would change path object `n`: whether an anchor of the path it snaps
|
||||
/// moves. Another kind of object is not changed.
|
||||
fn path_snaps(n: &Node, half: bool) -> bool {
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return false };
|
||||
match live.as_deref() {
|
||||
Some(LiveShape::Path { base, .. }) => segment_moves(base, half).is_some(),
|
||||
_ => segment_moves(path, half).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The move and scale that takes `from` onto `to` (a side without size is only moved).
|
||||
fn rect_to_rect(from: Rect, to: Rect) -> Affine {
|
||||
let sx = if from.width() > EPS { to.width() / from.width() } else { 1.0 };
|
||||
let sy = if from.height() > EPS { to.height() / from.height() } else { 1.0 };
|
||||
Affine::translate((to.x0, to.y0)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0))
|
||||
}
|
||||
|
||||
/// Move the anchors of `path`'s horizontal straight segments to whole points vertically and the
|
||||
/// anchors of its vertical ones to whole points horizontally (`half`: to half points), each anchor
|
||||
/// with its handles, so curves and diagonal segments keep their shape apart from the anchors they
|
||||
/// share with those segments. Coordinates that differ stay at least 1 point apart within a subpath,
|
||||
/// so no side collapses. Returns whether an anchor moved.
|
||||
pub(crate) fn snap_segments(path: &mut PathData, half: bool) -> bool {
|
||||
let Some(moves) = segment_moves(path, half) else { return false };
|
||||
for (sp, m) in path.subpaths.iter_mut().zip(moves) {
|
||||
for (a, d) in sp.anchors.iter_mut().zip(m) {
|
||||
if d.x != 0.0 || d.y != 0.0 {
|
||||
a.translate(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// How far [`snap_segments`] moves each anchor of each subpath of `path`, or `None` when it moves
|
||||
/// no anchor.
|
||||
fn segment_moves(path: &PathData, half: bool) -> Option<Vec<Vec<Vec2>>> {
|
||||
let mut changed = false;
|
||||
let mut moves = Vec::with_capacity(path.subpaths.len());
|
||||
for sp in &path.subpaths {
|
||||
let n = sp.anchors.len();
|
||||
let (mut snap_x, mut snap_y) = (vec![false; n], vec![false; n]);
|
||||
for i in 0..sp.segment_count() {
|
||||
if !sp.segment_is_line(i) {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = (i % n, (i + 1) % n);
|
||||
let (p, q) = (sp.anchors[a].p, sp.anchors[b].p);
|
||||
let (dx, dy) = ((q.x - p.x).abs(), (q.y - p.y).abs());
|
||||
if dy <= EPS && dx > EPS {
|
||||
(snap_y[a], snap_y[b]) = (true, true);
|
||||
} else if dx <= EPS && dy > EPS {
|
||||
(snap_x[a], snap_x[b]) = (true, true);
|
||||
}
|
||||
}
|
||||
let xs = snapped_values(sp.anchors.iter().zip(&snap_x).filter(|(_, s)| **s).map(|(a, _)| a.p.x), half);
|
||||
let ys = snapped_values(sp.anchors.iter().zip(&snap_y).filter(|(_, s)| **s).map(|(a, _)| a.p.y), half);
|
||||
let mut m = Vec::with_capacity(n);
|
||||
for (i, a) in sp.anchors.iter().enumerate() {
|
||||
let dx = if snap_x[i] { snapped(&xs, a.p.x) - a.p.x } else { 0.0 };
|
||||
let dy = if snap_y[i] { snapped(&ys, a.p.y) - a.p.y } else { 0.0 };
|
||||
changed |= dx != 0.0 || dy != 0.0;
|
||||
m.push(Vec2::new(dx, dy));
|
||||
}
|
||||
moves.push(m);
|
||||
}
|
||||
changed.then_some(moves)
|
||||
}
|
||||
|
||||
/// The coordinates `values` and where each snaps to, in increasing order: the nearest whole point
|
||||
/// (`half`: half point), and at least 1 point past where the coordinate before it snaps when the
|
||||
/// two differ.
|
||||
fn snapped_values(values: impl Iterator<Item = f64>, half: bool) -> Vec<(f64, f64)> {
|
||||
let mut sorted: Vec<f64> = values.filter(|v| v.is_finite()).collect();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
let mut out: Vec<(f64, f64)> = vec![];
|
||||
for v in sorted {
|
||||
match out.last() {
|
||||
Some(&(last, _)) if v - last <= EPS => {}
|
||||
Some(&(_, at)) => out.push((v, nearest(v, half).max(at + 1.0))),
|
||||
None => out.push((v, nearest(v, half))),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The whole point (`half`: half point) nearest `v`. A whole point halfway between two half points
|
||||
/// goes to the half point above it, and a half point halfway between two whole points goes to the
|
||||
/// whole point below it, so that switching between the two returns a coordinate to where it was.
|
||||
fn nearest(v: f64, half: bool) -> f64 {
|
||||
if half { (v + EPS).floor() + 0.5 } else { (v - 0.5 - EPS).ceil() }
|
||||
}
|
||||
|
||||
/// Where coordinate `v` snaps to, from [`snapped_values`] (`v` itself when it is not listed). A
|
||||
/// coordinate merged into one listed is at most [`EPS`] past it.
|
||||
fn snapped(values: &[(f64, f64)], v: f64) -> f64 {
|
||||
let i = values.partition_point(|(x, _)| *x < v - EPS);
|
||||
values.get(i).filter(|(x, _)| (x - v).abs() <= EPS).map_or(v, |(_, to)| *to)
|
||||
}
|
||||
@@ -254,6 +254,9 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
recut(path, live, partial, &picked, radius, kind);
|
||||
}
|
||||
for id in &ids {
|
||||
super::pixelgrid::resnap(d, *id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
|
||||
@@ -70,10 +70,12 @@ pub(crate) fn transforms_objects(p: &Value) -> bool {
|
||||
/// check them with [`check_switches`] before they change anything.
|
||||
pub(super) const TRANSFORM_SWITCHES: [&str; 6] = ["copy", "strokes", "corners", "patterns", "objects", "typeAreas"];
|
||||
|
||||
/// `xf` on `n` with Transform Objects (`objects`, see [`transforms_objects`]) on or off.
|
||||
/// `xf` on `n` with Transform Objects (`objects`, see [`transforms_objects`]) on or off. The objects
|
||||
/// in `n` that are aligned to the pixel grid snap to it again ([`super::pixelgrid::keep_pixel_aligned`]).
|
||||
pub(crate) fn transform_node(n: &mut Node, xf: Affine, sc: Scaling, objects: bool) {
|
||||
if objects {
|
||||
n.transform(xf, sc);
|
||||
super::pixelgrid::keep_pixel_aligned(n, sc);
|
||||
} else if sc.patterns {
|
||||
vectorcraft_doc::pattern::transform_patterns_only(n, xf);
|
||||
}
|
||||
@@ -168,6 +170,11 @@ fn apply_transform_moving_guides(
|
||||
transform_node(n, xf, sc, objects);
|
||||
}
|
||||
}
|
||||
if objects {
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
}
|
||||
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
for i in sel.guides.clone() {
|
||||
if let Some(g) = d.guides.get_mut(i) {
|
||||
@@ -242,6 +249,11 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
|
||||
// is left as it is, and the reply's warning goes to the status bar.
|
||||
if p.get("ids").is_none() && crate::cmd::brushsym::selected_part(s)?.is_some() {
|
||||
return Ok(json!({ "warning": crate::cmd::brushsym::part_only().to_string() }));
|
||||
}
|
||||
let (ids, anchors) = match ids_param(p, "ids") {
|
||||
Some(v) => (outermost(&s.doc()?.doc, v), false),
|
||||
None => (selected_roots_to_transform(s)?, bool_or(p, "anchors", false)),
|
||||
|
||||
@@ -82,9 +82,10 @@ fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The Objects on Path groups of the selection ([`groups_of`]).
|
||||
/// The Objects on Path groups of the selection ([`groups_of`]). None while an object of a dynamic
|
||||
/// symbol instance's art is selected.
|
||||
fn selected_groups(s: &Session) -> Vec<NodeId> {
|
||||
s.active().map(|st| groups_of(&st.doc, &st.selection.objects)).unwrap_or_default()
|
||||
s.active().filter(|st| st.selection.symbol_part.is_none()).map(|st| groups_of(&st.doc, &st.selection.objects)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The groups a command acts on: those of `ids` when given, otherwise those of the selection.
|
||||
@@ -102,6 +103,7 @@ fn target_groups(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
|
||||
fn has_objects_on_path(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
super::edit::no_symbol_part(s)?;
|
||||
if selected_groups(s).is_empty() { Err("select an Objects on Path group".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
@@ -312,13 +314,18 @@ fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// After an edit: put the objects of every Objects on Path group that changed back on its path
|
||||
/// ([`place`]), inner groups first. Only the parts of the tree that the edit changed are searched.
|
||||
pub(crate) fn refresh(before: &Document, doc: &mut Document) {
|
||||
/// Returns the groups that placing changed.
|
||||
pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Vec<NodeId> {
|
||||
let mut groups = vec![];
|
||||
changed_groups(&before.layers, &doc.layers, &mut groups);
|
||||
let mut placed = vec![];
|
||||
for id in groups.iter().rev() {
|
||||
follow_replacements(before, doc, *id);
|
||||
place_in(doc, *id);
|
||||
if place_in(doc, *id) {
|
||||
placed.push(*id);
|
||||
}
|
||||
}
|
||||
placed
|
||||
}
|
||||
|
||||
/// Members of the group `id` that the edit replaced with new art at the same index keep their
|
||||
@@ -337,14 +344,17 @@ fn follow_replacements(before: &Document, doc: &mut Document, id: NodeId) {
|
||||
}
|
||||
|
||||
/// [`place`] the Objects on Path group `id` of `doc`, measuring symbol instances by their art.
|
||||
fn place_in(doc: &mut Document, id: NodeId) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
/// Returns whether the group changed.
|
||||
fn place_in(doc: &mut Document, id: NodeId) -> bool {
|
||||
let Some(n) = doc.node(id) else { return false };
|
||||
let mut g = n.clone();
|
||||
if place(&mut g, &doc.symbol_boxes())
|
||||
&& let Some(slot) = doc.node_mut(id)
|
||||
{
|
||||
*slot = g;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The Objects on Path groups among `after` and inside them that are not the same nodes as before
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{id?|ids?} put the mask art back above each masked object (default: the selection, or the object whose mask is being edited, which leaves mask editing)",
|
||||
has_doc,
|
||||
can_change_mask,
|
||||
release
|
||||
),
|
||||
cmd!(
|
||||
@@ -43,25 +43,22 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{id?|ids?} keep the mask but stop applying it",
|
||||
has_doc,
|
||||
can_change_mask,
|
||||
|s, p| set_flags(s, p, "Disable Opacity Mask", &json!({ "disabled": true }))
|
||||
),
|
||||
cmd!("transparency.enableOpacityMask", "Enable Opacity Mask", ["Window", "Transparency"], None, "{id?|ids?}", has_doc, |s, p| set_flags(
|
||||
s,
|
||||
p,
|
||||
"Enable Opacity Mask",
|
||||
&json!({ "disabled": false })
|
||||
)),
|
||||
cmd!("transparency.enableOpacityMask", "Enable Opacity Mask", ["Window", "Transparency"], None, "{id?|ids?}", can_change_mask, |s, p| {
|
||||
set_flags(s, p, "Enable Opacity Mask", &json!({ "disabled": false }))
|
||||
}),
|
||||
cmd!(
|
||||
"transparency.unlinkOpacityMask",
|
||||
"Unlink Opacity Mask",
|
||||
["Window", "Transparency"],
|
||||
None,
|
||||
"{id?|ids?} the object moves without its mask",
|
||||
has_doc,
|
||||
can_change_mask,
|
||||
|s, p| set_flags(s, p, "Unlink Opacity Mask", &json!({ "linked": false }))
|
||||
),
|
||||
cmd!("transparency.linkOpacityMask", "Link Opacity Mask", ["Window", "Transparency"], None, "{id?|ids?}", has_doc, |s, p| set_flags(
|
||||
cmd!("transparency.linkOpacityMask", "Link Opacity Mask", ["Window", "Transparency"], None, "{id?|ids?}", can_change_mask, |s, p| set_flags(
|
||||
s,
|
||||
p,
|
||||
"Link Opacity Mask",
|
||||
@@ -73,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?, clip?, invert?, disabled?, linked?} change the opacity masks of `ids`, the selection, or the object whose mask is being edited",
|
||||
has_doc,
|
||||
can_change_mask,
|
||||
|s, p| set_flags(s, p, "Opacity Mask Options", p)
|
||||
),
|
||||
cmd!(
|
||||
@@ -152,9 +149,21 @@ pub(crate) fn percent(o: f64) -> f32 {
|
||||
(o / 100.0).clamp(0.0, 1.0) as f32
|
||||
}
|
||||
|
||||
/// The [`transparency_targets`] that have an opacity mask.
|
||||
/// Refuses a command that would change [`transparency_targets`] when they are the selection, without
|
||||
/// `id` or `ids` and outside mask editing, while an object of a dynamic symbol instance's art is
|
||||
/// selected: the instance's transparency and mask change only when the instance is selected.
|
||||
pub(crate) fn refuse_symbol_part_unnamed(s: &Session, p: &Value) -> Result<()> {
|
||||
if p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.doc.mask_edit.is_none() {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The [`transparency_targets`] that have an opacity mask, refused as
|
||||
/// [`refuse_symbol_part_unnamed`] says.
|
||||
fn masked_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
refuse_symbol_part_unnamed(s, p)?;
|
||||
let ids: Vec<NodeId> = transparency_targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some_and(|n| n.extras().mask.is_some())).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(EngineError::Other("no target object has an opacity mask: select one or give `id`".into()));
|
||||
@@ -162,6 +171,13 @@ fn masked_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The commands that change an existing opacity mask: a document is open, and outside mask editing
|
||||
/// no object of a dynamic symbol instance's art is selected ([`masked_targets`]).
|
||||
fn can_change_mask(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
if s.active().is_some_and(|st| st.doc.mask_edit.is_some()) { Ok(()) } else { super::edit::no_symbol_part(s) }
|
||||
}
|
||||
|
||||
/// Make Opacity Mask: a document is open, and one selected object, which [`make`] gives an empty
|
||||
/// mask and takes into mask editing, is where mask editing can be entered
|
||||
/// ([`super::maskedit::can_edit_mask`]: not in isolation mode or pattern editing mode). The
|
||||
|
||||
+126
-25
@@ -1,5 +1,7 @@
|
||||
//! Fill and stroke paint (the toolbar proxies and their defaults) and the Transparency panel.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind};
|
||||
@@ -19,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) → {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, 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)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -28,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",
|
||||
"{…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",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -37,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Fill and Stroke",
|
||||
[],
|
||||
Some("Shift+X"),
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults",
|
||||
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
@@ -46,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke",
|
||||
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -86,7 +88,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with nothing selected, invert the default → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -95,7 +97,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Complement",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item as paint.invert does; with nothing selected, the default → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
|
||||
),
|
||||
@@ -128,7 +130,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Recent Colors",
|
||||
[],
|
||||
None,
|
||||
"{} → {colors: [{hex, color}] newest first (fed by every paint command and the eyedropper), lastColor: {hex, color}, lastGradient: gradient paint}",
|
||||
"{} → {colors: [{hex, color}] newest first, at most 30, each once, kept across documents for the session (fed by every paint command and the eyedropper), lastColor: {hex, color}, lastGradient: gradient paint}",
|
||||
always,
|
||||
|s, _| {
|
||||
let c = |c: &Color| json!({"hex": c.to_hex(), "color": c});
|
||||
@@ -152,8 +154,9 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// How many colours the Recent Colors rows keep.
|
||||
pub const RECENT_MAX: usize = 10;
|
||||
/// How many colors Recent Colors keeps. The Session holds the list, so it stays the same when
|
||||
/// another document is opened or made active.
|
||||
pub const RECENT_MAX: usize = 30;
|
||||
|
||||
/// Remember an applied paint: a solid colour becomes the last colour and the newest recent
|
||||
/// colour, a gradient the last gradient. During a live preview this waits for the commit.
|
||||
@@ -171,7 +174,7 @@ impl Session {
|
||||
/// new art.
|
||||
pub fn proxy_paints(&self) -> (Paint, Paint) {
|
||||
let show = |stroke: bool| match self.proxy_source(stroke) {
|
||||
Some((n, item)) => proxy_paint(n, stroke, item),
|
||||
Some((n, item)) => proxy_paint(&n, stroke, item),
|
||||
None if stroke => self.paint.stroke.clone(),
|
||||
None => self.paint.fill.clone(),
|
||||
};
|
||||
@@ -179,17 +182,22 @@ impl Session {
|
||||
}
|
||||
|
||||
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(&Node, Option<usize>)> {
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
|
||||
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
|
||||
/// object as the instance draws it.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option<usize>)> {
|
||||
let st = self.active()?;
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
return Some((Cow::Owned(part), None));
|
||||
}
|
||||
let first = st.doc.node(*st.selection.subjects().first()?)?;
|
||||
let item = self.appearance_item();
|
||||
if first.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return Some((first, item));
|
||||
return Some((Cow::Borrowed(first), item));
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
painted(first, true, &mut nodes);
|
||||
nodes.first().map(|n| (*n, None))
|
||||
nodes.first().map(|n| (Cow::Borrowed(*n), None))
|
||||
}
|
||||
|
||||
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
|
||||
@@ -256,6 +264,9 @@ impl DocState {
|
||||
if self.selection.is_empty() {
|
||||
return (false, false);
|
||||
}
|
||||
if self.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
self.doc.walk(|n| {
|
||||
@@ -274,6 +285,18 @@ impl DocState {
|
||||
};
|
||||
(differ(false), differ(true))
|
||||
}
|
||||
|
||||
/// The object of a dynamic symbol instance's art selected with Direct Selection
|
||||
/// ([`vectorcraft_doc::Selection::symbol_part`]), with the instance's own appearance changes
|
||||
/// applied, in the symbol's coordinates. `None` without one.
|
||||
pub(crate) fn selected_symbol_part(&self) -> Option<Node> {
|
||||
let sp = self.selection.symbol_part.as_ref()?;
|
||||
let inst = self.doc.node(sp.instance)?;
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None };
|
||||
let sym = self.doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst);
|
||||
vectorcraft_doc::symbol_overrides::part(&art, &sp.path).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -464,6 +487,26 @@ 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.
|
||||
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());
|
||||
} else {
|
||||
o.stroke = Some(paint.clone());
|
||||
}
|
||||
})?;
|
||||
paint_new_art(s, &paint, fill);
|
||||
if focus {
|
||||
s.fill_active = fill;
|
||||
}
|
||||
s.remember_paint(&paint);
|
||||
return Ok(json!({"objects": 1}));
|
||||
}
|
||||
// Resolve the requested targets before mutating defaults or the active proxy.
|
||||
let item = item_target(s, p, cmd)?.of_kind(s, fill);
|
||||
let selected = item.targets(s, p)?;
|
||||
@@ -534,6 +577,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
// A stroke without paint has no weight; painting it again restores the 1 pt default.
|
||||
stroke.width = 0.0;
|
||||
}
|
||||
if !fill {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
|d, changed| {
|
||||
@@ -552,15 +598,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
},
|
||||
)?;
|
||||
// Rejected edits leave the next shape's appearance and active proxy untouched.
|
||||
// New art takes an unplaced gradient so that it fits the new object's own bounds.
|
||||
if fill {
|
||||
s.paint.fill = unplaced(&paint);
|
||||
} else {
|
||||
if !paint.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = unplaced(&paint);
|
||||
}
|
||||
paint_new_art(s, &paint, fill);
|
||||
if focus {
|
||||
s.fill_active = fill;
|
||||
}
|
||||
@@ -568,6 +606,39 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
}
|
||||
|
||||
/// The instance whose object is selected with Direct Selection, and that object's path
|
||||
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
|
||||
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
|
||||
fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result<Option<(NodeId, Vec<u32>)>> {
|
||||
if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let part = super::brushsym::selected_part(s)?;
|
||||
if part.is_some() {
|
||||
item_target(s, p, cmd)?;
|
||||
}
|
||||
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.
|
||||
pub(crate) fn part_takes(paint: &Paint) -> bool {
|
||||
matches!(paint, Paint::Solid { .. } | Paint::None)
|
||||
}
|
||||
|
||||
/// Make `paint` the fill or stroke of new art. New art takes an unplaced gradient so that it fits
|
||||
/// the new object's own bounds, and a painted stroke on art that had none gets the 1 pt default.
|
||||
fn paint_new_art(s: &mut Session, paint: &Paint, fill: bool) {
|
||||
if fill {
|
||||
s.paint.fill = unplaced(paint);
|
||||
} else {
|
||||
if !paint.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
s.paint.stroke = unplaced(paint);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `p` ask for `span: "selection"` (#2127)? Only a linear or radial gradient the targets
|
||||
/// would each fit to their own bounds can span them: one with its own vector (`start`/`end`),
|
||||
/// a freeform one or a gradient swatch already has its placement.
|
||||
@@ -783,7 +854,9 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
restore_unpainted_stroke(&mut n.appearance, None, &f);
|
||||
n.appearance.set_stroke(f);
|
||||
}
|
||||
Ok(super::appearance::count_changed(d, &before, &ids))
|
||||
// The swap writes the paint of the topmost fill and stroke, not their opacity.
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
}
|
||||
if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 {
|
||||
@@ -811,7 +884,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => n.appearance = Appearance::default_art().into(),
|
||||
}
|
||||
}
|
||||
Ok(super::appearance::count_changed(d, &before, &ids))
|
||||
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false);
|
||||
Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept))
|
||||
})?;
|
||||
}
|
||||
super::newart::reset(s);
|
||||
@@ -823,6 +897,32 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// active item of the proxy's kind is recoloured in each selected object's own stack instead.
|
||||
fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
let stroke = stroke_param(s, p, cmd)?;
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: the solid color
|
||||
// it shows is recolored for this instance only. A gradient or pattern is refused, and so is type
|
||||
// whose characters differ in that paint, since one change holds one paint.
|
||||
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
|
||||
let part = s.doc()?.selected_symbol_part();
|
||||
let mut paint = part.as_ref().map_or(Paint::None, |n| proxy_paint(n, stroke, None));
|
||||
let runs_differ = match part.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => t.runs.iter().any(|r| !same_in_proxy(if stroke { &r.style.stroke } else { &r.style.fill }, &paint)),
|
||||
_ => false,
|
||||
};
|
||||
if runs_differ || !part_takes(&paint) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let changed = super::colorcmds::map_paint(&mut paint, f);
|
||||
if changed {
|
||||
super::brushsym::edit_part(s, id, &path, label, |o| {
|
||||
if stroke {
|
||||
o.stroke = Some(paint.clone());
|
||||
} else {
|
||||
o.fill = Some(paint.clone());
|
||||
}
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
}
|
||||
return Ok(json!({ "changed": changed as usize }));
|
||||
}
|
||||
let ids = match super::given_objects(s, p, cmd)? {
|
||||
Some(ids) => ids,
|
||||
None => super::edit::selected_roots(s)?,
|
||||
@@ -862,6 +962,7 @@ 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";
|
||||
super::opacitymask::refuse_symbol_part_unnamed(s, p)?;
|
||||
let ids = super::opacitymask::transparency_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard)} a copy of each artboard, the copies placed together right of the last artboard as they lay, with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
has_doc,
|
||||
artboard_duplicate
|
||||
),
|
||||
@@ -297,9 +297,11 @@ pub(crate) fn beside_artboards(d: &vectorcraft_doc::Document, rect: Rect) -> Vec
|
||||
}
|
||||
|
||||
/// Duplicate Artboards: a copy of each artboard with its art, in one undo step. The copies keep
|
||||
/// their places relative to each other, together right of the last artboard.
|
||||
/// their places relative to each other, together right of the last artboard, or with `side`
|
||||
/// together on that side of the artboards they copy.
|
||||
fn artboard_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["patterns"], "artboard.duplicate")?;
|
||||
let side = super::layer::artboard_side(p, "artboard.duplicate")?;
|
||||
let (indices, art) = boards_and_art_noted(s, p, "artboard.duplicate")?;
|
||||
let locked_art = locked_and_hidden(s, p, art, "artboard.duplicate")?;
|
||||
let arts = artboards_art(s, &indices, art, locked_art, false)?;
|
||||
@@ -311,7 +313,7 @@ fn artboard_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.filter_map(|(i, _)| d.artboards.get(*i))
|
||||
.map(|a| a.rect)
|
||||
.reduce(|a, b| a.union(b))
|
||||
.map(|r| beside_artboards(d, r))
|
||||
.map(|r| side.map_or_else(|| beside_artboards(d, r), |side| side.offset(r)))
|
||||
.unwrap_or_default();
|
||||
let (mut index, mut ids) = (vec![], vec![]);
|
||||
for (i, art) in &arts {
|
||||
@@ -375,7 +377,10 @@ pub(crate) fn copy_artboard(d: &mut vectorcraft_doc::Document, i: usize, dv: Vec
|
||||
if let Some(id) = d.artboards.get(index).map(|a| a.id) {
|
||||
d.copy_artboard_guides(src.id, id, dv);
|
||||
}
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| c.transform(Affine::translate(dv), sc))?;
|
||||
let copies = super::edit::copy_above(d, art, |_, _, c| {
|
||||
c.transform(Affine::translate(dv), sc);
|
||||
super::object::keep_pixel_aligned(c, sc);
|
||||
})?;
|
||||
Ok((index, copies))
|
||||
}
|
||||
|
||||
|
||||
@@ -279,6 +279,29 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// An SVG filter's XML is one drawable <filter> element.
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER
|
||||
&& let Some(xml) = given.get("xml")
|
||||
{
|
||||
let xml = xml.as_str().ok_or_else(|| bad(id, "`xml` must be a string"))?;
|
||||
vectorcraft_render::effects::svg_filter::check(xml).map_err(|e| bad(id, e))?;
|
||||
}
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER
|
||||
&& let Some(scale) = given.get("scale")
|
||||
&& !scale.as_f64().is_some_and(|k| (0.001..=1000.0).contains(&k))
|
||||
{
|
||||
return Err(bad(id, "`scale` must be a number from 0.001 to 1000"));
|
||||
}
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER
|
||||
&& let Some(origin) = given.get("origin")
|
||||
&& !origin.as_array().is_some_and(|o| o.len() == 2 && o.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)))
|
||||
{
|
||||
return Err(bad(id, "`origin` must be [x, y] in points"));
|
||||
}
|
||||
// Its name is the filter's id.
|
||||
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
|
||||
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
|
||||
}
|
||||
check_effect_color(id, effect, params)?;
|
||||
check_effect_channel(id, effect, params)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected)",
|
||||
"{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -226,6 +226,8 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?);
|
||||
check_switches(p, &["patterns"], "path.moveAnchors")?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
// Objects selected whole move as objects, and their pattern tiles move with them when
|
||||
// `patterns` (default: General › Transform Pattern Tiles) is on.
|
||||
let whole = s.doc()?.selection.whole();
|
||||
@@ -260,11 +262,19 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
*a = a.transform(xf);
|
||||
}
|
||||
}
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps
|
||||
// to the pixel grid again after its anchors move.
|
||||
let top = compound_or_self(doc, *id);
|
||||
if let Some(n) = doc.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(n) = doc.node_mut(*id) {
|
||||
n.transform(xf, sc);
|
||||
super::object::keep_pixel_aligned(n, sc);
|
||||
}
|
||||
super::object::keep_compound_aligned(doc, *id, sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -306,6 +316,12 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = path_mut(d, id)?;
|
||||
let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?;
|
||||
*a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p));
|
||||
// A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps to the
|
||||
// pixel grid again.
|
||||
let top = compound_or_self(d, id);
|
||||
if let Some(n) = d.node_mut(top) {
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -335,13 +351,14 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
);
|
||||
s.edit("Reshape", |d, _| {
|
||||
*path_mut(d, id)? = data;
|
||||
super::object::resnap(d, id);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The compound path enclosing `id`, or `id` itself if it is not inside a compound path.
|
||||
pub(super) fn compound_or_self(d: &Document, id: NodeId) -> NodeId {
|
||||
pub(crate) fn compound_or_self(d: &Document, id: NodeId) -> NodeId {
|
||||
d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).unwrap_or(id)
|
||||
}
|
||||
|
||||
|
||||
@@ -189,8 +189,10 @@ fn has_selection_or_ids(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)
|
||||
}
|
||||
|
||||
/// The repeats of the selection: selected ones, and those around a selected object. None while
|
||||
/// an object of a dynamic symbol instance's art is selected.
|
||||
fn selected_repeats(s: &Session) -> Vec<NodeId> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] };
|
||||
let mut out = vec![];
|
||||
for id in &st.selection.objects {
|
||||
for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() {
|
||||
@@ -207,6 +209,7 @@ fn selected_repeats(s: &Session) -> Vec<NodeId> {
|
||||
|
||||
fn has_repeat(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
super::edit::no_symbol_part(s)?;
|
||||
if selected_repeats(s).is_empty() { Err("select a repeat".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
@@ -377,20 +380,24 @@ pub(crate) fn pattern_done(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if editing(s).is_some() {
|
||||
s.end_text_edit();
|
||||
}
|
||||
let name = s.edit("Done Editing Pattern", |d, sel| {
|
||||
let (pe, art) = leave_edit(d, sel)?;
|
||||
if let Some(def) = d.pattern_mut(&pe.pattern) {
|
||||
def.art = art;
|
||||
if def.size_tile_to_art {
|
||||
def.fit_tile_to_art();
|
||||
}
|
||||
}
|
||||
Ok(pe.pattern)
|
||||
})?;
|
||||
let name = s.edit("Done Editing Pattern", finish_edit)?;
|
||||
after_edit_mode(s, None)?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Leave pattern editing mode in `d`, storing the editing layer's art as the pattern's tile art
|
||||
/// (resizing the tile to the art when the pattern does so) → the pattern's name.
|
||||
pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<String> {
|
||||
let (pe, art) = leave_edit(d, sel)?;
|
||||
if let Some(def) = d.pattern_mut(&pe.pattern) {
|
||||
def.art = art;
|
||||
if def.size_tile_to_art {
|
||||
def.fit_tile_to_art();
|
||||
}
|
||||
}
|
||||
Ok(pe.pattern)
|
||||
}
|
||||
|
||||
fn pattern_cancel(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.edit("Cancel Pattern Editing", |d, sel| {
|
||||
let (pe, _) = leave_edit(d, sel)?;
|
||||
|
||||
@@ -428,7 +428,7 @@ fn rulers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Snap to Grid for a move of `ids` from page point `from` to `to` (unless `p` says `snap: false`):
|
||||
/// the plane and depth of the first one and the plane-space correction that lands the edge of the
|
||||
/// joint bounds of the objects there nearer a gridline on it.
|
||||
/// joint bounds of the objects on that plane, each measured at its own depth, nearer a gridline on it.
|
||||
pub(crate) fn snap_fix(doc: &Document, ids: &[NodeId], p: &Value, (from, to): (Point, Point)) -> Option<(Plane, f64, Vec2)> {
|
||||
let g = grid_of(doc);
|
||||
if !bool_or(p, "snap", g.snap) {
|
||||
|
||||
@@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, id_param, str_param, unique_name};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, object_param, str_param, unique_name};
|
||||
use crate::{EngineError, MAX_COORD};
|
||||
|
||||
const PLACE: &str = "file.place";
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at)} → {ids, name, format, linked, width, height, warnings}. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, PDF/.ai, EMF/WMF (clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed",
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -308,8 +308,10 @@ pub(crate) fn pdf_art(
|
||||
read = Err(e);
|
||||
}
|
||||
let (mut doc, warnings, alone) = fileio::page_or_editing_data(src, bytes, &o, index, read).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
if alone {
|
||||
// Linked images show their files, found from its folder.
|
||||
// Linked images show their files, found from its folder. Its placed documents can place this
|
||||
// file again: one already being read further up, or past the most nested reads, keeps its links
|
||||
// as stored, as a VectorCraft document's do.
|
||||
if alone && let Some(_reading) = document::Reading::enter(bytes) {
|
||||
super::links::resolve(&mut doc, path, false, false);
|
||||
}
|
||||
doc.drop_edit_modes();
|
||||
@@ -534,7 +536,7 @@ impl Session {
|
||||
if st.doc.node(old) != read.job.replaced.as_ref() {
|
||||
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
|
||||
}
|
||||
if st.selection.objects != [old] {
|
||||
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
|
||||
self.execute("select.set", &json!({ "ids": [old.0] }))?;
|
||||
}
|
||||
}
|
||||
@@ -565,6 +567,10 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
if corners.iter().flatten().any(|c| !(c.x.abs() <= MAX_COORD && c.y.abs() <= MAX_COORD)) {
|
||||
return Err(bad(PLACE, "at/rect lie outside the canvas"));
|
||||
}
|
||||
// An object selected in a symbol instance's art can't be swapped, and its instance stays.
|
||||
if replace {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let old = match (replace, &st.selection.objects[..]) {
|
||||
(false, _) => None,
|
||||
@@ -866,7 +872,7 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "image.info";
|
||||
let st = s.doc()?;
|
||||
let id = match (id_param(p, "id"), &st.selection.objects[..]) {
|
||||
let id = match (object_param(p, "id", C)?, &st.selection.objects[..]) {
|
||||
(Some(id), _) => id,
|
||||
(None, [id]) => *id,
|
||||
_ => return Err(bad(C, "select one image or pass id")),
|
||||
|
||||
@@ -157,11 +157,11 @@ std::thread_local! {
|
||||
}
|
||||
|
||||
/// A document's links being resolved ([`READING`]): the entry goes when this does.
|
||||
struct Reading;
|
||||
pub(super) struct Reading;
|
||||
|
||||
impl Reading {
|
||||
/// `None` when the document of `bytes` is already being read, or [`MAX_NESTED_READS`] are.
|
||||
fn enter(bytes: &[u8]) -> Option<Self> {
|
||||
pub(super) fn enter(bytes: &[u8]) -> Option<Self> {
|
||||
let hash = hash_bytes(bytes);
|
||||
READING.with_borrow_mut(|r| (r.len() < MAX_NESTED_READS && !r.contains(&hash)).then(|| r.push(hash))).map(|()| Reading)
|
||||
}
|
||||
|
||||
+228
-32
@@ -13,15 +13,29 @@
|
||||
//! 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`]).
|
||||
//!
|
||||
//! 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 of API level 2 that lists `progress` may import the host's `vc_progress`,
|
||||
//! `vc_cancelled` and `vc_log` ([`vectorcraft_plugins::host`]): run inside a
|
||||
//! [`vectorcraft_doc::cancel::scope`] (the app's heavy filters and background exports), its
|
||||
//! progress goes to the scope's sink and it sees the scope's Cancel; its log lines go to the log
|
||||
//! under its id.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Effect, Node};
|
||||
use vectorcraft_plugins::{Budget, Kind, Plugin, effect, export, objects, registry};
|
||||
use vectorcraft_plugins::{Budget, Kind, Plugin, effect, export, objects, registry, safe_mode};
|
||||
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
|
||||
|
||||
use vectorcraft_plugins::permissions::{self, Grant, Permission};
|
||||
|
||||
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
|
||||
fn err(e: vectorcraft_plugins::Error) -> EngineError {
|
||||
match e {
|
||||
@@ -37,6 +51,7 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
"id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description,
|
||||
"params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()),
|
||||
"size": p.size(), "source": p.source(),
|
||||
"permissions": permissions::names(&m.permissions()), "hash": p.hash(), "api": m.api,
|
||||
});
|
||||
match m.kind {
|
||||
Kind::Effect => v["effect"] = json!(effect::effect_id(&m.id)),
|
||||
@@ -122,15 +137,25 @@ impl FilterRun {
|
||||
}
|
||||
// Bad parameters fail before anything runs.
|
||||
let mut params = Value::Object(m.resolve_params(&plugin_params(p)).map_err(|e| bad(C, e.to_string()))?);
|
||||
let may = m.permissions();
|
||||
let st = s.doc()?;
|
||||
let selected = ids_param(p, "ids").unwrap_or_else(|| st.selection.objects.clone());
|
||||
let inputs = objects::filter_targets(&st.doc, &selected);
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused,
|
||||
// as `selected_roots` refuses it.
|
||||
let selected = match ids_param(p, "ids") {
|
||||
Some(ids) => ids,
|
||||
None => {
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
st.selection.objects.clone()
|
||||
}
|
||||
};
|
||||
// Without `doc.read` a filter is given no objects: it can only add new ones.
|
||||
let inputs = if may.contains(&Permission::DocRead) { objects::filter_targets(&st.doc, &selected) } else { Vec::new() };
|
||||
let parent = st.insertion_parent();
|
||||
let bounds = st.doc.bounds_of(&inputs, false);
|
||||
let board = bounds.and_then(|b| st.doc.artboard_at(b.center())).and_then(|i| st.doc.artboards.get(i)).or(st.doc.artboards.first());
|
||||
let rect = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]);
|
||||
// What the plug-in keeps with the document, as it last wrote it.
|
||||
let data = st.doc.plugin_data(&m.id).cloned().unwrap_or(Value::Null);
|
||||
let data = st.doc.plugin_data(&m.id).filter(|_| may.contains(&Permission::State)).cloned().unwrap_or(Value::Null);
|
||||
params["_context"] = json!({"mode": "filter", "bounds": bounds.map(rect), "artboard": board.map(|a| rect(a.rect)), "documentData": data});
|
||||
let input = objects::encode_input(&st.doc, &inputs);
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| bad(C, e.to_string()))?;
|
||||
@@ -175,13 +200,23 @@ impl FilterRun {
|
||||
}
|
||||
|
||||
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
|
||||
/// it keeps with the document from now on.
|
||||
/// it keeps with the document from now on. An output its permissions don't allow is refused,
|
||||
/// and the document stays as it was.
|
||||
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
|
||||
let m = self.plugin.manifest();
|
||||
let may = m.permissions();
|
||||
let out = objects::decode_output(output).map_err(err)?;
|
||||
if out.document_data.is_some() && !may.contains(&Permission::State) {
|
||||
return Err(not_granted(&m.name, Permission::State));
|
||||
}
|
||||
let may_write = may.contains(&Permission::DocWrite);
|
||||
let (inputs, parent) = (self.inputs, self.parent);
|
||||
let ids = s.edit(m.name.trim_end_matches('…'), |d, sel| {
|
||||
let before = (!may_write).then(|| d.layers.clone());
|
||||
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
|
||||
if before.is_some_and(|b| b != d.layers) {
|
||||
return Err(not_granted(&m.name, Permission::DocWrite));
|
||||
}
|
||||
if let Some(data) = out.document_data {
|
||||
d.set_plugin_data(&m.id, data);
|
||||
}
|
||||
@@ -192,6 +227,12 @@ impl FilterRun {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of a filter `name` whose output needs `permission`, which it wasn't granted.
|
||||
fn not_granted(name: &str, permission: Permission) -> EngineError {
|
||||
let (name, p) = (permissions::display_text(name, permissions::MAX_SHOWN_NAME), permission.name());
|
||||
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
|
||||
}
|
||||
|
||||
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
|
||||
/// parameters and `_context` (what it keeps with the document included), and applies its output as
|
||||
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
|
||||
@@ -283,13 +324,37 @@ fn load_given(c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The permissions `grant` lists in command `c`'s params: `None` when it is left out (or null).
|
||||
/// Anything but a list of permission names is an error.
|
||||
fn grant_param(c: &str, p: &Value) -> Result<Option<Vec<Permission>>> {
|
||||
let Some(v) = p.get("grant").filter(|v| !v.is_null()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let names = v.as_array().ok_or_else(|| bad(c, "`grant` must be a list of permission names"))?;
|
||||
let mut out = Vec::with_capacity(names.len());
|
||||
for n in names {
|
||||
let name = n.as_str().ok_or_else(|| bad(c, "`grant` must be a list of permission names"))?;
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
out.push(Permission::parse(name).ok_or_else(|| bad(c, format!("`grant` names an unknown permission `{shown}`")))?);
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless
|
||||
/// `allowHeavy` says the user agreed, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry.
|
||||
/// `allowHeavy` says the user agreed, and one that lists permissions the user hasn't granted its id
|
||||
/// unless `grant` lists them all, 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.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
let (replace, allow_heavy) = (switch_or(p, "replace", true, C)?, switch_or(p, "allowHeavy", false, C)?);
|
||||
let grant = grant_param(C, p)?;
|
||||
let (plugin, bytes) = load_given(C, p)?;
|
||||
// `hash` pins the module the user was shown: one with other bytes is refused.
|
||||
if let Some(h) = p.get("hash").filter(|v| !v.is_null())
|
||||
&& h.as_str() != Some(plugin.hash())
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
if !replace && registry::get(plugin.id()).is_some() {
|
||||
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
|
||||
}
|
||||
@@ -304,14 +369,47 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
),
|
||||
));
|
||||
}
|
||||
// A plug-in that lists permissions installs once the user grants them: whoever installs it
|
||||
// asks them first, unless they already granted its id 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")));
|
||||
}
|
||||
if m.asks_permissions() {
|
||||
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
|
||||
registry::grant(g.clone());
|
||||
s.store_grant(&m.id, Some(g));
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541).
|
||||
s.store_plugin(plugin.id(), &bytes);
|
||||
let stored = s.store_plugin(plugin.id(), &bytes);
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
let file = s.stored_plugin_file(plugin.id());
|
||||
let mut changed = false;
|
||||
if file.is_none() || stored {
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true);
|
||||
if let Some(file) = file {
|
||||
changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
Ok(describe(®istry::install(plugin)))
|
||||
}
|
||||
|
||||
/// `plugin.inspect`: what installing the module would install, without installing it.
|
||||
fn inspect(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
load_given("plugin.inspect", p).map(|(plugin, _)| describe(&plugin))
|
||||
/// `plugin.inspect`: what installing the module would install, without installing it, and whether
|
||||
/// that needs the user to grant its permissions first (`needsApproval`).
|
||||
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
load_given("plugin.inspect", p).map(|(plugin, _)| {
|
||||
let mut v = describe(&plugin);
|
||||
v["needsApproval"] = json!(!s.plugin_approved(&plugin));
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
/// The plug-in in the `.wasm` file `path`, and its module.
|
||||
@@ -328,36 +426,61 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
|
||||
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
|
||||
}
|
||||
|
||||
/// The plug-in folder last loaded from the preferences, and what happened.
|
||||
static FOLDER: Mutex<Option<(String, Value)>> = Mutex::new(None);
|
||||
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
|
||||
/// happened.
|
||||
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
|
||||
|
||||
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and has changed since
|
||||
/// the last load. Runs whenever preferences are applied (startup, `prefs.set`). Native only.
|
||||
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
|
||||
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
|
||||
/// (startup, `prefs.set`). Native only.
|
||||
pub(crate) fn sync_prefs(s: &Session) {
|
||||
let folder = s.prefs.plugins_folder.trim();
|
||||
if folder.is_empty() {
|
||||
// In Safe Mode nothing loads, and the folder is loaded once it ends ([`load_prefs_folder`]).
|
||||
if folder.is_empty() || safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if last.as_ref().is_some_and(|(f, _)| f == folder) {
|
||||
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
|
||||
return;
|
||||
}
|
||||
*last = Some((folder.to_string(), load_folder(folder)));
|
||||
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
|
||||
}
|
||||
|
||||
/// Turns Safe Mode on for `--safe-mode`, before the plug-in folder is attached: no plug-in loads or
|
||||
/// runs in this process from then on.
|
||||
pub fn start_in_safe_mode() {
|
||||
safe_mode::set_active(Some(safe_mode::Source::Flag));
|
||||
}
|
||||
|
||||
/// Loads the stored plug-ins and the Additional Plug-ins Folder preference: the app calls it when
|
||||
/// the user leaves the choice after a launch that stopped with Disable or Start Normally, which
|
||||
/// turns Safe Mode off first.
|
||||
pub fn load_prefs_folder(s: &mut Session) {
|
||||
s.load_stored_plugins();
|
||||
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
sync_prefs(s);
|
||||
}
|
||||
|
||||
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
|
||||
/// ([`Session::plugin_approved`], with the store's grants read once) → its report; saves the
|
||||
/// disabled list when loading changed it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_folder(folder: &str) -> Value {
|
||||
fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
return json!({"folder": folder, "error": e});
|
||||
}
|
||||
// A file in it may be a link to one elsewhere.
|
||||
match registry::load_folder_where(std::path::Path::new(folder), |f| match f.to_str() {
|
||||
let allow = |f: &std::path::Path| match f.to_str() {
|
||||
Some(f) => crate::file_access::check_read(f),
|
||||
// A lossy name would check another file than the one loaded.
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
}) {
|
||||
};
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_approver()) {
|
||||
Ok(r) => {
|
||||
if r.disabled_changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
|
||||
}
|
||||
Err(e) => json!({"folder": folder, "error": e.to_string()}),
|
||||
@@ -365,7 +488,7 @@ fn load_folder(folder: &str) -> Value {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn load_folder(folder: &str) -> Value {
|
||||
fn load_folder(_: &Session, folder: &str) -> Value {
|
||||
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
|
||||
}
|
||||
|
||||
@@ -378,17 +501,69 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if folder.is_empty() {
|
||||
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
|
||||
}
|
||||
let report = load_folder(&folder);
|
||||
let report = load_folder(s, &folder);
|
||||
if let Some(e) = report.get("error").and_then(Value::as_str) {
|
||||
return Err(EngineError::Other(e.to_string()));
|
||||
}
|
||||
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, report.clone()));
|
||||
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, r)| r.clone());
|
||||
Ok(json!({"plugins": registry::list().iter().map(|p| describe(p)).collect::<Vec<_>>(), "folder": folder}))
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| r.clone());
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect();
|
||||
Ok(
|
||||
json!({"plugins": registry::list().iter().map(|p| describe(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
|
||||
/// and the plug-in the last launch was loading when it stopped while the user hasn't chosen yet.
|
||||
fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"active": safe_mode::active(),
|
||||
"source": safe_mode::source().map(safe_mode::Source::name),
|
||||
"disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>(),
|
||||
"pendingItem": safe_mode::previous().map(|i| i.to_json()),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `plugin.setEnabled`: turns a plug-in on or off for the next launch, by `id` or by `file` (a
|
||||
/// plug-in that stopped a launch while loading may be known by its file alone). It neither loads
|
||||
/// nor unloads anything now, and uninstalls nothing.
|
||||
fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.setEnabled";
|
||||
let Some(enabled) = p.get("enabled").and_then(Value::as_bool) else {
|
||||
let key = "enabled";
|
||||
return Err(bad(C, format!("`{key}` must be true or false")));
|
||||
};
|
||||
let text = |key: &str| match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(v)) => Ok(Some(v.trim().to_string()).filter(|v| !v.is_empty())),
|
||||
Some(_) => Err(bad(C, format!("`{key}` must be a string"))),
|
||||
};
|
||||
// Turning on by id also matches the plug-in's stored file, which names it when it stopped a
|
||||
// launch while loading.
|
||||
let (item, stored) = match (text("id")?, text("file")?) {
|
||||
(Some(id), _) => {
|
||||
let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None };
|
||||
(registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored)
|
||||
}
|
||||
(None, Some(file)) => (safe_mode::Item::file(file), None),
|
||||
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
|
||||
};
|
||||
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
|
||||
if enabled && !safe_mode::disabled().iter().any(|i| items.iter().any(|item| i.same(item))) {
|
||||
return Err(bad(C, "that plug-in isn't disabled (see plugin.safeMode)"));
|
||||
}
|
||||
let mut changed = false;
|
||||
for item in items {
|
||||
changed |= safe_mode::set_enabled(item, enabled);
|
||||
}
|
||||
// Without a plug-in folder (a session confined to automation roots), or when the list there
|
||||
// can't take the change, the change stays in this process and goes with the next change that saves.
|
||||
let saved = !changed || s.store_disabled_plugins();
|
||||
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -402,12 +577,15 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// Installed again, it asks again.
|
||||
registry::revoke(id);
|
||||
s.store_grant(id, None);
|
||||
s.unstore_plugin(id);
|
||||
if registry::remove(id) { Ok(json!({"removed": id})) } else { Err(err(vectorcraft_plugins::Error::NotFound(id.into()))) }
|
||||
}
|
||||
|
||||
/// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove` and
|
||||
/// `.reload`.
|
||||
/// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove`,
|
||||
/// `.reload`, `.safeMode` and `.setEnabled`.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -415,7 +593,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's format id, plugin.<id>, for document.export, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's format id, plugin.<id>, for document.export, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -442,7 +620,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: a plug-in with the same id is replaced), 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)} 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: a plug-in with the same id is replaced), 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 replacing the plug-in with one that lists no new permission needs none; 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",
|
||||
always,
|
||||
install
|
||||
),
|
||||
@@ -451,7 +629,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",
|
||||
"{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 its id: plugin.install then needs grant)",
|
||||
always,
|
||||
inspect
|
||||
),
|
||||
@@ -461,9 +639,27 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reload Plug-ins",
|
||||
["Object", "Plug-ins"],
|
||||
None,
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module is reported and skipped) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted its id; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}]}",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
cmd!(
|
||||
query "plugin.safeMode",
|
||||
"Safe Mode",
|
||||
[],
|
||||
None,
|
||||
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
|
||||
always,
|
||||
safe_mode_state
|
||||
),
|
||||
cmd!(
|
||||
query "plugin.setEnabled",
|
||||
"Enable on Re-launch",
|
||||
[],
|
||||
None,
|
||||
"{id | file: a plug-in as plugin.safeMode's disabled lists it, enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
|
||||
always,
|
||||
set_enabled
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -150,10 +150,19 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("scaleCorners", "General", "Options", "Scale Corners", bool),
|
||||
p!("scaleStrokes", "General", "Options", "Scale Strokes & Effects", bool),
|
||||
p!("zoomWithMouseWheel", "General", "Options", "Zoom with Mouse Wheel", bool),
|
||||
p!("ctrlWheelScrollsSideways", "General", "Options", "Scroll Sideways with Cmd/Ctrl + Wheel", bool),
|
||||
p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool),
|
||||
p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool),
|
||||
p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool),
|
||||
// Selection & Anchor Display
|
||||
p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")),
|
||||
p!(
|
||||
"marqueeSelection",
|
||||
"Selection & Anchor Display",
|
||||
"Selection",
|
||||
"Marquee Selection",
|
||||
choice(&[("touching", "Touching"), ("enclosed", "Fully Enclosed"), ("directional", "Drag Direction")])
|
||||
),
|
||||
p!("objectSelectionByPathOnly", "Selection & Anchor Display", "Selection", "Object Selection by Path Only", bool),
|
||||
p!("snapToPointTolerance", "Selection & Anchor Display", "Selection", "Snap to Point", num(1.0, 8.0, "px")),
|
||||
p!("ctrlClickSelectsBehind", "Selection & Anchor Display", "Selection", "Command Click to Select Objects Behind", bool),
|
||||
@@ -206,6 +215,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("highlightAlternateGlyphs", "Type", "Options", "Highlight Alternate Glyphs", bool),
|
||||
p!("highlightSubstitutedFonts", "Type", "Options", "Highlight Substituted Fonts", bool),
|
||||
p!("placeholderText", "Type", "Options", "Fill New Type Objects With Placeholder Text", bool),
|
||||
p!("typedLists", "Type", "Options", "Start Lists From Typed Markers", bool),
|
||||
p!("fontsFolder", "Type", "Options", "Additional Fonts Folder", text),
|
||||
// Units
|
||||
p!("unitsGeneral", "Units", "", "General", choice(UNITS)),
|
||||
@@ -247,6 +257,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("measurementLabels", "Smart Guides", "Display Options", "Measurement Labels", bool),
|
||||
p!("spacingGuides", "Smart Guides", "Display Options", "Spacing Guides", bool),
|
||||
p!("distanceGuides", "Smart Guides", "Display Options", "Invoke Distance Guides", bool),
|
||||
p!("snapToLastLocation", "Smart Guides", "Display Options", "Snap to Last Location", bool),
|
||||
p!("snappingTolerance", "Smart Guides", "", "Snapping Tolerance", num(0.0, 40.0, "pt")),
|
||||
p!("snapTangent", "Smart Guides", "Geometric Guides", "Snap to Tangent", bool),
|
||||
p!("snapPerpendicular", "Smart Guides", "Geometric Guides", "Snap to Perpendicular", bool),
|
||||
@@ -338,6 +349,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("openDocumentsAsTabs", "User Interface", "", "Open Documents As Tabs", bool),
|
||||
p!("largeTabs", "User Interface", "", "Large Tabs", bool),
|
||||
p!("systemTitleBar", "User Interface", "", "System Title Bar", bool),
|
||||
p!("appTitleBar", "User Interface", "", "VectorCraft Title Bar on Every Desktop", bool),
|
||||
p!("uiScaling", "User Interface", "UI Scaling", "Scale", num(0.75, 2.0, "×")),
|
||||
p!("scaleCursorWithUi", "User Interface", "UI Scaling", "Scale Cursor Proportional to UI", bool),
|
||||
// `auto` or a language code the shell registers (`zh-hant`); the shell shows it as a dropdown.
|
||||
@@ -422,6 +434,9 @@ 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),
|
||||
// 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),
|
||||
];
|
||||
|
||||
pub fn spec(key: &str) -> Option<&'static PrefSpec> {
|
||||
|
||||
@@ -455,8 +455,9 @@ fn placed_symbol(d: &Document, n: &Node) -> Option<Node> {
|
||||
enum Which {
|
||||
/// Every raster effect (PDF).
|
||||
All,
|
||||
/// Effects SVG cannot represent faithfully, with their other raster effects.
|
||||
Pixel { cmyk: bool },
|
||||
/// Effects SVG cannot represent faithfully, with their other raster effects; `filters`: the SVG
|
||||
/// written has filters (SVG Tiny 1.2 has none).
|
||||
Pixel { cmyk: bool, filters: bool },
|
||||
}
|
||||
|
||||
/// Has `n` (its own, its fills' or strokes') raster effects `which` turns into an image?
|
||||
@@ -464,8 +465,14 @@ fn imaged(n: &Node, which: Which) -> bool {
|
||||
let fx = raster_fx(n);
|
||||
match which {
|
||||
Which::All => !fx.is_empty(),
|
||||
Which::Pixel { cmyk } => {
|
||||
fx.iter().any(|f| matches!(f, RasterFx::Pixel(_) | RasterFx::Rasterize(_)))
|
||||
Which::Pixel { cmyk, filters } => {
|
||||
// An SVG filter that is the object's last effect, and its only pixel effect, stays a filter.
|
||||
let pixels = fx.iter().filter(|f| matches!(f, RasterFx::Pixel(_) | RasterFx::Rasterize(_))).count();
|
||||
let live = filters
|
||||
&& pixels == 1
|
||||
&& effects::svg_filter::writes_live(&n.appearance.effects)
|
||||
&& fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11()));
|
||||
(pixels > 0 && !live)
|
||||
|| (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx)))
|
||||
}
|
||||
}
|
||||
@@ -592,7 +599,13 @@ pub fn flatten_raster_effects(doc: &Document) -> Option<Document> {
|
||||
/// Mask…) or Rasterize are images as [`flatten_raster_effects`] makes them (SVG export: its
|
||||
/// filters draw the other raster effects live), or `None` when there are none.
|
||||
pub fn flatten_pixel_effects(doc: &Document) -> Option<Document> {
|
||||
flatten(doc, &mut FlattenReport::new(Which::Pixel { cmyk: doc.color_mode == ColorMode::Cmyk }, doc))
|
||||
flatten_pixel_effects_for(doc, true)
|
||||
}
|
||||
|
||||
/// [`flatten_pixel_effects`] for SVG that has filters (`filters`) or not (SVG Tiny 1.2): without
|
||||
/// them an SVG filter (Effect › SVG Filters) also makes its object an image.
|
||||
pub fn flatten_pixel_effects_for(doc: &Document, filters: bool) -> Option<Document> {
|
||||
flatten(doc, &mut FlattenReport::new(Which::Pixel { cmyk: doc.color_mode == ColorMode::Cmyk, filters }, doc))
|
||||
}
|
||||
|
||||
fn flatten(doc: &Document, report: &mut FlattenReport) -> Option<Document> {
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::collections::{BTreeSet, HashMap};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink};
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::colorcmds::{Recolor, Scope};
|
||||
@@ -99,7 +99,7 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
|
||||
read(n, only, &mut nodes);
|
||||
}
|
||||
for m in nodes {
|
||||
for p in node_paints(m) {
|
||||
for p in node_paints(m).chain(override_paints(m)) {
|
||||
match p {
|
||||
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
|
||||
@@ -522,6 +522,9 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let row_swatches: Vec<Option<Swatch>> =
|
||||
rows.iter().map(|r| r.new_color().and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())).collect();
|
||||
// While an object of a dynamic symbol instance's art is selected, the selection is refused, as
|
||||
// `selected_roots` refuses it.
|
||||
super::edit::refuse_symbol_part(s)?;
|
||||
let ids = s.doc()?.selection.objects.clone();
|
||||
let group = text_param(p, "group", C)?;
|
||||
if ids.is_empty() && group.is_none() {
|
||||
|
||||
@@ -565,6 +565,10 @@ struct Meta {
|
||||
path: Option<String>,
|
||||
/// The format Save writes for it ([`SAVE_FORMATS`]).
|
||||
format: String,
|
||||
/// A document's own native PDF choice before the recovery copy omits its PDF. None keeps
|
||||
/// inheritance from the current application preference. Older copies did not record a choice.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
native_pdf_compatible: Option<bool>,
|
||||
/// When the copy was written (Unix seconds; none without a clock).
|
||||
saved: Option<i64>,
|
||||
/// The file it was read from when that import left things out of the document, and what
|
||||
@@ -821,7 +825,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
mode: SaveMode::Copy,
|
||||
path: st.path.clone(),
|
||||
format: native,
|
||||
options: Default::default(),
|
||||
options: serde_json::Map::from_iter([("pdfCompatible".into(), json!(false))]),
|
||||
name: format!("{file}{DOC_EXT}"),
|
||||
folder: None,
|
||||
modified: None,
|
||||
@@ -832,6 +836,11 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
title: title.clone(),
|
||||
path: st.path.clone(),
|
||||
format: st.format.to_string(),
|
||||
native_pdf_compatible: if matches!(st.format, "vectorcraft" | "template") {
|
||||
st.save_options.get("pdfCompatible").and_then(Value::as_bool)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
saved,
|
||||
imported_from: st.imported_from.clone(),
|
||||
import_losses: st.import_losses.clone(),
|
||||
@@ -1060,6 +1069,9 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
|
||||
st.imported_from = meta.imported_from.clone();
|
||||
st.import_losses = meta.import_losses.clone();
|
||||
st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft");
|
||||
if let Some(pdf) = meta.native_pdf_compatible {
|
||||
st.save_options.insert("pdfCompatible".into(), json!(pdf));
|
||||
}
|
||||
st.mark_unsaved();
|
||||
// The copy stays until the document is saved or closed.
|
||||
st.recovery = Some(RecoveryCopy { file: mine.clone(), doc: st.doc.clone() });
|
||||
|
||||
@@ -62,7 +62,7 @@ impl Loader for Folder {
|
||||
|
||||
/// The bytes the base64 text `b64` holds, up to `max` and a few more: only the text they take is
|
||||
/// decoded.
|
||||
fn decode_head(b64: &str, max: usize) -> Option<Vec<u8>> {
|
||||
pub(super) fn decode_head(b64: &str, max: usize) -> Option<Vec<u8>> {
|
||||
let chars = max.div_ceil(3).saturating_mul(4);
|
||||
let mut kept = 0usize;
|
||||
let end = b64
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! art retained underneath. Recipes select topology regions; source edits re-evaluate them in
|
||||
//! the same undo transaction. Rendering and exporters only see ordinary groups and paths.
|
||||
use super::pathops::Beside;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, point_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, f64_or, has_doc, id_param, object_param, point_param};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
@@ -785,15 +785,15 @@ fn end_isolation(s: &mut Session) -> Result<()> {
|
||||
st.isolation = editing_layer(&st.doc);
|
||||
Ok(())
|
||||
}
|
||||
fn target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
let id = id_param(p, "id")
|
||||
fn target(s: &Session, p: &Value, cmd: &str) -> Result<NodeId> {
|
||||
let id = object_param(p, "id", cmd)?
|
||||
.or_else(|| s.active().and_then(|d| d.selection.objects.first().copied()))
|
||||
.ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
|
||||
s.doc()?.doc.node(id).filter(|n| n.extras().shaper.is_some()).ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
|
||||
.ok_or_else(|| bad(cmd, "select a Shaper group"))?;
|
||||
s.doc()?.doc.node(id).filter(|n| n.extras().shaper.is_some()).ok_or_else(|| bad(cmd, "select a Shaper group"))?;
|
||||
Ok(id)
|
||||
}
|
||||
fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = target(s, p)?;
|
||||
let id = target(s, p, "shaper.release")?;
|
||||
let ids = s.edit("Release Shaper Group", |d, sel| {
|
||||
let original = d.node(id).map(sources).ok_or(EngineError::NoNode(id))?;
|
||||
let (parent, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
@@ -809,7 +809,7 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = target(s, p)?;
|
||||
let id = target(s, p, "shaper.expand")?;
|
||||
s.edit("Expand Shaper Group", |d, sel| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
n.extras_mut().shaper = None;
|
||||
|
||||
@@ -708,7 +708,9 @@ fn move_slices(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
n.transform(vectorcraft_geom::Affine::translate(v), vectorcraft_doc::Scaling::default());
|
||||
super::object::keep_pixel_aligned(n, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,6 +266,7 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(st) = n.appearance.stroke_at_mut(index) {
|
||||
set(st);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
Ok(())
|
||||
})?;
|
||||
// Commit the new-art template only after the complete request is validated
|
||||
@@ -329,6 +330,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result<Value> {
|
||||
if let Some(st) = n.appearance.stroke_at_mut(index) {
|
||||
st.width = step_weight(st.width, unit, up);
|
||||
}
|
||||
super::object::snap_if_aligned(n);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
|
||||
@@ -343,10 +345,15 @@ impl Session {
|
||||
/// The stroke the Stroke panel, the Control bar and the Properties panel show, picked as the
|
||||
/// Stroke proxy picks its paint: the Appearance panel's active item when it is a stroke, else
|
||||
/// the first selected object's (a group's first painted object's) top stroke, type's first
|
||||
/// run's character stroke; with nothing selected, the next object drawn's
|
||||
/// ([`Session::new_art_stroke`]). None without a document or the selection's stroke.
|
||||
/// run's character stroke; with an object of a dynamic symbol instance selected
|
||||
/// ([`DocState::selected_symbol_part`]), that object's as the instance draws it; with nothing
|
||||
/// selected, the next object drawn's ([`Session::new_art_stroke`]). None without a document or
|
||||
/// the selection's stroke.
|
||||
pub fn shown_stroke(&self) -> Option<StrokeLayer> {
|
||||
let st = self.active()?;
|
||||
if let Some(part) = st.selected_symbol_part() {
|
||||
return node_stroke(&part);
|
||||
}
|
||||
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
|
||||
let first = st.doc.node(*first)?;
|
||||
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
|
||||
@@ -360,13 +367,19 @@ impl Session {
|
||||
|
||||
impl DocState {
|
||||
/// Which Stroke panel values the selected objects' strokes (type: every run's) don't share,
|
||||
/// and whether Align Stroke applies to them (no open path among them). One walk of the
|
||||
/// selection, so callers that ask every frame cache it by revision.
|
||||
/// and whether Align Stroke applies to them (no open path among them). With an object of a
|
||||
/// dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that object alone is
|
||||
/// read. One walk of the selection, so callers that ask every frame cache it by revision.
|
||||
pub fn stroke_mixed(&self) -> StrokeMixed {
|
||||
let part = self.selected_symbol_part();
|
||||
let mut nodes = vec![];
|
||||
for id in &self.selection.objects {
|
||||
if let Some(n) = self.doc.node(*id) {
|
||||
painted(n, true, &mut nodes);
|
||||
if let Some(part) = &part {
|
||||
painted(part, true, &mut nodes);
|
||||
} else {
|
||||
for id in &self.selection.objects {
|
||||
if let Some(n) = self.doc.node(*id) {
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut strokes = vec![];
|
||||
|
||||
@@ -20,7 +20,7 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, id_param, index, ok, str_param, unique_name};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, object_param, ok, str_param, unique_name};
|
||||
use crate::EngineError;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Graphic Style",
|
||||
["Window", "Graphic Styles"],
|
||||
None,
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows; exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
|
||||
has_doc,
|
||||
style_apply
|
||||
),
|
||||
@@ -67,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked → {name}",
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked path directly in a graph series, the graph also stores the paint, weight and opacity of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -273,6 +273,7 @@ fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle, chars: bool) {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
style_node(n, g, chars);
|
||||
n.extras_mut().graphic_style = Some(g.id);
|
||||
super::object::snap_if_aligned(n);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +291,7 @@ fn style_index(d: &Document, name: &str) -> Result<usize> {
|
||||
|
||||
/// The object a style is made from: `id`, else the first selected object.
|
||||
fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)> {
|
||||
let id = match id_param(p, "id") {
|
||||
let id = match object_param(p, "id", cmd)? {
|
||||
Some(id) => id,
|
||||
None => super::edit::selected_roots(s)?.first().copied().ok_or_else(|| bad(cmd, "select an object (or pass `id`)"))?,
|
||||
};
|
||||
@@ -333,6 +334,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.new_art_style(&g, add);
|
||||
return Ok(json!({ "newArt": true }));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit("Apply Graphic Style", |d, _| {
|
||||
if add {
|
||||
let g = d.graphic_styles[i].clone();
|
||||
@@ -344,12 +346,17 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
// The graph stores the rows of the kinds the style shows, now on top of each stack.
|
||||
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
let kinds = (shows(true), shows(false));
|
||||
super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false);
|
||||
} else {
|
||||
d.graphic_style_id(i);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
for id in &ids {
|
||||
apply_style(d, *id, &g, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -456,6 +463,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let look = GraphicStyle::of(String::new(), captured(n), n);
|
||||
let name = d.graphic_styles[i].name.clone();
|
||||
let chars = s.prefs.override_char_color;
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
let id = d.graphic_style_id(i);
|
||||
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look });
|
||||
@@ -465,9 +473,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
let g = d.graphic_styles[i].clone();
|
||||
for nid in follow {
|
||||
apply_style(d, nid, &g, chars);
|
||||
for nid in &follow {
|
||||
apply_style(d, *nid, &g, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false);
|
||||
set_link(d, &[src], Some(id));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -156,6 +156,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (apply, add) = (switch_or(p, "apply", false, C)?, switch_or(p, "add", false, C)?);
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
checked_ids_param(s, p, "ids", C)?;
|
||||
} else if apply {
|
||||
// A selection that can't take a style is refused before any style is added.
|
||||
super::appearance::appearance_targets(s, &json!({}))?;
|
||||
}
|
||||
let mut names = names_param(p, C)?;
|
||||
names.extend(text_param(p, "name", C)?.map(str::to_string));
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Effect › SVG Filters: the SVG filters a document holds (`svgFilter.list`, `define`, `delete`,
|
||||
//! `import`) and applying one to objects as a live `svg.filter` effect (`svgFilter.apply`). An
|
||||
//! applied effect names the document's filter: editing the filter changes what every object that
|
||||
//! uses it draws, and deleting it leaves their effects in place, drawing nothing, until a filter of
|
||||
//! that name exists again. Each effect holds the definition it draws with, kept in step here.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, SvgFilter};
|
||||
use vectorcraft_render::effects::{self, svg_filter};
|
||||
|
||||
use super::fileio::{absolute_path, read_file_head};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, text_param};
|
||||
|
||||
/// The largest SVG file Import SVG Filter reads.
|
||||
const MAX_IMPORT_BYTES: usize = 16 << 20;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "svgFilter.list",
|
||||
"SVG Filters",
|
||||
[],
|
||||
None,
|
||||
"{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
"svgFilter.define",
|
||||
"New SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{xml: one SVG <filter> element (its id is its name; 1..64 primitives; at most 64 KB), replace?: the name of the filter it replaces and keeps (Edit SVG Filter)} add an SVG filter to the document, after the others, or replace one, as one undo step; every object whose svg.filter effect names it draws with the new definition; a name another filter has is refused and a document holds at most 64 filters → {name, filters}",
|
||||
has_doc,
|
||||
define
|
||||
),
|
||||
cmd!(
|
||||
"svgFilter.delete",
|
||||
"Delete SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{name} remove an SVG filter from the document, as one undo step; objects whose svg.filter effect names it keep the effect, which draws nothing until a filter of that name is defined or imported again → {filters}",
|
||||
has_doc,
|
||||
delete
|
||||
),
|
||||
cmd!(
|
||||
"svgFilter.import",
|
||||
"Import SVG Filter…",
|
||||
[],
|
||||
None,
|
||||
"{path?|svg?} add the <filter> elements of an SVG file (at most 16 MB; not SVGZ; its first 256 filters) or of SVG text to the document's SVG filters, as one undo step; a filter whose name the document already has, and one svgFilter.define would refuse, is left out; objects whose effect names an added filter draw with it → {added: [names…], skipped: count, filters}",
|
||||
has_doc,
|
||||
import
|
||||
),
|
||||
cmd!(
|
||||
"svgFilter.apply",
|
||||
"Apply SVG Filter",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?, item?} apply the document's SVG filter `name` (svgFilter.list) to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn filters_json(d: &Document) -> Value {
|
||||
json!(d.svg_filters.iter().map(|f| json!({ "name": f.name, "xml": f.xml })).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and not empty.
|
||||
fn name_param(p: &Value, cmd: &str) -> Result<String> {
|
||||
let n = text_param(p, "name", cmd)?.map(str::trim).filter(|n| !n.is_empty());
|
||||
n.map(str::to_string).ok_or_else(|| bad(cmd, "give `name`, an SVG filter's name"))
|
||||
}
|
||||
|
||||
/// Is `e` an `svg.filter` effect that names filter `name`?
|
||||
fn names(e: &vectorcraft_doc::Effect, name: &str) -> bool {
|
||||
e.id == effects::SVG_FILTER && e.params.get("name").and_then(Value::as_str) == Some(name)
|
||||
}
|
||||
|
||||
/// The `svg.filter` effects of appearance `a` (its own and its fills' and strokes') that name
|
||||
/// filter `name`.
|
||||
fn named<'a>(a: &'a Appearance, name: &'a str) -> impl Iterator<Item = &'a vectorcraft_doc::Effect> + 'a {
|
||||
let items = a.items.iter().flat_map(|i| i.effects().iter());
|
||||
a.effects.iter().chain(items).filter(move |e| names(e, name))
|
||||
}
|
||||
|
||||
/// Make the effects of appearance `a` that name filter `name` draw with `xml`.
|
||||
fn update_appearance(a: &mut Appearance, name: &str, xml: &str) {
|
||||
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in a.effects.iter_mut().chain(items) {
|
||||
if names(e, name) && e.params.is_object() {
|
||||
e.params["xml"] = json!(xml);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does an effect in `d` that names filter `name` draw with something other than `xml` (`""`:
|
||||
/// nothing)? Symbol definitions, graph designs, patterns, opacity masks and graphic styles count.
|
||||
fn out_of_step(d: &Document, name: &str, xml: &str) -> bool {
|
||||
let stale = |a: &Appearance| named(a, name).any(|e| e.params.get("xml").and_then(Value::as_str) != Some(xml));
|
||||
d.any_node(|n| stale(&n.appearance)) || d.graphic_styles.iter().any(|s| stale(&s.appearance))
|
||||
}
|
||||
|
||||
/// Make every effect in `d` that names filter `name` draw with `xml` (`""` when the document no
|
||||
/// longer has the filter: the effect keeps its name and draws nothing), symbol definitions, graph
|
||||
/// designs, patterns, opacity masks and graphic styles included.
|
||||
fn update_users(d: &mut Document, name: &str, xml: &str) {
|
||||
// Through `DerefMut` only for an appearance that has such an effect (it is shared copy-on-write).
|
||||
d.edit_nodes_where(|n| named(&n.appearance, name).next().is_some(), |n| update_appearance(&mut n.appearance, name, xml));
|
||||
for s in d.graphic_styles.iter_mut().filter(|s| named(&s.appearance, name).next().is_some()) {
|
||||
update_appearance(&mut s.appearance, name, xml);
|
||||
}
|
||||
}
|
||||
|
||||
fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.define";
|
||||
let xml = match p.get("xml") {
|
||||
Some(Value::String(x)) => x.trim().to_string(),
|
||||
Some(_) => return Err(bad(C, "`xml` must be a string")),
|
||||
None => return Err(bad(C, "give `xml`, one SVG <filter> element")),
|
||||
};
|
||||
let replace = match p.get("replace") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(r)) => Some(r.trim().to_string()),
|
||||
Some(_) => return Err(bad(C, "`replace` must be a string")),
|
||||
};
|
||||
svg_filter::check(&xml).map_err(|e| bad(C, e))?;
|
||||
let filters = &s.doc()?.doc.svg_filters;
|
||||
let at = match &replace {
|
||||
Some(r) => Some(filters.iter().position(|f| f.name == *r).ok_or_else(|| bad(C, format!("the document has no SVG filter named {r:?}")))?),
|
||||
None => None,
|
||||
};
|
||||
// An edited filter keeps its name, whatever id its new code gives it.
|
||||
let xml = match &replace {
|
||||
Some(r) => svg_filter::with_id(&xml, r).ok_or_else(|| bad(C, "give one <filter> element"))?,
|
||||
None => xml,
|
||||
};
|
||||
let name = svg_filter::check(&xml).map_err(|e| bad(C, e))?;
|
||||
if filters.iter().enumerate().any(|(i, f)| f.name == name && Some(i) != at) {
|
||||
return Err(bad(C, format!("the document already has an SVG filter named {name:?}")));
|
||||
}
|
||||
if at.is_none() && filters.len() >= SvgFilter::MAX {
|
||||
return Err(bad(C, format!("a document holds at most {} SVG filters", SvgFilter::MAX)));
|
||||
}
|
||||
let new = SvgFilter { name: name.clone(), xml };
|
||||
// Nothing to record when the filter, and every object that uses it, is already as given.
|
||||
if at.and_then(|i| filters.get(i)) != Some(&new) || out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
|
||||
let label = if at.is_some() { "Edit SVG Filter" } else { "New SVG Filter" };
|
||||
s.edit(label, |d, _| {
|
||||
update_users(d, &new.name, &new.xml);
|
||||
match at.and_then(|i| d.svg_filters.get_mut(i)) {
|
||||
Some(f) => *f = new,
|
||||
None => d.svg_filters.push(new),
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.delete";
|
||||
let name = name_param(p, C)?;
|
||||
if !s.doc()?.doc.svg_filters.iter().any(|f| f.name == name) {
|
||||
return Err(bad(C, format!("the document has no SVG filter named {name:?}")));
|
||||
}
|
||||
s.edit("Delete SVG Filter", |d, _| {
|
||||
d.svg_filters.retain(|f| f.name != name);
|
||||
update_users(d, &name, "");
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
/// The bytes of `p`'s `path` (an SVG file, read up to [`MAX_IMPORT_BYTES`]) or `svg`.
|
||||
fn import_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {
|
||||
let bytes = match (text_param(p, "path", cmd)?, text_param(p, "svg", cmd)?) {
|
||||
// One byte past the cap is enough to refuse the file below.
|
||||
(Some(path), _) => read_file_head(&absolute_path(path), MAX_IMPORT_BYTES + 1)?,
|
||||
(None, Some(svg)) => svg.as_bytes().to_vec(),
|
||||
_ => return Err(bad(cmd, "give `path`, an SVG file, or `svg`, SVG text")),
|
||||
};
|
||||
if bytes.len() > MAX_IMPORT_BYTES {
|
||||
return Err(bad(cmd, format!("the SVG file is larger than {MAX_IMPORT_BYTES} bytes")));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.import";
|
||||
let bytes = import_bytes(p, C)?;
|
||||
// SVGZ would unpack past the size read above.
|
||||
if vectorcraft_svg::is_svgz(&bytes) {
|
||||
return Err(bad(C, "Import SVG Filter reads SVG files, not SVGZ"));
|
||||
}
|
||||
let text = vectorcraft_svg::text_of(&bytes).map_err(|e| bad(C, format!("the file isn't valid SVG: {e}")))?;
|
||||
let held = s.doc()?.doc.svg_filters.clone();
|
||||
let room = SvgFilter::MAX.saturating_sub(held.len());
|
||||
// Filters past the room left and names the document has are left out unchecked.
|
||||
let (found, skipped) = vectorcraft_svg::svg_filters(&text, room, |name| held.iter().any(|f| f.name == name))
|
||||
.map_err(|e| bad(C, format!("the file isn't valid SVG: {e}")))?;
|
||||
let added: Vec<SvgFilter> = found.into_iter().map(|(name, xml)| SvgFilter { name, xml }).collect();
|
||||
let names: Vec<String> = added.iter().map(|f| f.name.clone()).collect();
|
||||
if !added.is_empty() {
|
||||
s.edit("Import SVG Filter", |d, _| {
|
||||
for f in &added {
|
||||
update_users(d, &f.name, &f.xml);
|
||||
}
|
||||
d.svg_filters.extend(added);
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(json!({ "added": names, "skipped": skipped, "filters": filters_json(&s.doc()?.doc) }))
|
||||
}
|
||||
|
||||
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "svgFilter.apply";
|
||||
let name = name_param(p, C)?;
|
||||
let f = s.doc()?.doc.svg_filters.iter().find(|f| f.name == name).cloned();
|
||||
let f = f.ok_or_else(|| bad(C, format!("the document has no SVG filter named {name:?}")))?;
|
||||
let mut q = json!({ "effect": effects::SVG_FILTER, "params": { "name": f.name, "xml": f.xml } });
|
||||
for key in ["ids", "id", "item"] {
|
||||
if let Some(v) = p.get(key) {
|
||||
q[key] = v.clone();
|
||||
}
|
||||
}
|
||||
super::effectcmd::apply(s, &q)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user