mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
- A group with fill or stroke rows of its own stays whole, so its members keep the paint the group draws for them. - A clipping group whose shown clipped artwork overlaps a locked artboard stays whole even when its clipping path lies off the artboard, including when a target inside it is named by `ids`. Hidden artwork, art in pattern editing mode and runs with `clipGroups` false do not count.
423 lines
19 KiB
Rust
423 lines
19 KiB
Rust
//! Artwork Cleanup's Release All Containers (`addon.cleanup.releaseAll`): every group, clipping
|
|
//! mask and compound path in the selection, the objects named or the whole document, taken apart
|
|
//! at every level of nesting as one undo step, so that only the objects they held are left.
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::sync::Arc;
|
|
|
|
use serde_json::{Value, json};
|
|
use vectorcraft_doc::{Document, LiveShape, LockedArtboards, Node, NodeId, NodeKind};
|
|
use vectorcraft_geom::PathData;
|
|
use vectorcraft_tools::builder::is_live_paint;
|
|
|
|
use super::checks::{MAX_OBJECTS, Scope};
|
|
use super::{named, retain_targets, scope_of};
|
|
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
|
use crate::{EngineError, Result, Session};
|
|
|
|
/// The command.
|
|
const COMMAND: &str = "addon.cleanup.releaseAll";
|
|
|
|
pub(super) fn specs() -> Vec<CommandSpec> {
|
|
vec![cmd!(
|
|
"addon.cleanup.releaseAll",
|
|
"Release All Containers…",
|
|
["Object", "Plug-ins", "Artwork Cleanup"],
|
|
None,
|
|
"{scope?: \"selection\"|\"document\" (default: the selection, or the document while nothing is selected), ids?: [id…] (the objects, groups and layers to release in, instead of `scope`; duplicate ids are an error), groups?: bool (true: groups are ungrouped), clipGroups?: bool (true: clipping groups are ungrouped and layers stop clipping unless their clipping path or clipped artwork overlaps a locked artboard, their released clipping paths kept as plain paths), compoundPaths?: bool (true: compound paths, and paths of several subpaths, become one path per subpath); at least one of the three true; `scope` and the three are never null} take apart every container of the kinds asked for, at every level of nesting, as one undo step when one goes; layers stay; each object keeps the opacity of the groups and compound paths it was in, and a compound path's paths take its paint; objects with live effects on their appearance or fill and stroke rows, groups with fill or stroke rows of their own, objects with an opacity mask, compound shapes, Live Paint groups, graphs, dimensions, flares, Objects on Path, generated art, Shaper Groups, Image Trace objects, paths with Live Corners, blends, envelopes, repeats, intertwines and other live objects stay whole, including directly selected or named descendants; the entire clipping mask subtree of a clipping group or layer that stays is left as it is, including directly selected or named descendants; from the selection or the document, locked and hidden objects, and objects on a locked artboard, stay whole; named by `ids`, locked and hidden ones are taken apart too (their objects become locked or hidden as they were), but not those on a locked artboard; the selection keeps what it held, each object taken apart replaced by what it left, locked and hidden objects left out → {scope (\"selection\", \"document\" or \"ids\"), ids (the objects selected), groups, clipGroups, compoundPaths (how many of each were released)}",
|
|
has_doc,
|
|
release_all
|
|
)]
|
|
}
|
|
|
|
/// The kinds of container a request takes apart.
|
|
#[derive(Clone, Copy)]
|
|
struct Kinds {
|
|
groups: bool,
|
|
clips: bool,
|
|
compounds: bool,
|
|
}
|
|
|
|
impl Kinds {
|
|
/// Whether a group is taken apart: a clipping group (`clip`) with `clips`, another with `groups`.
|
|
fn takes_group(self, clip: bool) -> bool {
|
|
if clip { self.clips } else { self.groups }
|
|
}
|
|
}
|
|
|
|
/// One run over the objects: what it takes apart and what it found.
|
|
struct Release<'a> {
|
|
kinds: Kinds,
|
|
/// Locked and hidden objects are taken apart too.
|
|
named: bool,
|
|
/// The artwork on a locked artboard, which stays whole.
|
|
held: &'a HashSet<NodeId>,
|
|
/// Groups, clipping groups and layers, and compound paths released.
|
|
counts: [usize; 3],
|
|
/// Objects made from the containers taken apart.
|
|
made: usize,
|
|
/// Each container taken apart and the objects left in its place.
|
|
left: HashMap<NodeId, Vec<NodeId>>,
|
|
}
|
|
|
|
/// Whether `n` stays whole whatever is asked: a live object kept as a group or compound path
|
|
/// (a compound shape, Live Paint group, graph, dimension, flare, Objects on Path, generated art,
|
|
/// Shaper Group, Image Trace object, a clipping path's painted pieces), a path with Live Corners,
|
|
/// whose parts would lose their editable corners, one with an opacity mask or live effects
|
|
/// on its appearance or fill and stroke rows, or a group with fill or stroke rows of its own.
|
|
fn live(n: &Node) -> bool {
|
|
let x = n.extras();
|
|
matches!(&n.kind, NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. })
|
|
|| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))
|
|
|| !n.appearance.effects.is_empty()
|
|
|| n.appearance.items.iter().any(|item| !item.effects().is_empty())
|
|
|| x.mask.is_some()
|
|
|| x.shaper.is_some()
|
|
|| x.trace.is_some()
|
|
|| x.graph.is_some()
|
|
|| x.dimension.is_some()
|
|
|| x.flare.is_some()
|
|
|| x.objects_on_path.is_some()
|
|
|| x.generated.is_some()
|
|
|| x.live_paint_gaps.is_some()
|
|
|| x.clip_pieces
|
|
|| (matches!(&n.kind, NodeKind::Group { .. }) && !n.appearance.items.is_empty())
|
|
|| n.is_compound_shape()
|
|
|| is_live_paint(n)
|
|
}
|
|
|
|
/// The artwork under `n` is added to `out`.
|
|
fn candidates(n: &Node, clips: bool, out: &mut Vec<NodeId>) {
|
|
let candidate = match &n.kind {
|
|
NodeKind::Layer { .. } => false,
|
|
NodeKind::Group { .. } | NodeKind::Compound { .. } => true,
|
|
NodeKind::Path { path, .. } => clips || path.subpaths.len() > 1,
|
|
_ => clips,
|
|
};
|
|
if candidate {
|
|
out.push(n.id);
|
|
}
|
|
if let Some(children) = n.children() {
|
|
children.iter().for_each(|c| candidates(c, clips, out));
|
|
}
|
|
}
|
|
|
|
impl Release<'_> {
|
|
fn total(&self) -> usize {
|
|
self.counts.iter().sum()
|
|
}
|
|
|
|
/// Whether `n` is left as it is: locked or hidden (unless named), on a locked artboard, or live.
|
|
fn keeps(&self, n: &Node) -> bool {
|
|
(!self.named && (n.locked || !n.visible)) || self.held.contains(&n.id) || live(n)
|
|
}
|
|
|
|
/// `n` with the containers in it released, into `out`; `member` counts what a container left.
|
|
fn node(&mut self, d: &mut Document, n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
|
|
if self.keeps(&n) {
|
|
if member {
|
|
self.made(1)?;
|
|
}
|
|
out.push(n);
|
|
return Ok(());
|
|
}
|
|
match &n.kind {
|
|
NodeKind::Group { clip, .. } if self.kinds.takes_group(*clip) => {
|
|
let clip = *clip;
|
|
self.counts[usize::from(clip)] += 1;
|
|
self.take_apart(d, n, clip, false, out)
|
|
}
|
|
NodeKind::Compound { .. } if self.kinds.compounds => {
|
|
self.counts[2] += 1;
|
|
self.take_apart(d, n, false, true, out)
|
|
}
|
|
NodeKind::Path { path, clipping: false, guide: false, .. } if self.kinds.compounds && path.subpaths.len() > 1 => {
|
|
self.counts[2] += 1;
|
|
self.split(d, (*n).clone(), out)
|
|
}
|
|
NodeKind::Group { .. } | NodeKind::Layer { .. } => self.keep(d, n, member, out),
|
|
_ => {
|
|
if member {
|
|
self.made(1)?;
|
|
}
|
|
out.push(n);
|
|
Ok(())
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Group or compound path `n` replaced by its members, released in turn. Members take on the
|
|
/// container's opacity, are hidden when it was hidden and locked when it was locked; a
|
|
/// compound path's take its paint; a clipping group's clipping path becomes a plain path.
|
|
fn take_apart(&mut self, d: &mut Document, n: Arc<Node>, clip: bool, compound: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
|
|
let Some(children) = n.children() else { return Ok(()) };
|
|
let mut parts = vec![];
|
|
for (k, c) in children.iter().enumerate() {
|
|
let mut c = (**c).clone();
|
|
if clip
|
|
&& k == 0
|
|
&& let NodeKind::Path { clipping, .. } = &mut c.kind
|
|
{
|
|
*clipping = false;
|
|
}
|
|
if compound {
|
|
c.appearance = n.appearance.clone();
|
|
if n.extras().pixel_aligned {
|
|
c.extras_mut().pixel_aligned = true;
|
|
}
|
|
}
|
|
c.opacity *= n.opacity;
|
|
c.visible &= n.visible;
|
|
c.locked |= n.locked;
|
|
self.node(d, Arc::new(c), true, &mut parts)?;
|
|
}
|
|
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
|
|
out.extend(parts);
|
|
Ok(())
|
|
}
|
|
|
|
/// Path `n` of several subpaths as one path per subpath with its paint, in the same stacking
|
|
/// order; the first keeps its id.
|
|
fn split(&mut self, d: &mut Document, n: Node, out: &mut Vec<Arc<Node>>) -> Result<()> {
|
|
let Some(path) = n.path_data() else { return Ok(()) };
|
|
if self.made.saturating_add(path.subpaths.len()) > MAX_OBJECTS {
|
|
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
|
|
}
|
|
let mut template = n.clone();
|
|
if let NodeKind::Path { path, live, .. } = &mut template.kind {
|
|
(*path, *live) = (PathData::single(Default::default()), None);
|
|
}
|
|
let mut parts = Vec::with_capacity(path.subpaths.len());
|
|
for (k, sp) in path.subpaths.iter().enumerate() {
|
|
let mut c = if k == 0 { template.clone() } else { d.reid(&template) };
|
|
if let NodeKind::Path { path, live, .. } = &mut c.kind {
|
|
(*path, *live) = (PathData::single(sp.clone()), None);
|
|
}
|
|
parts.push(Arc::new(c));
|
|
}
|
|
self.made(parts.len())?;
|
|
self.left.insert(n.id, parts.iter().map(|p| p.id).collect());
|
|
out.extend(parts);
|
|
Ok(())
|
|
}
|
|
|
|
/// Group or layer `n` kept, with the containers in it released. A layer stops clipping when
|
|
/// clipping groups are released; the clipping path of a group or layer that still clips is
|
|
/// left as it is. Unchanged, `n` itself goes to `out`.
|
|
fn keep(&mut self, d: &mut Document, mut n: Arc<Node>, member: bool, out: &mut Vec<Arc<Node>>) -> Result<()> {
|
|
if member {
|
|
self.made(1)?;
|
|
}
|
|
let before = self.total();
|
|
let mut clips = n.clips();
|
|
if clips && n.is_layer() && self.kinds.clips && !n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c))) {
|
|
self.counts[1] += 1;
|
|
let n = Arc::make_mut(&mut n);
|
|
n.set_clips(false);
|
|
clips = false;
|
|
if let Some(first) = n.children_mut().and_then(|c| c.first_mut())
|
|
&& let NodeKind::Path { clipping, .. } = &mut Arc::make_mut(first).kind
|
|
{
|
|
*clipping = false;
|
|
}
|
|
}
|
|
let Some(children) = n.children() else {
|
|
out.push(n);
|
|
return Ok(());
|
|
};
|
|
let mut kept = Vec::with_capacity(children.len());
|
|
for (k, c) in children.iter().enumerate() {
|
|
if clips && k == 0 {
|
|
if member {
|
|
self.made(1)?;
|
|
}
|
|
kept.push(Arc::clone(c));
|
|
} else {
|
|
self.node(d, Arc::clone(c), member, &mut kept)?;
|
|
}
|
|
}
|
|
if self.total() != before
|
|
&& let Some(ch) = Arc::make_mut(&mut n).children_mut()
|
|
{
|
|
*ch = kept;
|
|
}
|
|
out.push(n);
|
|
Ok(())
|
|
}
|
|
|
|
fn holds_art(&self, n: &Node) -> bool {
|
|
self.held.contains(&n.id) || n.children().is_some_and(|children| children.iter().any(|c| self.holds_art(c)))
|
|
}
|
|
|
|
/// Counts the objects made, refusing a run that makes too many.
|
|
fn made(&mut self, count: usize) -> Result<()> {
|
|
self.made += count;
|
|
if self.made > MAX_OBJECTS {
|
|
return Err(EngineError::Other("Release All Containers: too many objects to release at once".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `id`, or the objects left in its place when it was taken apart.
|
|
fn replaced(&self, id: NodeId, into: &mut Vec<NodeId>) {
|
|
match self.left.get(&id) {
|
|
Some(ids) => into.extend(ids),
|
|
None => into.push(id),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether shown artwork in `n` overlaps a locked artboard: a plain group that is not live
|
|
/// ([`live`]) by its shown members, anything else by its own bounds.
|
|
fn shows_on(locks: &LockedArtboards<'_>, n: &Node) -> bool {
|
|
if !n.visible {
|
|
return false;
|
|
}
|
|
match (&n.kind, n.children()) {
|
|
(NodeKind::Group { clip: false, .. }, Some(children)) if !live(n) => children.iter().any(|c| shows_on(locks, c)),
|
|
_ => locks.holds(n),
|
|
}
|
|
}
|
|
|
|
/// Whether `id` is in the clipping mask subtree of a clipping group or layer.
|
|
fn in_clipping_mask(d: &Document, id: NodeId) -> bool {
|
|
d.ancestry(id).is_some_and(|chain| {
|
|
chain
|
|
.windows(2)
|
|
.any(|pair| d.node(pair[0]).is_some_and(|p| p.clips() && p.children().and_then(|c| c.first()).is_some_and(|c| c.id == pair[1])))
|
|
})
|
|
}
|
|
|
|
fn release_all(s: &mut Session, p: &Value) -> Result<Value> {
|
|
if !p.is_object() {
|
|
return Err(bad(COMMAND, "parameters must be an object"));
|
|
}
|
|
for key in ["groups", "clipGroups", "compoundPaths"] {
|
|
if p.get(key).is_some_and(|v| !v.is_boolean()) {
|
|
return Err(bad(COMMAND, format!("`{key}` must be true or false")));
|
|
}
|
|
}
|
|
if p.get("scope").is_some_and(|v| !matches!(v.as_str(), Some("selection" | "document"))) {
|
|
return Err(bad(COMMAND, "`scope` must be \"selection\" or \"document\""));
|
|
}
|
|
if let Some(ids) = p.get("ids").filter(|v| !v.is_null()) {
|
|
let ids = ids.as_array().ok_or_else(|| bad(COMMAND, "`ids` must be an array of non-negative integer object ids"))?;
|
|
let mut seen = HashSet::new();
|
|
for id in ids {
|
|
let id = id.as_u64().ok_or_else(|| bad(COMMAND, "`ids` must contain non-negative integer object ids"))?;
|
|
if !seen.insert(id) {
|
|
return Err(bad(COMMAND, format!("duplicate object id {id} in `ids`")));
|
|
}
|
|
}
|
|
}
|
|
let kinds = Kinds {
|
|
groups: switch_or(p, "groups", true, COMMAND)?,
|
|
clips: switch_or(p, "clipGroups", true, COMMAND)?,
|
|
compounds: switch_or(p, "compoundPaths", true, COMMAND)?,
|
|
};
|
|
if !(kinds.groups || kinds.clips || kinds.compounds) {
|
|
return Err(bad(COMMAND, "`groups`, `clipGroups` and `compoundPaths` are all false: there is nothing to release"));
|
|
}
|
|
let named = named(p);
|
|
if named && p.get("scope").is_some() {
|
|
return Err(bad(COMMAND, "give `scope` or `ids`, not both"));
|
|
}
|
|
let (roots, name) = if named {
|
|
let mut roots = checked_ids_or_selection(s, p, COMMAND)?;
|
|
retain_targets(&s.doc()?.doc, &mut roots, true, |id| *id);
|
|
(roots, "ids")
|
|
} else {
|
|
match scope_of(s, p, COMMAND)? {
|
|
(Scope::Document, name) => (s.doc()?.doc.layers.iter().map(|l| l.id).collect(), name),
|
|
(Scope::Objects(mut roots), name) => {
|
|
retain_targets(&s.doc()?.doc, &mut roots, false, |id| *id);
|
|
(roots, name)
|
|
}
|
|
}
|
|
};
|
|
let st = s.doc()?;
|
|
let (mut d, mut sel) = ((*st.doc).clone(), st.selection.clone());
|
|
// The artwork on a locked artboard, found while nothing is changed yet.
|
|
let held: HashSet<NodeId> = if d.artboards.iter().any(|a| a.locked) {
|
|
let mut found = vec![];
|
|
for n in roots.iter().filter_map(|id| d.node(*id)) {
|
|
candidates(n, kinds.clips, &mut found);
|
|
}
|
|
let locks = d.locked_artboards();
|
|
let mut held: HashSet<NodeId> = found.iter().copied().filter(|id| locks.holds_id(*id)).collect();
|
|
// A shown clipping group whose clipped artwork overlaps a locked artboard stays whole,
|
|
// wherever its clipping path lies, when clipping groups are released; the clipping groups
|
|
// the targets are in count too.
|
|
let ancestors = roots.iter().filter_map(|id| d.ancestry(*id)).flatten();
|
|
let clip_groups: HashSet<NodeId> = found
|
|
.iter()
|
|
.copied()
|
|
.chain(ancestors)
|
|
.filter(|id| kinds.clips && d.node(*id).is_some_and(|n| matches!(&n.kind, NodeKind::Group { clip: true, .. })))
|
|
.collect();
|
|
// Pattern editing mode's art is on no artboard.
|
|
let pattern_layer = d.pattern_edit.as_ref().map(|e| e.layer);
|
|
for id in clip_groups {
|
|
let shown = d.ancestry(id).is_some_and(|chain| chain.iter().all(|a| Some(*a) != pattern_layer && d.node(*a).is_some_and(|n| n.visible)));
|
|
if shown
|
|
&& let Some(n) = d.node(id)
|
|
&& n.children().is_some_and(|c| c.iter().skip(1).any(|c| shows_on(&locks, c)))
|
|
{
|
|
held.insert(id);
|
|
}
|
|
}
|
|
held
|
|
} else {
|
|
HashSet::new()
|
|
};
|
|
let mut run = Release { kinds, named, held: &held, counts: [0; 3], made: 0, left: HashMap::new() };
|
|
let mut items = vec![];
|
|
for id in roots {
|
|
// Direct targets inside a live object or clipping mask stay whole.
|
|
let protected =
|
|
d.ancestry(id).is_some_and(|chain| chain.iter().take(chain.len().saturating_sub(1)).filter_map(|id| d.node(*id)).any(|n| run.keeps(n)));
|
|
if in_clipping_mask(&d, id) || protected {
|
|
continue;
|
|
}
|
|
let Some(n) = d.node_arc(id).cloned() else { continue };
|
|
let before = run.total();
|
|
let mut out = vec![];
|
|
run.node(&mut d, n, false, &mut out)?;
|
|
if run.total() != before {
|
|
items.push((id, out.into_iter().map(Arc::unwrap_or_clone).collect()));
|
|
}
|
|
}
|
|
let [groups, clips, compounds] = run.counts;
|
|
// With nothing to release, the document, the selection and the undo history stay as they are.
|
|
if run.total() == 0 {
|
|
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
|
|
return Ok(json!({ "scope": name, "ids": ids, "groups": 0, "clipGroups": 0, "compoundPaths": 0 }));
|
|
}
|
|
d.insert_beside(items, true)?;
|
|
let mut ids = vec![];
|
|
for id in sel.objects.iter() {
|
|
run.replaced(*id, &mut ids);
|
|
}
|
|
// Locked and hidden objects, and those in locked or hidden groups, are not selected.
|
|
{
|
|
let editable = d.editable();
|
|
ids.retain(|id| editable(*id));
|
|
}
|
|
let kept: HashSet<NodeId> = ids.iter().copied().collect();
|
|
let removed: Vec<NodeId> = sel.objects.iter().copied().filter(|id| run.left.contains_key(id) || !kept.contains(id)).collect();
|
|
sel.remove_all(removed);
|
|
let mut seen = HashSet::new();
|
|
sel.objects = ids.into_iter().filter(|id| seen.insert(*id)).collect();
|
|
sel.prune(&d);
|
|
let ids: Vec<u64> = sel.objects.iter().map(|i| i.0).collect();
|
|
s.edit("Release All Containers", |doc, selection| {
|
|
*doc = d;
|
|
*selection = sel;
|
|
Ok(())
|
|
})?;
|
|
Ok(json!({ "scope": name, "ids": ids, "groups": groups, "clipGroups": clips, "compoundPaths": compounds }))
|
|
}
|