mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 04:51:52 +00:00
Merge pull request #7658 from dotCooCoo/feat/svg-filter-defaults
Effects: Effect › SVG Filters lists default filters
This commit is contained in:
@@ -718,7 +718,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// 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; a hidden one has its given values checked. → `{ids}`.
|
||||
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.setParams";
|
||||
let index = index_param(p, "index", C)?;
|
||||
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! The default filters ([`svg_filter::defaults`]) are listed for every document. Applying or
|
||||
//! editing one adds a copy to the document under the default's name, and from then on that copy is
|
||||
//! the filter of that name. Deleting the copy lists the default again.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Appearance, Document, SvgFilter};
|
||||
use vectorcraft_render::effects::svg_filter::defaults::{DEFAULT_FILTERS, default_filter};
|
||||
use vectorcraft_render::effects::{self, svg_filter};
|
||||
|
||||
use super::fileio::{absolute_path, read_file_head};
|
||||
@@ -21,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"SVG Filters",
|
||||
[],
|
||||
None,
|
||||
"{} → {filters: [{name, xml}…]} the SVG filters the document holds, in the SVG Filters submenu's order",
|
||||
"{} → {filters: [{name, xml}…], defaults: [{name, xml, inDocument}…]} filters: the SVG filters the document holds, in the order they were added; defaults: the default filters every document lists (VectorCraft's own set), with inDocument true when the document holds a filter of that name, which then stands in the default's place. The SVG Filters submenu and Apply SVG Filter list the defaults first, then the document's other filters",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -30,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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}",
|
||||
"{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 of the document has is refused and a document holds at most 64 filters; replace with the name of a default filter the document does not hold adds the edited copy to the document under that name, and code equal to the default's adds nothing; a new filter may take a default's name, and then stands in its place → {name, filters}",
|
||||
has_doc,
|
||||
define
|
||||
),
|
||||
@@ -39,7 +44,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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}",
|
||||
"{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, or the default of that name is applied; a default filter the document holds no copy of is refused (the defaults are not deleted), and deleting the document's copy of one lists the default again → {filters}",
|
||||
has_doc,
|
||||
delete
|
||||
),
|
||||
@@ -57,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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}",
|
||||
"{name, ids?|id?, item?, index?} apply the document's SVG filter `name`, or the default filter of that name when the document holds none (svgFilter.list), to ids or the selection as a live svg.filter effect, as one undo step, like effect.apply → {ids, index, item}; with index, the filter takes the place of the applied svg.filter effect at index of item, like effect.setParams → {ids}; a default is copied into the document in the same undo step, which is refused when the document already holds 64 filters",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -69,7 +74,10 @@ fn filters_json(d: &Document) -> Value {
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "filters": filters_json(&s.doc()?.doc) }))
|
||||
let d = &s.doc()?.doc;
|
||||
let held = |name: &str| d.svg_filters.iter().any(|f| f.name == name);
|
||||
let defaults: Vec<Value> = DEFAULT_FILTERS.iter().map(|f| json!({ "name": f.name, "xml": f.xml, "inDocument": held(f.name) })).collect();
|
||||
Ok(json!({ "filters": filters_json(d), "defaults": defaults }))
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and not empty.
|
||||
@@ -132,10 +140,12 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
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,
|
||||
};
|
||||
let at = replace.as_ref().and_then(|r| filters.iter().position(|f| f.name == *r));
|
||||
// A default the document does not hold: its edited copy is added under the default's name.
|
||||
let default = replace.as_ref().filter(|_| at.is_none()).and_then(|r| default_filter(r));
|
||||
if let Some(r) = replace.as_ref().filter(|_| at.is_none() && default.is_none()) {
|
||||
return Err(bad(C, format!("the document has no SVG filter named {r:?}")));
|
||||
}
|
||||
// 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"))?,
|
||||
@@ -145,22 +155,28 @@ fn define(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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:?}")));
|
||||
}
|
||||
let new = SvgFilter { name: name.clone(), xml };
|
||||
// Nothing to record when the filter, and every object that uses it, is already as given: a
|
||||
// default saved with its own code stays out of the document.
|
||||
let as_given = match default {
|
||||
Some(d) => d.to_filter() == new,
|
||||
None => at.and_then(|i| filters.get(i)) == Some(&new),
|
||||
};
|
||||
if as_given && !out_of_step(&s.doc()?.doc, &new.name, &new.xml) {
|
||||
return Ok(json!({ "name": name, "filters": filters_json(&s.doc()?.doc) }));
|
||||
}
|
||||
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(())
|
||||
})?;
|
||||
}
|
||||
let label = if replace.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) }))
|
||||
}
|
||||
|
||||
@@ -168,6 +184,9 @@ 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) {
|
||||
if default_filter(&name).is_some() {
|
||||
return Err(bad(C, format!("{name:?} is a default SVG filter, and the document holds no copy of it to delete")));
|
||||
}
|
||||
return Err(bad(C, format!("the document has no SVG filter named {name:?}")));
|
||||
}
|
||||
s.edit("Delete SVG Filter", |d, _| {
|
||||
@@ -222,13 +241,79 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 } });
|
||||
let filters = &s.doc()?.doc.svg_filters;
|
||||
// The document's filter of that name, or the default of that name, which the document then takes.
|
||||
let (f, copied) = match (filters.iter().find(|f| f.name == name), default_filter(&name)) {
|
||||
(Some(f), _) => (f.clone(), false),
|
||||
(None, Some(_)) if filters.len() >= SvgFilter::MAX => {
|
||||
return Err(bad(C, format!("a document holds at most {} SVG filters, and applying a default filter adds it", SvgFilter::MAX)));
|
||||
}
|
||||
(None, Some(d)) => (d.to_filter(), true),
|
||||
(None, None) => return Err(bad(C, format!("the document has no SVG filter named {name:?}"))),
|
||||
};
|
||||
// A given `index`, null included, is checked as an index: only a missing one adds an effect.
|
||||
let replaces = p.get("index").is_some();
|
||||
let mut q = match replaces {
|
||||
true => json!({ "index": p["index"], "params": { "name": f.name, "xml": f.xml } }),
|
||||
false => 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)
|
||||
if !copied {
|
||||
return apply_as_given(s, p, &q, replaces, None);
|
||||
}
|
||||
// The effect and the copy are two edits joined into one step. The history keeps room for both
|
||||
// until they are joined, so the application lets one old step go at most, as any edit does.
|
||||
let limit = s.doc()?.history.limit;
|
||||
if let Some(st) = s.active_mut() {
|
||||
st.history.limit = limit.saturating_add(2);
|
||||
}
|
||||
let out = apply_as_given(s, p, &q, replaces, Some(f));
|
||||
if let Some(st) = s.active_mut() {
|
||||
st.history.limit = limit;
|
||||
st.history.trim();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`apply`] once the filter is known: the effect added (`q`) or put in the applied filter's place
|
||||
/// (`replaces`), and `copy`, a default's copy, added to the document in the same undo step.
|
||||
fn apply_as_given(s: &mut Session, p: &Value, q: &Value, replaces: bool, copy: Option<SvgFilter>) -> Result<Value> {
|
||||
const C: &str = "svgFilter.apply";
|
||||
let newest = s.doc()?.history.step().0;
|
||||
let out = if replaces {
|
||||
super::appearance::index_param(p, "index", C)?;
|
||||
// Only an applied SVG filter gives its place: another effect would take the filter's
|
||||
// parameters as its own.
|
||||
let edited = super::effectcmd::set_params_effects(s, q);
|
||||
if edited.is_empty() || edited.iter().any(|e| e != effects::SVG_FILTER) {
|
||||
return Err(bad(C, "`index` must be the index of an applied SVG filter"));
|
||||
}
|
||||
super::effectcmd::set_params(s, q)?
|
||||
} else {
|
||||
super::effectcmd::apply(s, q)?
|
||||
};
|
||||
if let Some(f) = copy {
|
||||
// The copy joins the step that applied it, under that step's name. That step is found by
|
||||
// its document, not its place: in an undo group both edits join the group's one step.
|
||||
let h = &s.doc()?.history;
|
||||
let applied = h.undo.last().filter(|_| h.step().0 != newest).map(|step| (step.label.clone(), step.doc.clone()));
|
||||
let label = applied.as_ref().map_or_else(|| "SVG Filter".to_string(), |(l, _)| l.clone());
|
||||
s.edit(&label, |d, _| {
|
||||
update_users(d, &f.name, &f.xml);
|
||||
d.svg_filters.push(f);
|
||||
Ok(())
|
||||
})?;
|
||||
let undo = &s.doc()?.history.undo;
|
||||
let below = undo.len().checked_sub(2);
|
||||
if let (Some(at), Some((_, doc))) = (below, &applied)
|
||||
&& undo.get(at).is_some_and(|e| std::sync::Arc::ptr_eq(&e.doc, doc))
|
||||
{
|
||||
super::menucmds::squash(s, at, &label);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user