Merge main into fix/plugin-grant-app-approval

This commit is contained in:
dotCooCoo
2026-11-08 23:26:53 -08:00
23 changed files with 903 additions and 145 deletions
+17 -9
View File
@@ -1027,6 +1027,12 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
if !direct { clear(s, &json!({ "ids": roots, "guides": true })) } else { cut_direct_selection(s, &roots) }
}
/// Remove the geometry copied by a direct-selection Cut, including selected guides in one edit.
/// Select every surviving piece while retaining intentional compound-path structure.
/// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths
/// lose only the copied geometry. An exhausted partial path is removed, along with its compound
/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection
/// references with surviving object IDs.
fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let st = s.doc()?;
let sel = st.selection.clone();
@@ -1035,6 +1041,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
let gone = selection.guides.clone();
d.retain_guides(selection, |i, _| !gone.contains(&i));
let mut survivors = vec![];
let mut pieces = super::pathops::Beside::replacing(d, roots);
for id in roots {
let Some(node) = d.node(*id) else { continue };
let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id);
@@ -1042,20 +1049,22 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
d.remove(*id)?;
continue;
}
let Some(path) = node.path_data() else {
if node.path_data().is_none() {
d.remove(*id)?;
continue;
};
}
let original = super::path::deletion_source(d, *id)?;
let seg_refs = sel.segments.get(id);
let anchor_refs = sel.anchors.get(id);
let mut subpaths = Vec::new();
for (si, sp) in path.subpaths.iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(sp, si, seg_refs, anchor_refs);
let owned = std::mem::take(&mut super::path::path_mut(d, *id)?.subpaths);
for (si, sp) in owned.into_iter().enumerate() {
let cuts = super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs);
if cuts.is_empty() {
subpaths.push(sp.clone());
subpaths.push(sp);
} else {
subpaths.extend(super::path::without_segments(sp.clone(), &cuts));
subpaths.extend(super::path::without_segments(sp, &cuts));
}
}
subpaths.retain(|sp| sp.anchors.len() >= 2);
@@ -1068,11 +1077,10 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
d.remove(p)?;
}
} else {
let path_node = super::path::path_mut(d, *id)?;
path_node.subpaths = subpaths;
survivors.push(*id);
survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?);
}
}
pieces.finish(d)?;
selection.set(survivors);
selection.anchors.clear();
selection.segments.clear();
+57 -10
View File
@@ -1,6 +1,7 @@
//! Path editing commands (used by the Pen and Direct Selection tools and Object → Path).
use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling};
@@ -1206,6 +1207,11 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Delete direct-selected anchors or segments and whole selected objects in one edit.
/// Leave surviving pieces selected, splitting ordinary contours into independent sibling objects.
/// `p.guides: true` also removes the selected ruler guides in that edit; otherwise guides remain.
/// Layers are retained, and an object removed with a selected ancestor is not removed twice.
/// Returns JSON `null` on success; selection is replaced by the surviving object IDs.
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
@@ -1237,11 +1243,13 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
if d.node(*id).is_none() {
continue;
}
let remove_node = {
let original = deletion_source(d, *id)?;
let subpaths: Vec<SubPath> = {
let path = path_mut(d, *id)?;
let subpaths = std::mem::take(&mut path.subpaths);
if let Some(refs) = segments.get(id) {
// A segment pick cuts its connection, keeping every neighboring cubic.
path.subpaths = std::mem::take(&mut path.subpaths)
subpaths
.into_iter()
.enumerate()
.flat_map(|(si, sp)| {
@@ -1249,11 +1257,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
without_segments(sp, &cuts)
})
.filter(|s| s.anchors.len() >= 2)
.collect();
.collect()
} else {
// Remove every selected anchor against the original indexes, keeping surviving
// stretches separate rather than joining across deleted anchors.
path.subpaths = std::mem::take(&mut path.subpaths)
subpaths
.into_iter()
.enumerate()
.flat_map(|(si, sp)| {
@@ -1261,16 +1269,14 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
without_anchors(sp, &gone)
})
.filter(|s| s.anchors.len() >= 2)
.collect();
.collect()
}
path.subpaths.retain(|s| s.anchors.len() >= 2);
path.subpaths.is_empty()
};
if remove_node {
if subpaths.is_empty() {
emptied.put(d, *id, vec![])?;
} else {
// The remainder is selected whole, so the next Delete removes it.
survivors.push(*id);
// Every remaining piece is selected whole, so the next Delete removes them.
survivors.extend(replace_deleted_pieces(d, &mut emptied, original, subpaths)?);
}
}
emptied.finish(d)?;
@@ -1280,6 +1286,47 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Retain path `id` from `d` without copying its geometry before deletion takes its subpaths.
/// The shared snapshot supplies the original path classification and, only if needed, gradient
/// bounds after the working node's geometry has moved. Returns `NoNode` for a missing/non-path ID.
pub(super) fn deletion_source(d: &Document, id: NodeId) -> Result<Arc<Node>> {
let (parent, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
// Verify the cached position still names this path before retaining the shared node.
d.children(parent)
.and_then(|children| children.get(index))
.filter(|n| n.id == id && n.path_data().is_some())
.cloned()
.ok_or(EngineError::NoNode(id))
}
/// Replace the deleted path in `d` with the nonempty surviving runs in `subpaths`.
/// `original` must be retained by [`deletion_source`] before taking the working node's geometry.
/// An ordinary single-contour source becomes siblings; multi-subpath paths and compound members
/// retain their node. Only actual splits pin unplaced gradients to `original`'s bounds; already
/// placed gradients and connected remainders retain their placement behavior.
///
/// Returns the surviving IDs in `subpaths` order (the first keeps the source ID). The original
/// node's geometry is updated immediately. Replacements are handed to `beside`, which may defer
/// insertion; the caller must finish that [`Beside`] before using new IDs in `d`.
/// Missing/invalid paths return an error.
pub(super) fn replace_deleted_pieces(d: &mut Document, beside: &mut Beside, original: Arc<Node>, subpaths: Vec<SubPath>) -> Result<Vec<NodeId>> {
let id = original.id;
let single = original.path_data().is_some_and(|p| p.subpaths.len() == 1);
if single && compound_or_self(d, id) == id {
// Pin only actual splits: each new object's smaller bounds would otherwise refit its gradients.
if subpaths.len() > 1
&& original.appearance.has_unplaced_gradient()
&& let Some(bounds) = original.geometric_bounds()
{
d.node_mut(id).ok_or(EngineError::NoNode(id))?.appearance.pin_gradients(bounds);
}
super::draw2::replace_with_pieces(d, beside, id, subpaths.into_iter().map(PathData::single).collect())
} else {
path_mut(d, id)?.subpaths = subpaths;
Ok(vec![id])
}
}
/// Remove anchors and their incident segments, keeping each surviving stretch as an open path.
/// Only a closed path can have a surviving stretch that wraps past the last anchor.
fn without_anchors(sp: SubPath, removed: &BTreeSet<usize>) -> Vec<SubPath> {
+5 -6
View File
@@ -44,7 +44,6 @@
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
@@ -137,9 +136,9 @@ pub struct FilterRun {
params: Vec<u8>,
/// The objects the plug-in is given, and the container new objects go in.
inputs: Vec<NodeId>,
/// The type, images and symbol instances among them (a filter that asks for them), as given:
/// its output must return each one unchanged.
read_only: HashMap<NodeId, Value>,
/// The type, images and symbol instances among them (a filter that asks for them): its output
/// must return each one as `input` gives it. These are their places in `input`.
read_only: objects::ReadOnlySpans,
parent: Option<NodeId>,
/// The document it was made from, and that document's revision then.
document: (u64, u64),
@@ -273,7 +272,7 @@ impl FilterRun {
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
let out = objects::decode_output_with(output, &self.read_only).map_err(err)?;
let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?;
if out.document_data.is_some() && !may.contains(&Permission::State) {
return Err(not_granted(&m.name, Permission::State));
}
@@ -967,7 +966,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, with at most 16 MiB of pixels and 16 MiB of type runs per run (later ones come with pixelsOmitted or truncated); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}",
has_doc,
run
),
+36 -12
View File
@@ -2698,11 +2698,26 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1), (0, 2)].into());
s.execute("edit.copy", &json!({})).unwrap();
assert_eq!(pasted(&mut s), [2]);
// Cut takes the segment between them out of the path, as with Direct Selection chosen.
// Cut takes the segment between them. The two surviving runs of an ordinary path
// become independent objects, and this path keeps the first run (#3380).
s.execute("edit.undo", &json!({})).unwrap();
let original = path(&s, id);
let picked = s.doc().unwrap().selection.clone();
s.execute("edit.cut", &json!({})).unwrap();
let left = path(&s, id).subpaths.iter().map(|sp| sp.anchors.len()).collect::<Vec<_>>();
assert_eq!((s.clipboard.nodes.len(), left), (1, vec![2, 2]));
let left = paths(&s);
assert_eq!(left.len(), 2);
assert_eq!(left[0].0, id);
assert!(left.iter().all(|(_, p)| p.subpaths.len() == 1 && !p.subpaths[0].closed));
assert_eq!(left[0].1.subpaths[0].anchors, original.subpaths[0].anchors[..2]);
assert_eq!(left[1].1.subpaths[0].anchors, original.subpaths[0].anchors[2..]);
assert_eq!(s.doc().unwrap().selection.objects, left.iter().map(|(id, _)| *id).collect::<Vec<_>>());
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(paths(&s), left);
// Drawing on: the last anchor the Pen leaves selected doesn't make Copy take that anchor.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
@@ -3412,6 +3427,7 @@ fn a_filled_pencil_path_keeps_no_stroke() {
assert!(!s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_paint().is_none());
}
/// Interior and endpoint deletions preserve each surviving run without adding connecting segments.
#[test]
fn open_anchor_delete_splits_runs_without_new_connections() {
let cases = [
@@ -3439,16 +3455,19 @@ fn open_anchor_delete_splits_runs_without_new_connections() {
assert!(s.doc().unwrap().doc.node(id).is_none(), "only isolated points remain: {removed:?}");
assert!(s.doc().unwrap().selection.objects.is_empty());
} else {
let result = path(&s, id);
assert_eq!(result.subpaths.len(), expected.len(), "deleted anchors: {removed:?}");
for (sp, indices) in result.subpaths.iter().zip(&expected) {
let pieces = &s.doc().unwrap().selection.objects;
assert_eq!(pieces.len(), expected.len(), "deleted anchors: {removed:?}");
assert_eq!(pieces[0], id);
for (piece, indices) in pieces.iter().zip(&expected) {
let result = path(&s, *piece);
assert_eq!(result.subpaths.len(), 1);
let sp = &result.subpaths[0];
assert!(!sp.closed);
assert_eq!(sp.anchors.iter().map(|a| a.p).collect::<Vec<_>>(), indices.iter().map(|&i| original.anchors[i].p).collect::<Vec<_>>());
for (segment, pair) in indices.windows(2).enumerate() {
assert_eq!(sp.segment(segment), original.segment(pair[0]));
}
}
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
}
assert_eq!(undo_steps(&s), undo + 1);
assert!(s.doc().unwrap().selection.anchors.is_empty() && s.doc().unwrap().selection.segments.is_empty());
@@ -3547,6 +3566,7 @@ fn open_anchor_delete_does_not_change_explicit_remove_anchors() {
}
}
/// Baked transforms and mixed whole/partial selection survive splitting and atomic Undo/Redo.
#[test]
fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
use vectorcraft_geom::Affine;
@@ -3584,13 +3604,17 @@ fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
let st = s.doc().unwrap();
assert!(st.doc.node(whole).is_none());
assert_eq!(st.doc.node(untouched), before.node(untouched));
let result = path(&s, id);
assert_eq!(result.subpaths.len(), 2);
for (sp, segment) in result.subpaths.iter().zip([0, 3]) {
let pieces = st.selection.objects.clone();
assert_eq!(pieces.len(), 2);
assert_eq!(pieces[0], id);
for (piece, segment) in pieces.iter().zip([0, 3]) {
let result = path(&s, *piece);
assert_eq!(result.subpaths.len(), 1);
let sp = &result.subpaths[0];
assert_eq!(sp.segment_count(), 1);
assert_eq!(sp.segment(0), original.subpaths[0].segment(segment));
}
assert_eq!(st.selection.objects, vec![id]);
assert_eq!(st.selection.objects, pieces);
assert!(st.selection.anchors.is_empty() && st.selection.segments.is_empty());
assert_eq!(undo_steps(&s), undo + 1);
let after = st.doc.clone();
@@ -3599,7 +3623,7 @@ fn open_anchor_delete_after_transform_keeps_mixed_selection_atomic() {
assert_eq!(s.doc().unwrap().selection, selection);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, after);
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
assert_eq!(s.doc().unwrap().selection.objects, pieces);
}
}
+63
View File
@@ -1647,6 +1647,69 @@ fn read_only_kind_field_and_omission_refuse_without_undo() {
assert!(e.contains("`inputs` needs `api` 2"), "{e}");
}
/// A run past its memory budget fails before the plug-in starts, with the document and undo
/// history as they were: a read-only object whose other fields don't fit, a path and a compound
/// path that don't fit, and parameters past the input's half of the cap, with objects selected or
/// with none. The module has one page of memory, the most it may have, so a run that started would
/// report that the plug-in ran out of memory instead.
#[test]
fn a_run_past_the_memory_budget_fails_before_the_plugin_starts() {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
use vectorcraft_geom::FillRule;
use vectorcraft_plugins::{Limits, Plugin, registry};
let id = "test.engine.inputs.budget";
let params: Vec<String> = (0..9).map(|i| format!(r#""p{i}":{{"type":"string","maxLength":4096}}"#)).collect();
let manifest = format!(
r#"{{"id":"{id}","name":"Budget","kind":"filter","api":2,"permissions":["doc.read","doc.write"],"inputs":["type"],"params":{{{}}}}}"#,
params.join(",")
);
let module = wat::parse_str(tpl::module(&manifest, "unreachable", "", 1)).unwrap();
// One page of memory: the input and the parameters share 32 KiB.
registry::install(Plugin::load(&module, Limits { max_memory_bytes: 1 << 16, ..Limits::default() }).unwrap());
let mut s = session();
let small = rect(&mut s, 10.0, "#ff0000");
let long = rect(&mut s, 30.0, "#00ff00");
let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap());
let mut compound = NodeId(0);
s.edit("Set up", |d, _| {
d.node_mut(t).unwrap().name = Some("n".repeat(40_000));
let points: Vec<Point> = (0..4_000).map(|i| Point::new(f64::from(i), 0.0)).collect();
let outline = PathData::single(SubPath::polyline(&points, false));
if let NodeKind::Path { path, .. } = &mut d.node_mut(long).unwrap().kind {
*path = outline.clone();
}
let member = Node::path(d.alloc_id(), outline, Appearance::default());
let n = Node::new(d.alloc_id(), NodeKind::Compound { children: vec![Arc::new(member)], rule: FillRule::NonZero });
let layer = d.layers[0].id;
compound = d.insert(Some(layer), usize::MAX, n).unwrap();
Ok(())
})
.unwrap();
let padding: Value = (0..9).map(|i| (format!("p{i}"), json!("x".repeat(4096)))).collect::<serde_json::Map<_, _>>().into();
let too_large = "memory budget (the selection is too large to hand over)";
let named = format!("memory budget (object {} needs", t.0);
let with_padding = |ids: Vec<u64>| {
let mut p = padding.clone();
p["id"] = json!(id);
p["ids"] = json!(ids);
p
};
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
for (p, says) in [
(json!({"id": id, "ids": [t.0]}), named.as_str()),
(json!({"id": id, "ids": [long.0]}), too_large),
(json!({"id": id, "ids": [compound.0]}), too_large),
(with_padding(vec![small.0]), too_large),
(with_padding(vec![]), too_large),
] {
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
assert!(e.contains(says), "{says}: {e}");
assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{says}");
}
assert!(registry::remove(id));
}
/// What the user granted is kept in the plug-in store with the module: the next session installs
/// the plug-in again without asking. A stored plug-in that lists permissions nobody granted it is
/// skipped, even when another store granted it, and so is one in the Additional Plug-ins Folder