From 386c6c1d3eb923459111e9df0fb75c231a5c3722 Mon Sep 17 00:00:00 2001
From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com>
Date: Sat, 7 Nov 2026 13:45:31 +0100
Subject: [PATCH 01/13] Reject negative and fractional index in
image.savePreset
Found while testing crates/engine/src/cmd/image.rs:239 (save_preset, `index = num(p, "index").filter(..).map(|k| k as usize)`)
Co-Authored-By: Claude Haiku 5.5
Co-Authored-By: Claude Sonnet 5.5
---
crates/engine/src/cmd/image.rs | 7 +++++--
crates/engine/src/paint_tests.rs | 10 ++++++++++
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs
index 865e4d19a..37472b2d4 100644
--- a/crates/engine/src/cmd/image.rs
+++ b/crates/engine/src/cmd/image.rs
@@ -5,7 +5,7 @@ use figcraft_doc::{Document, ImagePreset, Node};
use serde_json::{Value, json};
use super::{CommandSpec, ok};
-use crate::params::{f64_of, get, num, req_index, req_string, req_targets, string, targets};
+use crate::params::{f64_of, get, req_index, req_string, req_targets, string, targets};
use crate::{EngineError, Result, Session, bad, spec};
pub fn specs() -> Vec {
@@ -236,7 +236,10 @@ fn save_preset(s: &mut Session, p: &Value) -> Result {
Some(v) => with_values(cmd, ImageFilters::NONE, v)?,
None => {
let stroke = strokes(cmd, p)?;
- let index = num(p, "index").filter(|k| k.is_finite() && *k >= 0.0).map(|k| k as usize);
+ let index = match get(p, "index") {
+ None | Some(Value::Null) => None,
+ Some(_) => Some(req_index(cmd, p, "index")?),
+ };
let doc = s.doc()?;
targets(s, p)
.iter()
diff --git a/crates/engine/src/paint_tests.rs b/crates/engine/src/paint_tests.rs
index 1e97b05ca..00ada8d79 100644
--- a/crates/engine/src/paint_tests.rs
+++ b/crates/engine/src/paint_tests.rs
@@ -135,6 +135,16 @@ fn image_adjust_refuses_what_it_cannot_do() {
assert_eq!(s.execute("image.adjust", &json!({"ids": [plain, r], "index": 1, "preset": "vivid"})).unwrap()["changed"], 1);
}
+#[test]
+fn save_preset_rejects_bad_index() {
+ let mut s = Session::new();
+ let r = image_rect(&mut s);
+ assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 0})).is_err());
+ assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": -1})).is_err(), "negative index accepted");
+ assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 1.5})).is_err(), "fractional index accepted");
+ assert!(s.execute("image.savePreset", &json!({"ids": [r], "name": "B", "index": 1})).is_ok());
+}
+
#[test]
fn saved_image_presets() {
let mut s = Session::new();
From 0fec344f3cc1cc439808aed4781390f9ca76123c Mon Sep 17 00:00:00 2001
From: Trevor Brown
Date: Sat, 7 Nov 2026 23:38:58 -0500
Subject: [PATCH 02/13] M8: copy, cut and paste in vector edit mode act on the
selected points and segments (#1875)
Measured in Figma: in vector edit mode Copy takes only the selected segments (a lone point, the segments touching it) and a paste outside makes a new vector in place; Cut removes them, splitting the path in the same layer and staying in edit mode; Paste while editing adds the clipboard's segments or a copied layer's outline to the vector's network in place, selecting them. FigCraft copied the whole layer, Cut left nothing to paste, and Paste while editing did nothing. 16 new engine and UI tests cover copy, cut, paste, undo and junk parameters; the whole engine suite passes bar the known font test.
Co-Authored-By: Claude Sonnet 5.5
Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at high
---
crates/engine/src/canvas/vectoredit.rs | 2 +-
crates/engine/src/cmd/edit.rs | 21 +-
crates/engine/src/cmd/edit/clipboard.rs | 62 +++-
.../engine/src/cmd/edit/vector_clipboard.rs | 274 +++++++++++++++
.../src/cmd/edit/vector_clipboard_tests.rs | 324 ++++++++++++++++++
crates/ui-egui/src/menus.rs | 10 +-
crates/ui-egui/src/shortcuts.rs | 13 +-
crates/ui-egui/src/vector_keys_tests.rs | 12 +
docs/ui-parity.md | 5 +-
9 files changed, 701 insertions(+), 22 deletions(-)
create mode 100644 crates/engine/src/cmd/edit/vector_clipboard.rs
create mode 100644 crates/engine/src/cmd/edit/vector_clipboard_tests.rs
diff --git a/crates/engine/src/canvas/vectoredit.rs b/crates/engine/src/canvas/vectoredit.rs
index 4f265e0f5..749e246c0 100644
--- a/crates/engine/src/canvas/vectoredit.rs
+++ b/crates/engine/src/canvas/vectoredit.rs
@@ -638,7 +638,7 @@ fn index(cmd: &str, p: &Value, key: &str) -> Result {
}
/// Delete the points and segments of `parts` (`heal` keeps paths through deleted points closed).
-fn delete_selection(s: &mut Session, parts: Vec, heal: bool) -> Result<()> {
+pub(crate) fn delete_selection(s: &mut Session, parts: Vec, heal: bool) -> Result<()> {
let doc = s.doc_mut()?;
for EditPart { id, vertices: verts, segments: segs } in parts {
edit(doc, id, |net| {
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index efcb0fc52..19a7d7011 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -17,6 +17,9 @@ mod clipboard;
mod props;
pub(crate) use props::{edit_region_fills, fill_regions};
mod select;
+mod vector_clipboard;
+#[cfg(test)]
+mod vector_clipboard_tests;
pub(crate) use clipboard::apply_copied_props;
pub use clipboard::{CLIP_CLOSE, CLIP_OPEN, copy_to_clipboard, design_clipboard_buffer, paste_into};
@@ -117,12 +120,24 @@ pub fn specs() -> Vec {
true,
duplicate
),
- spec!("edit.copy", "Copy", "{ids?}", false, copy),
- spec!("edit.cut", "Cut", "{ids?}", true, cut),
+ spec!(
+ "edit.copy",
+ "Copy",
+ "{ids?} in vector edit mode with points or segments selected (and no ids): just those, the segments touching a selected point, as a new vector with the edited layer's look",
+ false,
+ copy
+ ),
+ spec!(
+ "edit.cut",
+ "Cut",
+ "{ids?} in vector edit mode with points or segments selected (and no ids): copies them as Copy does, then removes them as Delete does; the path splits in the same layer and edit mode stays on",
+ true,
+ cut
+ ),
spec!(
"edit.paste",
"Paste",
- "{parent?, x?, y? (page coordinates of the pasted top-left)} a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
+ "{parent?, x?, y? (page coordinates of the pasted top-left)} in vector edit mode (and no parent): the copied vectors' segments and shapes' outlines join the edited vector's network in place, selected, and the layers that have no outline (text, frames, groups) are skipped (`skipped`); a copied main component pastes as an instance of it within its file (cut ones, and pastes into other files, keep the component)",
true,
paste
),
diff --git a/crates/engine/src/cmd/edit/clipboard.rs b/crates/engine/src/cmd/edit/clipboard.rs
index 150a3b577..da5089419 100644
--- a/crates/engine/src/cmd/edit/clipboard.rs
+++ b/crates/engine/src/cmd/edit/clipboard.rs
@@ -1,6 +1,6 @@
use super::{
- Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, id, json, num, ok,
- req_targets, roots, string, targets, z_sorted,
+ Affine, BTreeMap, BTreeSet, Document, EngineError, ImageData, Node, NodeId, NodeKind, Result, Session, Value, bad, delete, get, id, json, num,
+ ok, req_targets, roots, string, targets, vector_clipboard, z_sorted,
};
/// The copied form of the selection.
@@ -12,6 +12,18 @@ pub fn copy_to_clipboard(s: &mut Session, cmd: &str, ids: &[NodeId]) -> Result<(
return Err(EngineError::Disabled(cmd.into(), "pages can't be copied; use page.duplicate".into()));
}
let (nodes, images, bounds) = copied(&ds.doc, &layers);
+ store_clipboard(s, cmd, nodes, images, bounds)
+}
+
+/// Make `nodes` (the copied layers, each root's transform in page space) the clipboard's layers.
+pub(super) fn store_clipboard(
+ s: &mut Session,
+ cmd: &str,
+ nodes: Vec<(NodeId, Vec)>,
+ images: BTreeMap,
+ bounds: Option,
+) -> Result<()> {
+ let ds = s.ds()?;
let (source, source_path, uid) = (ds.doc.clone(), ds.path.clone(), ds.uid);
s.clipboard.source = Some(source);
s.clipboard.source_path = source_path;
@@ -43,21 +55,26 @@ fn copied(doc: &Document, ids: &[NodeId]) -> Copied {
if let Some(r) = sub.first_mut() {
r.transform = world;
}
- for n in &sub {
- for p in n.fills.iter().chain(n.strokes.iter()) {
- if let figcraft_color::PaintKind::Image(img) = &p.kind
- && let Some(d) = doc.images.get(&img.image)
- {
- images.insert(img.image.clone(), d.clone());
- }
- }
- }
+ collect_images(doc, &sub, &mut images);
nodes.push((*i, sub));
}
let bounds = doc.bounds_of(&ids);
(nodes, images, bounds)
}
+/// The images the paints of `nodes` use, taken from `doc` into `images`.
+pub(super) fn collect_images(doc: &Document, nodes: &[Node], images: &mut BTreeMap) {
+ for n in nodes {
+ for p in n.fills.iter().chain(n.strokes.iter()) {
+ if let figcraft_color::PaintKind::Image(img) = &p.kind
+ && let Some(d) = doc.images.get(&img.image)
+ {
+ images.insert(img.image.clone(), d.clone());
+ }
+ }
+ }
+}
+
/// The markers around the copied layers in the clipboard's HTML, spelt as that format spells them.
pub const CLIP_OPEN: &str = "(figma)";
@@ -167,13 +184,32 @@ fn layers_missing_images(doc: &figcraft_doc::Document, ids: &[NodeId]) -> Vec bool {
+ get(p, "ids").is_some() || get(p, "id").is_some()
+}
+
pub(super) fn copy(s: &mut Session, p: &Value) -> Result {
+ // In vector edit mode with points or segments selected, Copy takes just those (#1875).
+ if !names_layers(p)
+ && let Some(sel) = vector_clipboard::edit_selection(s)
+ && !sel.parts.is_empty()
+ {
+ return vector_clipboard::copy_selection(s, "edit.copy", sel);
+ }
let ids = req_targets("edit.copy", s, p)?;
copy_to_clipboard(s, "edit.copy", &ids)?;
Ok(json!({"copied": s.clipboard.nodes.len()}))
}
pub(super) fn cut(s: &mut Session, p: &Value) -> Result {
+ // In vector edit mode with points or segments selected, Cut takes just those and stays in edit mode (#1875).
+ if !names_layers(p)
+ && let Some(sel) = vector_clipboard::edit_selection(s)
+ && sel.any
+ {
+ return vector_clipboard::cut_selection(s, sel);
+ }
let ids = req_targets("edit.cut", s, p)?;
copy_to_clipboard(s, "edit.cut", &ids)?;
let doc = s.doc()?;
@@ -238,6 +274,10 @@ pub fn paste_into(s: &mut Session, parent: NodeId, at: Option<(f64, f64)>) -> Re
}
pub(super) fn paste(s: &mut Session, p: &Value) -> Result {
+ // While editing a vector, the copied layers join its network (#1875); `parent` asks for layers.
+ if id(p, "parent").is_none() && s.ds()?.vector_edit.is_some() {
+ return vector_clipboard::paste_into_vector(s, p);
+ }
let page = s.page()?;
// Figma pastes into the selected frame (if one is selected), at the same position when it fits,
// else in the frame's centre; otherwise in place on the page (or the viewport centre).
diff --git a/crates/engine/src/cmd/edit/vector_clipboard.rs b/crates/engine/src/cmd/edit/vector_clipboard.rs
new file mode 100644
index 000000000..d9efea269
--- /dev/null
+++ b/crates/engine/src/cmd/edit/vector_clipboard.rs
@@ -0,0 +1,274 @@
+//! Copy, cut and paste in vector edit mode (#1875).
+//!
+//! With points or segments selected, Copy and Cut take just those: a temporary vector holding the
+//! selected segments (and the segments touching a selected point) goes on the ordinary layer
+//! clipboard, kept at its place on the page, so a paste outside edit mode is a plain layer paste
+//! in place. Cut then removes the selection the way Delete does and stays in edit mode. Paste
+//! while editing adds the clipboard's layers to the edited vector's network, in place: a vector
+//! with its segments, a shape or boolean with its outline.
+
+use figcraft_doc::{NodeKind, Region, VectorNetwork};
+
+use super::clipboard::{collect_images, store_clipboard};
+use super::{Affine, BTreeMap, BTreeSet, Document, EngineError, Node, NodeId, Result, Session, Value, json, num};
+use crate::canvas::vectoredit::{self, EditPart};
+
+/// The most segments a vector network takes through a paste.
+const MAX_SEGMENTS: usize = 500_000;
+
+/// What the edited layers have selected.
+pub(super) struct EditSelection {
+ /// Whether any edited layer has a point or a segment selected.
+ pub any: bool,
+ /// Each edited layer with something to copy, and the sub-network that is.
+ pub parts: Vec<(NodeId, VectorNetwork)>,
+}
+
+/// The selection of the vector being edited (and the other layers edited with it), or `None` when
+/// not in vector edit mode.
+pub(super) fn edit_selection(s: &Session) -> Option {
+ let ds = s.ds().ok()?;
+ let ve = ds.vector_edit.as_ref()?;
+ let mut sel = EditSelection { any: false, parts: Vec::new() };
+ for part in ve.parts() {
+ if part.vertices.is_empty() && part.segments.is_empty() {
+ continue;
+ }
+ sel.any = true;
+ let Some(net) = vectoredit::network(&ds.doc, part.id) else { continue };
+ let active = part.id == ve.id;
+ // Points selected only through a selected region don't pull in the segments touching
+ // them: the region's own segments are the selection.
+ let vertices: Vec = part.vertices.iter().copied().filter(|v| !active || !ve.region_vertices.contains(v)).collect();
+ let mut segments = part.segments.clone();
+ if active {
+ segments.extend(ve.regions.iter().filter_map(|r| net.regions.get(*r)).flat_map(|r| r.loops.iter().flatten().copied()));
+ }
+ if let Some(sub) = sub_network(net, &vertices, &segments) {
+ sel.parts.push((part.id, sub));
+ }
+ }
+ Some(sel)
+}
+
+/// The part of `net` that is the segments `segments` and those touching a point of `vertices`,
+/// with the points they join; `None` when there are none (a lone point with no segment draws
+/// nothing). The regions whose every segment is kept stay regions.
+fn sub_network(net: &VectorNetwork, vertices: &[usize], segments: &[usize]) -> Option {
+ let picked: BTreeSet = vertices.iter().copied().collect();
+ let mut keep: BTreeSet = segments.iter().copied().filter(|i| *i < net.segments.len()).collect();
+ for (i, sg) in net.segments.iter().enumerate() {
+ if picked.contains(&sg.a) || picked.contains(&sg.b) {
+ keep.insert(i);
+ }
+ }
+ let used: BTreeSet = keep.iter().filter_map(|i| net.segments.get(*i)).flat_map(|sg| [sg.a, sg.b]).collect();
+ let vmap: BTreeMap = used.iter().enumerate().map(|(new, old)| (*old, new)).collect();
+ let smap: BTreeMap = keep.iter().enumerate().map(|(new, old)| (*old, new)).collect();
+ let mut out = VectorNetwork {
+ vertices: used.iter().filter_map(|v| net.vertices.get(*v).cloned()).collect(),
+ segments: keep
+ .iter()
+ .filter_map(|i| net.segments.get(*i))
+ .filter_map(|sg| {
+ let mut sg = *sg;
+ sg.a = *vmap.get(&sg.a)?;
+ sg.b = *vmap.get(&sg.b)?;
+ Some(sg)
+ })
+ .collect(),
+ regions: Vec::new(),
+ };
+ if out.segments.is_empty() || out.segments.len() != keep.len() || out.vertices.len() != used.len() {
+ return None;
+ }
+ for r in &net.regions {
+ let loops: Option>> = r.loops.iter().map(|l| l.iter().map(|i| smap.get(i).copied()).collect::
")), "slot Label HTML: {html}");
+}
+
+fn assert_local_slot_text(s: &mut Session, instance: NodeId, expected: &str) {
+ assert!(matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Text") == Some(&json!(expected))));
+ let properties = props_of(s, instance);
+ assert_eq!(properties.iter().find(|p| p["name"] == "Text").unwrap()["value"], expected);
+}
+
+#[test]
+fn slot_text_properties_stay_local_in_default_and_own_content() {
+ for own in [false, true] {
+ let mut s = Session::new();
+ let (content, label, _base, composition, main_content) = slot_text_composition(&mut s, own);
+ let a = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
+ let b = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 800})));
+ let ac = copy_of(&s, a, main_content);
+ let bc = copy_of(&s, b, main_content);
+ ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
+ assert_local_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Default");
+ assert_slot_text(&mut s, main_content, "Default");
+ assert_eq!(node(&s, label).kind.text().unwrap().characters, "Default");
+ // Main property edits propagate without replacing another instance's local value.
+ ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Main value");
+ assert_slot_text(&mut s, main_content, "Main value");
+ ex(&mut s, "component.editProperty", json!({"id": content, "name": "Text", "default": "New default"}));
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Main value");
+ healthy(&s);
+ }
+}
+
+#[test]
+fn slot_text_properties_do_not_read_an_unbound_base_property() {
+ let mut s = Session::new();
+ let (_content, _label, base, composition, main_content) = slot_text_composition(&mut s, true);
+ ex(&mut s, "component.addProperty", json!({"id": base, "name": "Text", "type": "text", "default": "Wrong owner"}));
+ let i = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
+ let nested = copy_of(&s, i, main_content);
+ assert_slot_text(&mut s, nested, "Default");
+ ex(&mut s, "instance.setProperties", json!({"ids": [nested], "properties": {"Text": "Custom"}}));
+ assert_local_slot_text(&mut s, nested, "Custom");
+ assert_slot_text(&mut s, nested, "Custom");
+ assert_slot_text(&mut s, main_content, "Default");
+ healthy(&s);
+}
+
+#[test]
+fn slot_text_properties_survive_inherited_own_content_and_persistence() {
+ let mut s = Session::new();
+ let (_content, _label, _base, composition, main_content) = slot_text_composition(&mut s, true);
+ let (outer, inherited) = slot_text_wrapper(&mut s, composition, "Outer composition");
+ let inherited_content = copy_of(&s, inherited, main_content);
+ let a = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 400})));
+ let b = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 800})));
+ let ac = copy_of(&s, a, inherited_content);
+ let bc = copy_of(&s, b, inherited_content);
+ ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
+ assert_local_slot_text(&mut s, ac, "Custom");
+ let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
+ let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
+ let mut s = Session::with_document(back);
+ assert_local_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Default");
+ assert_slot_text(&mut s, inherited_content, "Default");
+ assert_slot_text(&mut s, main_content, "Default");
+ // Explicit characters override the bound property, even after a main update.
+ let alabel = kids(&s, ac)[0];
+ ex(&mut s, "text.set", json!({"id": alabel, "characters": "Explicit"}));
+ ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Later"}}));
+ ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
+ assert_local_slot_text(&mut s, ac, "Later");
+ assert_slot_text(&mut s, ac, "Explicit");
+ assert_slot_text(&mut s, bc, "Main value");
+ ex(&mut s, "component.resetOverride", json!({"id": alabel, "group": "characters"}));
+ assert_slot_text(&mut s, ac, "Later");
+ s.undo().unwrap();
+ assert_slot_text(&mut s, ac, "Explicit");
+ healthy(&s);
+}
+
/// Random slot edits, main edits and resets keep every instance mirroring its main.
#[test]
fn random_slot_edits_keep_instances_consistent() {
From 0ff3a3682ea8b2e2df68fab3156c2c99d4b8c442 Mon Sep 17 00:00:00 2001
From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com>
Date: Sun, 8 Nov 2026 19:22:04 +0000
Subject: [PATCH 07/13] Reject negative and fractional index in file.openRecent
Found while testing crates/engine/src/cmd/file/open.rs:33 (open_recent, `.nth(i.max(0.0) as usize)`)
Co-Authored-By: Claude Haiku 5.5
Co-Authored-By: Claude Sonnet 5.5
---
crates/engine/src/cmd/file/open.rs | 5 ++++-
crates/engine/src/menu_gaps_tests.rs | 17 +++++++++++++++++
2 files changed, 21 insertions(+), 1 deletion(-)
diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs
index e4c3e0fb7..b6e154c35 100644
--- a/crates/engine/src/cmd/file/open.rs
+++ b/crates/engine/src/cmd/file/open.rs
@@ -31,7 +31,10 @@ pub(super) fn open_recent(s: &mut Session, p: &Value) -> Result {
Some(path)
}
(None, Some(i)) => {
- Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i.max(0.0) as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
+ if !(i >= 0.0 && i.fract() == 0.0) {
+ return Err(bad(CMD, "no such recent file"));
+ }
+ Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
}
_ => None,
};
diff --git a/crates/engine/src/menu_gaps_tests.rs b/crates/engine/src/menu_gaps_tests.rs
index 057c5119a..fa32f5d8f 100644
--- a/crates/engine/src/menu_gaps_tests.rs
+++ b/crates/engine/src/menu_gaps_tests.rs
@@ -84,3 +84,20 @@ fn outlined_layers_draw_as_outlines_and_the_rest_normally() {
assert_eq!(outlined.pixel(20, 20).unwrap(), empty, "only its outline");
assert_eq!(outlined.pixel(80, 20).unwrap(), plain.pixel(80, 20).unwrap(), "the other layer draws normally");
}
+
+#[test]
+fn open_recent_rejects_negative_and_fractional_index() {
+ let dir = std::env::temp_dir().join(format!("figcraft-recent-bad-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let a = dir.join("a.figcraft").to_string_lossy().to_string();
+ let b = dir.join("b.figcraft").to_string_lossy().to_string();
+ let mut s = Session::new();
+ s.execute("file.save", &json!({"path": a})).unwrap();
+ s.execute("file.saveAs", &json!({"path": b})).unwrap();
+ let recent = s.prefs.recent_files.clone();
+ for i in [json!(-1), json!(1.5), json!(-0.5)] {
+ assert!(s.execute("file.openRecent", &json!({"index": i})).is_err(), "index {i} must be an error");
+ }
+ assert_eq!(s.prefs.recent_files, recent);
+ let _ = std::fs::remove_dir_all(&dir);
+}
From a66946d13e6d22eb8fcfcc9ea0100f2f59db349a Mon Sep 17 00:00:00 2001
From: impulsado <72570835+impulsado@users.noreply.github.com>
Date: Tue, 10 Nov 2026 09:34:17 +0100
Subject: [PATCH 08/13] M3: strengthen inherited slot property regression
coverage
Cover inherited Boolean bindings and independent same-component slot content. Strengthen text, HTML and stored-property assertions, split default and own-content cases, and document ownership-based binding resolution.
---
crates/engine/src/assets/components/sync.rs | 6 +-
crates/engine/src/slot_tests.rs | 196 +++++++++++++++++---
2 files changed, 172 insertions(+), 30 deletions(-)
diff --git a/crates/engine/src/assets/components/sync.rs b/crates/engine/src/assets/components/sync.rs
index 17836b111..513f4f7c8 100644
--- a/crates/engine/src/assets/components/sync.rs
+++ b/crates/engine/src/assets/components/sync.rs
@@ -165,8 +165,8 @@ fn copy_layers(
// No longer a slot in the main: it mirrors the main again.
n.overrides.remove(SLOT);
}
- // Component properties: the main layer's bindings use this instance's values; layers of
- // nested instances use the nested instance's values (one level per source hop).
+ // Bindings use the enclosing instance of their defining component, even when slot
+ // content has fewer source hops than enclosing instances.
let enc = enclosing.get(&parent).cloned().unwrap_or_default();
apply_enclosing_props(doc, &mut n, orig, &enc, &inst_props);
if let NodeKind::Instance { component: c, props } = &n.kind {
@@ -254,6 +254,8 @@ fn rebuild_nested(doc: &mut Document, nested: Vec, old: &BTreeMap (NodeId, NodeId, NodeId,
}
fn assert_slot_text(s: &mut Session, instance: NodeId, expected: &str) {
- let label = kids(s, instance)[0];
- let characters = node(s, label).kind.text().unwrap().characters.clone();
+ let children = kids(s, instance);
+ assert_eq!(children.len(), 1, "Content {instance} must have exactly one Label");
+ let label = children[0];
+ assert_eq!(node(s, label).name, "Label");
+ let characters = node(s, label).kind.text().expect("Content's only child must be text").characters.clone();
let html = ex(s, "inspect.code", json!({"id": instance, "language": "html"}))["code"].as_str().unwrap().to_string();
assert_eq!(characters, expected, "slot Label characters; HTML: {html}");
+ assert_eq!(html.matches("
").count(), 1, "slot Label HTML must contain exactly one paragraph: {html}");
assert!(html.contains(&format!(">{expected}
")), "slot Label HTML: {html}");
}
fn assert_local_slot_text(s: &mut Session, instance: NodeId, expected: &str) {
- assert!(matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Text") == Some(&json!(expected))));
+ assert!(
+ matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Text") == Some(&json!(expected))),
+ "instance {instance} must store its own Text value {expected:?}: {:?}",
+ node(s, instance).kind
+ );
let properties = props_of(s, instance);
- assert_eq!(properties.iter().find(|p| p["name"] == "Text").unwrap()["value"], expected);
+ let text = properties.iter().find(|p| p["name"] == "Text").unwrap_or_else(|| panic!("instance {instance} has no Text property: {properties:?}"));
+ assert_eq!(text["value"], expected, "instance {instance} Text property");
+}
+
+/// Exercise the same ownership contract for default slot content and content supplied by the
+/// Composition main; separate tests identify which route regresses.
+fn check_slot_text_properties_stay_local(own: bool) {
+ let mut s = Session::new();
+ let (content, label, _base, composition, main_content) = slot_text_composition(&mut s, own);
+ let a = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
+ let b = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 800})));
+ let ac = copy_of(&s, a, main_content);
+ let bc = copy_of(&s, b, main_content);
+ ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
+ assert_local_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_local_slot_text(&mut s, bc, "Default");
+ assert_slot_text(&mut s, bc, "Default");
+ assert_local_slot_text(&mut s, main_content, "Default");
+ assert_slot_text(&mut s, main_content, "Default");
+ assert_eq!(node(&s, label).kind.text().unwrap().characters, "Default");
+ // Main property edits propagate without replacing another instance's local value.
+ ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Main value");
+ assert_slot_text(&mut s, main_content, "Main value");
+ ex(&mut s, "component.editProperty", json!({"id": content, "name": "Text", "default": "New default"}));
+ assert_slot_text(&mut s, ac, "Custom");
+ assert_slot_text(&mut s, bc, "Main value");
+ assert_local_slot_text(&mut s, main_content, "Main value");
+ assert_slot_text(&mut s, main_content, "Main value");
+ healthy(&s);
}
#[test]
-fn slot_text_properties_stay_local_in_default_and_own_content() {
- for own in [false, true] {
- let mut s = Session::new();
- let (content, label, _base, composition, main_content) = slot_text_composition(&mut s, own);
- let a = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
- let b = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 800})));
- let ac = copy_of(&s, a, main_content);
- let bc = copy_of(&s, b, main_content);
- ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
- assert_local_slot_text(&mut s, ac, "Custom");
- assert_slot_text(&mut s, ac, "Custom");
- assert_slot_text(&mut s, bc, "Default");
- assert_slot_text(&mut s, main_content, "Default");
- assert_eq!(node(&s, label).kind.text().unwrap().characters, "Default");
- // Main property edits propagate without replacing another instance's local value.
- ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Text": "Main value"}}));
- assert_slot_text(&mut s, ac, "Custom");
- assert_slot_text(&mut s, bc, "Main value");
- assert_slot_text(&mut s, main_content, "Main value");
- ex(&mut s, "component.editProperty", json!({"id": content, "name": "Text", "default": "New default"}));
- assert_slot_text(&mut s, ac, "Custom");
- assert_slot_text(&mut s, bc, "Main value");
- healthy(&s);
- }
+fn slot_text_properties_stay_local_in_default_content() {
+ check_slot_text_properties_stay_local(false);
+}
+
+#[test]
+fn slot_text_properties_stay_local_in_own_content() {
+ check_slot_text_properties_stay_local(true);
}
#[test]
@@ -451,11 +474,15 @@ fn slot_text_properties_do_not_read_an_unbound_base_property() {
let (_content, _label, base, composition, main_content) = slot_text_composition(&mut s, true);
ex(&mut s, "component.addProperty", json!({"id": base, "name": "Text", "type": "text", "default": "Wrong owner"}));
let i = idv(&ex(&mut s, "instance.create", json!({"component": composition, "x": 400})));
+ let nested_base = kids(&s, i)[0];
+ assert_local_slot_text(&mut s, nested_base, "Wrong owner");
let nested = copy_of(&s, i, main_content);
+ assert_local_slot_text(&mut s, nested, "Default");
assert_slot_text(&mut s, nested, "Default");
ex(&mut s, "instance.setProperties", json!({"ids": [nested], "properties": {"Text": "Custom"}}));
assert_local_slot_text(&mut s, nested, "Custom");
assert_slot_text(&mut s, nested, "Custom");
+ assert_local_slot_text(&mut s, nested_base, "Wrong owner");
assert_slot_text(&mut s, main_content, "Default");
healthy(&s);
}
@@ -472,6 +499,9 @@ fn slot_text_properties_survive_inherited_own_content_and_persistence() {
let bc = copy_of(&s, b, inherited_content);
ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Text": "Custom"}}));
assert_local_slot_text(&mut s, ac, "Custom");
+ assert_local_slot_text(&mut s, bc, "Default");
+ assert_local_slot_text(&mut s, inherited_content, "Default");
+ assert_local_slot_text(&mut s, main_content, "Default");
let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
let mut s = Session::with_document(back);
@@ -495,6 +525,116 @@ fn slot_text_properties_survive_inherited_own_content_and_persistence() {
healthy(&s);
}
+/// Check both the stored property and the Label it drives, not just one representation.
+fn assert_slot_visibility(s: &mut Session, instance: NodeId, expected: bool) {
+ assert!(
+ matches!(&node(s, instance).kind, NodeKind::Instance { props, .. } if props.get("Visible") == Some(&json!(expected))),
+ "instance {instance} must store Visible={expected}: {:?}",
+ node(s, instance).kind
+ );
+ let properties = props_of(s, instance);
+ let visible =
+ properties.iter().find(|p| p["name"] == "Visible").unwrap_or_else(|| panic!("instance {instance} has no Visible property: {properties:?}"));
+ assert_eq!(visible["value"], expected, "instance {instance} Visible property");
+ let children = kids(s, instance);
+ assert_eq!(children.len(), 1, "Content {instance} must have exactly one Label");
+ assert_eq!(node(s, children[0]).name, "Label");
+ assert_eq!(node(s, children[0]).visible, expected, "instance {instance} Label visibility");
+}
+
+#[test]
+fn slot_boolean_properties_stay_local_in_inherited_own_content() {
+ let mut s = Session::new();
+ let (content, label, base, composition, main_content) = slot_text_composition(&mut s, true);
+ ex(&mut s, "component.addProperty", json!({"id": content, "name": "Visible", "type": "boolean", "default": true, "layer": label}));
+ ex(&mut s, "component.addProperty", json!({"id": base, "name": "Visible", "type": "boolean", "default": false}));
+ let (outer, inherited) = slot_text_wrapper(&mut s, composition, "Outer composition");
+ let inherited_base = kids(&s, inherited)[0];
+ let inherited_content = copy_of(&s, inherited, main_content);
+ let a = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 400})));
+ let b = idv(&ex(&mut s, "instance.create", json!({"component": outer, "x": 800})));
+ let ac = copy_of(&s, a, inherited_content);
+ let bc = copy_of(&s, b, inherited_content);
+ let abase = copy_of(&s, a, inherited_base);
+ assert!(matches!(&node(&s, abase).kind, NodeKind::Instance { props, .. } if props.get("Visible") == Some(&json!(false))));
+ assert_slot_visibility(&mut s, ac, true);
+ assert_slot_visibility(&mut s, bc, true);
+ ex(&mut s, "instance.setProperties", json!({"ids": [ac], "properties": {"Visible": false}}));
+ assert_slot_visibility(&mut s, ac, false);
+ assert_slot_visibility(&mut s, bc, true);
+ assert_slot_visibility(&mut s, inherited_content, true);
+ assert_slot_visibility(&mut s, main_content, true);
+ // A main update must not replace either instance's local value with the Base's homonym.
+ ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Visible": false}}));
+ assert_slot_visibility(&mut s, ac, false);
+ assert_slot_visibility(&mut s, bc, false);
+ ex(&mut s, "instance.setProperties", json!({"ids": [bc], "properties": {"Visible": true}}));
+ ex(&mut s, "node.set", json!({"id": content, "props": {"fill": "#abcdef"}}));
+ assert_slot_visibility(&mut s, ac, false);
+ assert_slot_visibility(&mut s, bc, true);
+ assert_slot_visibility(&mut s, main_content, false);
+ healthy(&s);
+ let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
+ let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
+ let mut s = Session::with_document(back);
+ assert_slot_visibility(&mut s, ac, false);
+ assert_slot_visibility(&mut s, bc, true);
+ assert_slot_visibility(&mut s, inherited_content, false);
+ assert_slot_visibility(&mut s, main_content, false);
+ ex(&mut s, "instance.setProperties", json!({"ids": [main_content], "properties": {"Visible": true}}));
+ assert_slot_visibility(&mut s, ac, false);
+ assert_slot_visibility(&mut s, bc, true);
+ assert_slot_visibility(&mut s, main_content, true);
+ healthy(&s);
+}
+
+#[test]
+fn same_component_in_own_slot_keeps_independent_text_properties() {
+ let mut s = Session::new();
+ let frame = idv(&ex(&mut s, "frame.create", json!({"width": 200, "height": 100, "name": "Card"})));
+ let label = idv(&ex(&mut s, "text.create", json!({"text": "Default", "parent": frame, "props": {"name": "Label"}})));
+ let body = idv(&ex(&mut s, "frame.create", json!({"width": 180, "height": 60, "y": 40, "name": "Body", "parent": frame})));
+ let card = idv(&ex(&mut s, "component.create", json!({"ids": [frame]})));
+ ex(&mut s, "component.addProperty", json!({"id": card, "name": "Text", "type": "text", "default": "Default", "layer": label}));
+ ex(&mut s, "component.makeSlot", json!({"id": body}));
+ // Only page instance content holds another Card: the main never contains itself.
+ let outer = idv(&ex(&mut s, "instance.create", json!({"component": card, "x": 400})));
+ let inner = idv(&ex(&mut s, "instance.slotInsert", json!({"id": outer, "slot": "Body", "component": card})));
+ let check = |s: &mut Session, outer_text: &str, inner_text: &str| {
+ assert_local_slot_text(s, outer, outer_text);
+ assert_local_slot_text(s, inner, inner_text);
+ assert_eq!(node(s, copy_of(s, outer, label)).kind.text().unwrap().characters, outer_text);
+ assert_eq!(node(s, copy_of(s, inner, label)).kind.text().unwrap().characters, inner_text);
+ let outer_body = copy_of(s, outer, body);
+ assert!(slot_edited(s.doc().unwrap(), outer_body));
+ assert_eq!(kids(s, outer_body), vec![inner]);
+ assert!(kids(s, copy_of(s, inner, body)).is_empty());
+ assert!(kids(s, body).is_empty(), "the main's slot must remain empty");
+ healthy(s);
+ };
+ ex(&mut s, "instance.setProperties", json!({"ids": [outer], "properties": {"Text": "Outer"}}));
+ check(&mut s, "Outer", "Default");
+ ex(&mut s, "instance.setProperties", json!({"ids": [inner], "properties": {"Text": "Inner"}}));
+ check(&mut s, "Outer", "Inner");
+ ex(&mut s, "text.set", json!({"id": label, "characters": "New default"}));
+ ex(&mut s, "node.set", json!({"id": card, "props": {"fill": "#abcdef"}}));
+ check(&mut s, "Outer", "Inner");
+ assert_eq!(fill(&s, outer), "ABCDEF");
+ assert_eq!(fill(&s, inner), "ABCDEF");
+ ex(&mut s, "instance.setProperties", json!({"ids": [outer], "properties": {"Text": "Outer updated"}}));
+ check(&mut s, "Outer updated", "Inner");
+ ex(&mut s, "instance.setProperties", json!({"ids": [inner], "properties": {"Text": "Inner updated"}}));
+ check(&mut s, "Outer updated", "Inner updated");
+ let bytes = figcraft_format::save_bytes(s.doc().unwrap(), None).unwrap();
+ let (back, _) = figcraft_format::load_bytes(&bytes).unwrap();
+ let mut s = Session::with_document(back);
+ check(&mut s, "Outer updated", "Inner updated");
+ ex(&mut s, "node.set", json!({"id": card, "props": {"fill": "#123456"}}));
+ check(&mut s, "Outer updated", "Inner updated");
+ assert_eq!(fill(&s, outer), "123456");
+ assert_eq!(fill(&s, inner), "123456");
+}
+
/// Random slot edits, main edits and resets keep every instance mirroring its main.
#[test]
fn random_slot_edits_keep_instances_consistent() {
From 4d3fe2aa1ac041df7fa4d785beb8429d66678ed8 Mon Sep 17 00:00:00 2001
From: "Dylan M. Taylor"
Date: Wed, 11 Nov 2026 15:59:59 +0000
Subject: [PATCH 09/13] svg import: cap attributes per element, map span
offsets to characters once
---
crates/svg/src/import.rs | 35 ++++++++++++++++++++++----
crates/svg/src/import/budget.rs | 2 +-
crates/svg/src/import/hostile_tests.rs | 12 +++++++++
crates/svg/src/import/text.rs | 12 ++++++---
crates/svg/src/import/text_tests.rs | 8 ++++++
5 files changed, 60 insertions(+), 9 deletions(-)
diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs
index 1ac8a78bf..f77b10bfa 100644
--- a/crates/svg/src/import.rs
+++ b/crates/svg/src/import.rs
@@ -704,13 +704,28 @@ fn simple_hash(b: &[u8]) -> String {
/// Deepest element nesting the parser is given: deeper documents would exhaust the stack.
const MAX_NESTING: usize = 512;
+/// The most attributes one element may have. The XML parser checks each attribute against the
+/// earlier ones, so a huge count is quadratic work; real elements have a few dozen at most.
+const MAX_ATTRIBUTES: usize = 4096;
+
/// How deep elements nest in `data`: a scan of its tags (comments, CDATA, declarations and quoted
/// attribute values skipped) that stops once past `limit`.
pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
+ scan(data, limit).0
+}
+
+/// Whether an element of `data` has more than [`MAX_ATTRIBUTES`] attributes (counted as quoted
+/// values, before the parser sees them).
+pub(crate) fn too_wide(data: &[u8]) -> bool {
+ scan(data, usize::MAX).1 > MAX_ATTRIBUTES
+}
+
+/// [`nesting`] and the most attribute values on one element; stops once either is past its limit.
+fn scan(data: &[u8], limit: usize) -> (usize, usize) {
let find = |from: usize, pat: &[u8]| -> usize {
data.get(from..).and_then(|r| r.windows(pat.len()).position(|w| w == pat)).map_or(data.len(), |p| from + p + pat.len())
};
- let (mut depth, mut max, mut i) = (0usize, 0usize, 0usize);
+ let (mut depth, mut max, mut i, mut widest) = (0usize, 0usize, 0usize, 0usize);
while let Some(off) = data.get(i..).and_then(|r| r.iter().position(|b| *b == b'<')) {
i += off;
let rest = data.get(i..).unwrap_or(&[]);
@@ -725,12 +740,15 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
i = find(i + 2, b">");
} else {
// A start tag: to its `>` outside quotes; `/>` closes it.
- let (mut quote, mut j, mut closed) = (None, i + 1, false);
+ let (mut quote, mut j, mut closed, mut attrs) = (None, i + 1, false, 0usize);
while let Some(&c) = data.get(j) {
match quote {
Some(q) if c == q => quote = None,
Some(_) => {}
- None if c == b'"' || c == b'\'' => quote = Some(c),
+ None if c == b'"' || c == b'\'' => {
+ quote = Some(c);
+ attrs += 1;
+ }
None if c == b'>' => {
closed = data.get(j.wrapping_sub(1)) == Some(&b'/');
break;
@@ -739,17 +757,21 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
}
j += 1;
}
+ widest = widest.max(attrs);
+ if widest > MAX_ATTRIBUTES {
+ return (max, widest);
+ }
if !closed {
depth += 1;
max = max.max(depth);
if max > limit {
- return max;
+ return (max, widest);
}
}
i = j + 1;
}
}
- max
+ (max, widest)
}
/// Whether `data` nests elements more than [`MAX_NESTING`] deep: the byte scan first, then the
@@ -883,6 +905,9 @@ fn import_within(
) -> Result {
// SVGZ is unpacked here, within a budget, so every check below sees the real document.
let data = budget::document(data, &limits).map_err(ImportError)?;
+ if too_wide(&data) {
+ return Err(ImportError(format!("an element has more than {MAX_ATTRIBUTES} attributes")));
+ }
if too_deep(&data) {
return Err(ImportError(format!("elements nested more than {MAX_NESTING} deep")));
}
diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs
index 7de080af4..c50266dc0 100644
--- a/crates/svg/src/import/budget.rs
+++ b/crates/svg/src/import/budget.rs
@@ -87,7 +87,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], opts: &Options) -> Option
}
};
used.bytes.fetch_add(plain.len(), Ordering::Relaxed);
- if super::too_deep(&plain) {
+ if super::too_wide(&plain) || super::too_deep(&plain) {
return None;
}
used.depth.fetch_add(1, Ordering::Relaxed);
diff --git a/crates/svg/src/import/hostile_tests.rs b/crates/svg/src/import/hostile_tests.rs
index 0af1297d0..16731407c 100644
--- a/crates/svg/src/import/hostile_tests.rs
+++ b/crates/svg/src/import/hostile_tests.rs
@@ -181,3 +181,15 @@ fn entity_expansion_cannot_bypass_the_nesting_limit() {
let err = import_svg(&mut d, data.as_bytes(), p, 0.0, 0.0, "x").err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("nested more than 512 deep"), "{err:?}");
}
+
+#[test]
+fn an_element_with_thousands_of_attributes_is_refused_before_parsing() {
+ use super::too_wide;
+ let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::();
+ assert!(!too_wide(format!("", many(4096)).as_bytes()));
+ assert!(too_wide(format!("", many(4097)).as_bytes()));
+ assert!(!too_wide(format!("", "".repeat(10_000)).as_bytes()), "per element, not per file");
+ let mut d = Document::new("t");
+ let p = d.first_page().unwrap();
+ assert!(import_svg(&mut d, &svg(&format!("", many(100_000))), p, 0.0, 0.0, "x").is_err());
+}
diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs
index cee54bbd8..7ed8d018f 100644
--- a/crates/svg/src/import/text.rs
+++ b/crates/svg/src/import/text.rs
@@ -195,7 +195,7 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
let x = chunk.x().map_or(pen_x, f64::from) + d(t.dx());
let y = chunk.y().map_or(pen_y, f64::from) + d(t.dy());
char_at += count;
- let ci = |b: usize| text.get(..b).map_or(count, |p| p.chars().count());
+ let ci = char_index(text);
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, s, fonts))).collect();
if spans.is_empty() {
continue;
@@ -229,6 +229,13 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
}
}
+/// The characters of `text` before a byte offset (all of them for an offset that is past the end
+/// or inside a character), by a search in a table built once: many spans don't rescan the prefix.
+fn char_index(text: &str) -> impl Fn(usize) -> usize + '_ {
+ let starts: Vec = text.char_indices().map(|(i, _)| i).collect();
+ move |b| if text.is_char_boundary(b) { starts.partition_point(|s| *s < b) } else { starts.len() }
+}
+
/// The text of `lines` (one per line, stacked at their pitch; `s`: their scale): characters, the
/// first span's style and a run per span, fills still to come.
fn text_data(lines: &[Line], s: f64) -> TextData {
@@ -262,8 +269,7 @@ fn on_path(cx: &mut Ctx, t: &usvg::Text, world: Affine, parent: NodeId) -> bool
let Some(len) = figcraft_geom::measure::polylines(&path).and_then(|l| l.first().map(|l| l.length())).filter(|l| *l > 1e-9) else { return false };
let fonts = cx.fonts.get_or_insert_with(Fonts::load);
let text = chunk.text();
- let count = text.chars().count();
- let ci = |b: usize| text.get(..b).map_or(count, |p| p.chars().count());
+ let ci = char_index(text);
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, 1.0, fonts))).collect();
let line = Line { x: 0.0, y: 0.0, anchor: chunk.anchor(), text: text.to_string(), spans };
let mut td = text_data(std::slice::from_ref(&line), 1.0);
diff --git a/crates/svg/src/import/text_tests.rs b/crates/svg/src/import/text_tests.rs
index f267b2947..94c6ae5b2 100644
--- a/crates/svg/src/import/text_tests.rs
+++ b/crates/svg/src/import/text_tests.rs
@@ -30,3 +30,11 @@ fn css_system_font_names_keep_their_name_where_the_system_font_is() {
assert_eq!(family(&named(&["-apple-system", "BlinkMacSystemFont", "system-ui", "sans-serif"]), &elsewhere), "Inter");
assert_eq!(family(&named(&["-apple-system"]), &elsewhere), "-apple-system", "nothing installed: the first name it gives");
}
+
+#[test]
+fn char_index_counts_the_characters_before_a_byte_offset() {
+ let t = "aé😀b";
+ let ci = super::char_index(t);
+ assert_eq!([ci(0), ci(1), ci(3), ci(7), ci(8)], [0, 1, 2, 3, 4]);
+ assert_eq!([ci(2), ci(4), ci(99)], [4, 4, 4], "inside a character or past the end: all of them");
+}
From 2f8dd85f4284c9b1ba0007d401d76200551c209e Mon Sep 17 00:00:00 2001
From: "Dylan M. Taylor"
Date: Wed, 11 Nov 2026 17:43:55 +0000
Subject: [PATCH 10/13] load: share one layer allowance across Penpot raw SVGs,
sum font-run coverage once
---
crates/engine/src/cmd/file/load.rs | 111 +++++++++++++++++++++++------
1 file changed, 91 insertions(+), 20 deletions(-)
diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs
index 3e917d5dd..77dd68198 100644
--- a/crates/engine/src/cmd/file/load.rs
+++ b/crates/engine/src/cmd/file/load.rs
@@ -399,11 +399,19 @@ pub(crate) fn load_fig(bytes: &[u8], name: &str) -> Option) {
+ expand_penpot_raw_svgs_within(doc, notes, MAX_PENPOT_SVG_LAYERS);
+}
+
+/// [`expand_penpot_raw_svgs`] with at most `room` layers made in all.
+fn expand_penpot_raw_svgs_within(doc: &mut Document, notes: &mut Vec, mut room: usize) {
let layers = doc
.nodes()
.filter_map(|node| {
@@ -413,12 +421,25 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec) {
})
.collect::>();
let mut ok_count = 0usize;
+ // The SVG importer caps its own layers per file; `room` is the cap over all of a file's placeholders.
for (id, name, width, height, xml, empty) in layers {
+ if room == 0 {
+ if let Some(n) = doc.node_mut(id) {
+ n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
+ }
+ if notes.len() < 100 {
+ notes.push(format!("Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"));
+ }
+ continue;
+ }
if !empty {
notes.push(format!("Penpot SVG '{name}': has separate child layers; the original tree was preserved to prevent duplicate rendering"));
continue;
}
- match figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name) {
+ let before = doc.node_count();
+ let imported = figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name);
+ room = room.saturating_sub(doc.node_count().saturating_sub(before));
+ match imported {
Ok(imported) => {
// An SVG can be syntactically valid yet contain no supported drawable
// elements. Do not claim success or leave an empty extra frame.
@@ -470,6 +491,28 @@ fn expand_penpot_raw_svgs(doc: &mut Document, notes: &mut Vec) {
}
}
+/// Whether some of the first `len` characters are in none of `runs`. Where runs start and stop
+/// covering is summed once, so runs overlapping any number of times cost no more than their count.
+fn has_uncovered(len: usize, runs: &[figcraft_doc::StyleRun]) -> bool {
+ let mut change = vec![0i64; len + 1];
+ for run in runs {
+ let (start, end) = (run.start.min(len), run.end.min(len));
+ if start < end {
+ if let Some(c) = change.get_mut(start) {
+ *c += 1;
+ }
+ if let Some(c) = change.get_mut(end) {
+ *c -= 1;
+ }
+ }
+ }
+ let mut open = 0i64;
+ change.iter().take(len).any(|c| {
+ open += c;
+ open <= 0
+ })
+}
+
/// Non-destructive font diagnostic for the action palette, CLI and control API.
/// Includes styled runs, not just the default typeface of each text layer.
pub(super) fn font_report(doc: &Document) -> Value {
@@ -485,21 +528,15 @@ fn font_report_with_families(doc: &Document, installed: &[String]) -> Value {
if text.characters.is_empty() {
continue;
}
- let mut covered = vec![false; text.characters.chars().count().min(100_000)];
+ let len = text.characters.chars().count().min(100_000);
let mut used = BTreeSet::new();
for run in &text.runs {
- let start = run.start.min(covered.len());
- let end = run.end.min(covered.len());
- if start < end {
- if !run.style.font_family.trim().is_empty() {
- used.insert(run.style.font_family.clone());
- }
- for entry in covered.iter_mut().take(end).skip(start) {
- *entry = true;
- }
+ if run.start.min(len) < run.end.min(len) && !run.style.font_family.trim().is_empty() {
+ used.insert(run.style.font_family.clone());
}
}
- if covered.iter().any(|entry| !entry) {
+ let uncovered = has_uncovered(len, &text.runs);
+ if uncovered {
used.insert(text.style.font_family.clone());
}
for family in used {
@@ -599,19 +636,14 @@ fn missing_penpot_font_warnings(doc: &Document, families: &[String]) -> Vec"#;
+ let ids: Vec = (0..2)
+ .map(|i| {
+ let id = doc.create(page, NodeKind::Frame, &format!("S{i}"), 0.0, 0.0, 10.0, 10.0).unwrap();
+ let layer = doc.node_mut(id).unwrap();
+ layer.plugin_data.insert("penpot.svgRawXml".into(), svg.into());
+ layer.plugin_data.insert("penpot.svgRawStatus".into(), "pending".into());
+ id
+ })
+ .collect();
+ let mut warnings = Vec::new();
+ expand_penpot_raw_svgs_within(&mut doc, &mut warnings, 1);
+ let status = |i: usize| doc.node(ids[i]).unwrap().plugin_data.get("penpot.svgRawStatus").cloned();
+ assert_eq!(status(0).as_deref(), Some("expanded"), "the first uses the allowance");
+ assert_eq!(status(1).as_deref(), Some("not-expanded"));
+ assert!(doc.node(ids[1]).unwrap().children.is_empty());
+ assert!(warnings.iter().any(|w| w.contains("over the limit")), "{warnings:?}");
+ }
+
+ #[test]
+ fn many_overlapping_style_runs_are_summed_once() {
+ use figcraft_doc::StyleRun;
+ let mut doc = Document::new("Runs");
+ let page = doc.first_page().unwrap();
+ let mut t = TextData::new("x".repeat(100_000));
+ t.style.font_family = "Unused Base".into();
+ let mut run = t.style.clone();
+ run.font_family = "Run Font".into();
+ t.runs = (0..50_000).map(|_| StyleRun { start: 0, end: 100_000, style: run.clone() }).collect();
+ doc.create(page, NodeKind::Text(t), "Long", 0.0, 0.0, 100.0, 30.0).unwrap();
+ let report = font_report_with_families(&doc, &[]);
+ assert_eq!(report["fonts"].as_array().map(Vec::len), Some(1), "{report}");
+ assert_eq!(report["fonts"][0]["family"], "Run Font");
+ }
+
#[test]
fn expands_inline_svg_into_editable_shapes_without_discarding_source() {
let mut doc = Document::new("SVG fixture");
From 70ed6c1636b1560f8f17d8471f1c2661d06130b7 Mon Sep 17 00:00:00 2001
From: "Dylan M. Taylor"
Date: Wed, 11 Nov 2026 18:53:53 +0000
Subject: [PATCH 11/13] svg import: budget attribute work over the whole file
and DTD, map span offsets in one pass
---
crates/svg/src/import.rs | 42 ++++++++++++++++++++------
crates/svg/src/import/hostile_tests.rs | 12 ++++++++
crates/svg/src/import/text.rs | 33 +++++++++++++++-----
crates/svg/src/import/text_tests.rs | 2 +-
4 files changed, 71 insertions(+), 18 deletions(-)
diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs
index f77b10bfa..fbdb9b2c1 100644
--- a/crates/svg/src/import.rs
+++ b/crates/svg/src/import.rs
@@ -714,18 +714,26 @@ pub(crate) fn nesting(data: &[u8], limit: usize) -> usize {
scan(data, limit).0
}
-/// Whether an element of `data` has more than [`MAX_ATTRIBUTES`] attributes (counted as quoted
-/// values, before the parser sees them).
+/// The most the parser's duplicate-attribute checks may cost over a whole document, as the sum of
+/// each element's attribute count squared (a real file with 100,000 elements of 20 attributes is
+/// 40 million).
+const MAX_ATTRIBUTE_WORK: usize = 1 << 28;
+
+/// Whether an element of `data` has more than [`MAX_ATTRIBUTES`] attributes, or all of them cost
+/// more than [`MAX_ATTRIBUTE_WORK`] (counted as quoted values, before the parser sees them; the
+/// declarations of a DTD count as one element, as entities can hold elements).
pub(crate) fn too_wide(data: &[u8]) -> bool {
- scan(data, usize::MAX).1 > MAX_ATTRIBUTES
+ let (_, widest, work) = scan(data, usize::MAX);
+ widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK
}
-/// [`nesting`] and the most attribute values on one element; stops once either is past its limit.
-fn scan(data: &[u8], limit: usize) -> (usize, usize) {
+/// [`nesting`], the most attribute values on one element and the attribute work (see
+/// [`MAX_ATTRIBUTE_WORK`]); stops once any is past its limit.
+fn scan(data: &[u8], limit: usize) -> (usize, usize, usize) {
let find = |from: usize, pat: &[u8]| -> usize {
data.get(from..).and_then(|r| r.windows(pat.len()).position(|w| w == pat)).map_or(data.len(), |p| from + p + pat.len())
};
- let (mut depth, mut max, mut i, mut widest) = (0usize, 0usize, 0usize, 0usize);
+ let (mut depth, mut max, mut i, mut widest, mut work) = (0usize, 0usize, 0usize, 0usize, 0usize);
while let Some(off) = data.get(i..).and_then(|r| r.iter().position(|b| *b == b'<')) {
i += off;
let rest = data.get(i..).unwrap_or(&[]);
@@ -733,6 +741,19 @@ fn scan(data: &[u8], limit: usize) -> (usize, usize) {
i = find(i + 4, b"-->");
} else if rest.starts_with(b"");
+ } else if rest.starts_with(b"` closing its subset (the first `>` when it has none).
+ let end = match (rest.iter().position(|b| *b == b'['), rest.iter().position(|b| *b == b'>')) {
+ (Some(o), Some(g)) if o < g => find(i, b"]>"),
+ _ => find(i, b">"),
+ };
+ let quotes = data.get(i..end).unwrap_or(&[]).iter().filter(|b| matches!(**b, b'"' | b'\'')).count();
+ widest = widest.max(quotes / 2);
+ work = work.saturating_add((quotes / 2).saturating_mul(quotes / 2));
+ if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
+ return (max, widest, work);
+ }
+ i = end;
} else if rest.starts_with(b"") || rest.starts_with(b"");
} else if rest.starts_with(b"") {
@@ -758,20 +779,21 @@ fn scan(data: &[u8], limit: usize) -> (usize, usize) {
j += 1;
}
widest = widest.max(attrs);
- if widest > MAX_ATTRIBUTES {
- return (max, widest);
+ work = work.saturating_add(attrs * attrs);
+ if widest > MAX_ATTRIBUTES || work > MAX_ATTRIBUTE_WORK {
+ return (max, widest, work);
}
if !closed {
depth += 1;
max = max.max(depth);
if max > limit {
- return (max, widest);
+ return (max, widest, work);
}
}
i = j + 1;
}
}
- (max, widest)
+ (max, widest, work)
}
/// Whether `data` nests elements more than [`MAX_NESTING`] deep: the byte scan first, then the
diff --git a/crates/svg/src/import/hostile_tests.rs b/crates/svg/src/import/hostile_tests.rs
index 16731407c..daeaa085a 100644
--- a/crates/svg/src/import/hostile_tests.rs
+++ b/crates/svg/src/import/hostile_tests.rs
@@ -193,3 +193,15 @@ fn an_element_with_thousands_of_attributes_is_refused_before_parsing() {
let p = d.first_page().unwrap();
assert!(import_svg(&mut d, &svg(&format!("", many(100_000))), p, 0.0, 0.0, "x").is_err());
}
+
+#[test]
+fn attribute_work_is_bounded_over_the_whole_document_and_its_dtd() {
+ use super::too_wide;
+ let many = |n: usize| (0..n).map(|i| format!(" a{i}=\"1\"")).collect::();
+ let tag = format!("", many(4000));
+ assert!(!too_wide(format!("", tag.repeat(10)).as_bytes()));
+ assert!(too_wide(format!("", tag.repeat(40)).as_bytes()), "each element is within the limit, all together are not");
+ let dtd = format!("'>]>", many(5000));
+ assert!(too_wide(dtd.as_bytes()), "entities can hold elements");
+ assert!(!too_wide(b"]>"));
+}
diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs
index 7ed8d018f..6f557fb13 100644
--- a/crates/svg/src/import/text.rs
+++ b/crates/svg/src/import/text.rs
@@ -195,7 +195,7 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
let x = chunk.x().map_or(pen_x, f64::from) + d(t.dx());
let y = chunk.y().map_or(pen_y, f64::from) + d(t.dy());
char_at += count;
- let ci = char_index(text);
+ let ci = char_index(text, chunk.spans().iter().flat_map(|sp| [sp.start(), sp.end()]));
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, s, fonts))).collect();
if spans.is_empty() {
continue;
@@ -229,11 +229,30 @@ pub(crate) fn text(cx: &mut Ctx, t: &usvg::Text, parent: NodeId, base: Affine, d
}
}
-/// The characters of `text` before a byte offset (all of them for an offset that is past the end
-/// or inside a character), by a search in a table built once: many spans don't rescan the prefix.
-fn char_index(text: &str) -> impl Fn(usize) -> usize + '_ {
- let starts: Vec = text.char_indices().map(|(i, _)| i).collect();
- move |b| if text.is_char_boundary(b) { starts.partition_point(|s| *s < b) } else { starts.len() }
+/// The characters of `text` before each of the byte `offsets` (all of them for an offset that is
+/// past the end or inside a character): one pass over the text, whatever the number of spans.
+fn char_index(text: &str, offsets: impl IntoIterator) -> impl Fn(usize) -> usize {
+ let mut want: Vec = offsets.into_iter().collect();
+ want.sort_unstable();
+ want.dedup();
+ let mut found: Vec<(usize, usize)> = Vec::with_capacity(want.len());
+ let mut wanted = want.into_iter().peekable();
+ let mut count = 0;
+ for (i, _) in text.char_indices() {
+ while let Some(&o) = wanted.peek() {
+ match o.cmp(&i) {
+ std::cmp::Ordering::Equal => found.push((o, count)),
+ std::cmp::Ordering::Greater => break,
+ std::cmp::Ordering::Less => {}
+ }
+ wanted.next();
+ }
+ count += 1;
+ }
+ if wanted.any(|o| o == text.len()) {
+ found.push((text.len(), count));
+ }
+ move |b| found.binary_search_by_key(&b, |f| f.0).ok().and_then(|k| found.get(k)).map_or(count, |f| f.1)
}
/// The text of `lines` (one per line, stacked at their pitch; `s`: their scale): characters, the
@@ -269,7 +288,7 @@ fn on_path(cx: &mut Ctx, t: &usvg::Text, world: Affine, parent: NodeId) -> bool
let Some(len) = figcraft_geom::measure::polylines(&path).and_then(|l| l.first().map(|l| l.length())).filter(|l| *l > 1e-9) else { return false };
let fonts = cx.fonts.get_or_insert_with(Fonts::load);
let text = chunk.text();
- let ci = char_index(text);
+ let ci = char_index(text, chunk.spans().iter().flat_map(|sp| [sp.start(), sp.end()]));
let spans: Vec<_> = chunk.spans().iter().map(|sp| (ci(sp.start()), ci(sp.end()), sp, span_style(sp, 1.0, fonts))).collect();
let line = Line { x: 0.0, y: 0.0, anchor: chunk.anchor(), text: text.to_string(), spans };
let mut td = text_data(std::slice::from_ref(&line), 1.0);
diff --git a/crates/svg/src/import/text_tests.rs b/crates/svg/src/import/text_tests.rs
index 94c6ae5b2..c43bd7f9e 100644
--- a/crates/svg/src/import/text_tests.rs
+++ b/crates/svg/src/import/text_tests.rs
@@ -34,7 +34,7 @@ fn css_system_font_names_keep_their_name_where_the_system_font_is() {
#[test]
fn char_index_counts_the_characters_before_a_byte_offset() {
let t = "aé😀b";
- let ci = super::char_index(t);
+ let ci = super::char_index(t, [0, 1, 3, 7, 8, 2, 4, 99]);
assert_eq!([ci(0), ci(1), ci(3), ci(7), ci(8)], [0, 1, 2, 3, 4]);
assert_eq!([ci(2), ci(4), ci(99)], [4, 4, 4], "inside a character or past the end: all of them");
}
From cf77dfdabc040b98e2958429e40ad495dfd15659 Mon Sep 17 00:00:00 2001
From: "Dylan M. Taylor"
Date: Wed, 11 Nov 2026 21:31:26 +0000
Subject: [PATCH 12/13] load: an SVG that doesn't fit the allowance is taken
out again; charge after cleanup
---
crates/engine/src/cmd/file/load.rs | 20 ++++++++++++++++++--
1 file changed, 18 insertions(+), 2 deletions(-)
diff --git a/crates/engine/src/cmd/file/load.rs b/crates/engine/src/cmd/file/load.rs
index 77dd68198..da03ca1d1 100644
--- a/crates/engine/src/cmd/file/load.rs
+++ b/crates/engine/src/cmd/file/load.rs
@@ -438,7 +438,6 @@ fn expand_penpot_raw_svgs_within(doc: &mut Document, notes: &mut Vec, mu
}
let before = doc.node_count();
let imported = figcraft_svg::import_svg_with_notes(doc, xml.as_bytes(), id, 0.0, 0.0, &name);
- room = room.saturating_sub(doc.node_count().saturating_sub(before));
match imported {
Ok(imported) => {
// An SVG can be syntactically valid yet contain no supported drawable
@@ -453,6 +452,21 @@ fn expand_penpot_raw_svgs_within(doc: &mut Document, notes: &mut Vec, mu
}
continue;
}
+ // Charged once the empty ones are gone; one that doesn't fit is taken out again.
+ let added = doc.node_count().saturating_sub(before);
+ if added > room {
+ let _ = doc.remove(imported.frame);
+ if let Some(n) = doc.node_mut(id) {
+ n.plugin_data.insert("penpot.svgRawStatus".into(), "not-expanded".into());
+ }
+ if notes.len() < 100 {
+ notes.push(format!(
+ "Penpot SVG '{name}': not converted, the file's SVG layers are over the limit; the original markup is preserved"
+ ));
+ }
+ continue;
+ }
+ room -= added;
let size = doc.node(imported.frame).map(|n| (n.width, n.height));
if let Some((svg_w, svg_h)) = size
&& svg_w.is_finite()
@@ -837,7 +851,9 @@ mod penpot_svg_v10_tests {
})
.collect();
let mut warnings = Vec::new();
- expand_penpot_raw_svgs_within(&mut doc, &mut warnings, 1);
+ let nodes = doc.node_count();
+ expand_penpot_raw_svgs_within(&mut doc, &mut warnings, 4);
+ assert!(doc.node_count() - nodes <= 4, "never more layers than the allowance");
let status = |i: usize| doc.node(ids[i]).unwrap().plugin_data.get("penpot.svgRawStatus").cloned();
assert_eq!(status(0).as_deref(), Some("expanded"), "the first uses the allowance");
assert_eq!(status(1).as_deref(), Some("not-expanded"));
From 82da8f513acdcb49f75cec25685c7e74874178fd Mon Sep 17 00:00:00 2001
From: bflatastic
Date: Thu, 12 Nov 2026 09:19:05 +0700
Subject: [PATCH 13/13] file.openRecent: check the index with the shared
req_index
---
crates/engine/src/cmd/file/open.rs | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs
index b6e154c35..ea9a0d90a 100644
--- a/crates/engine/src/cmd/file/open.rs
+++ b/crates/engine/src/cmd/file/open.rs
@@ -30,11 +30,9 @@ pub(super) fn open_recent(s: &mut Session, p: &Value) -> Result {
allow(&path, Access::Read)?;
Some(path)
}
- (None, Some(i)) => {
- if !(i >= 0.0 && i.fract() == 0.0) {
- return Err(bad(CMD, "no such recent file"));
- }
- Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i as usize).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
+ (None, Some(_)) => {
+ let i = req_index(CMD, p, "index")?;
+ Some(s.prefs.recent_files.iter().filter(|r| listed(r)).nth(i).cloned().ok_or_else(|| bad(CMD, "no such recent file"))?)
}
_ => None,
};