From 12edbb10738153d80f7195f81a90e89025a1ce34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:09:30 -0800 Subject: [PATCH 001/106] Swatches: a pattern swatch dropped on empty canvas places a copy of its tile art A pattern swatch dragged from the Swatches panel and released where there is no art now runs the new `pattern.placeArt {name, x?, y?}`: one group holding a rectangle of the tile with no fill and no stroke at its back and the tile art in its place in the tile, centered on the drop point, selected, in one undo step. Dropped on art, the swatch fills it as before. `object.pattern.replaceArt` now reads a rectangle with no fill and no stroke at the back of the art (or at the back of one selected group) as the tile and leaves it out of the tile art, so the placed copy, edited and Alt-dragged back onto the swatch, keeps its place in the tile. Without such a rectangle the tile keeps its size and moves as far as the art's bounds moved from the old tile art's, instead of staying where it was. The help page describes this edit cycle and the unpainted bounding rectangle: https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=208 https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=204 Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 5 +- crates/engine/src/cmd/patterncmds.rs | 95 +++++++++-- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/pattern.rs | 154 +++++++++++++++++- crates/ui-egui/src/canvas/context.rs | 14 +- crates/ui-egui/src/canvas/tests.rs | 44 +++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/widgets/drag.rs | 6 +- docs/mcp.md | 27 ++- docs/target-app-parity.md | 3 +- 38 files changed, 352 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..ba4277da58 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ mod dynamic; mod symbolism; mod symbols; -pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; +pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint}; use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..afdf7d9f60 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -766,10 +766,11 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and +/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its /// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. -fn frame_marker(n: &Node) -> Option { +pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| match i { diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index e4b6d810a6..1b5d00de58 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; +use super::brushsym::frame_marker; use super::edit::{outermost, selected_roots}; use super::pathops::Beside; use super::{ @@ -43,10 +44,19 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), + cmd!( + "pattern.placeArt", + "Place Pattern Art", + [], + None, + "{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}", + can_replace_pattern_art, + pattern_place_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -429,41 +439,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { const C: &str = "object.pattern.replaceArt"; let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); let roots = roots(s, p, C)?; let d = &s.doc()?.doc; - let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; - if roots.is_empty() { + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect()); + if src.is_empty() { return Err(bad(C, "select the art for the pattern tile")); } - let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); if paints_pattern(d, &src, &name) { return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); } + let mut next = def.clone(); + next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) { + (Some(tile), ..) => tile, + (None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()), + (None, ..) => def.tile, + }; + next.art = src.clone(); + if next.size_tile_to_art { + next.fit_tile_to_art(); + } + let tile = next.tile; // Copies made from the same next id are equal when the art matches the tile art. let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); - if fresh(&old) == fresh(&src) { + if tile == def.tile && fresh(&def.art) == fresh(&src) { return Ok(json!({ "name": name })); } s.edit("Replace Pattern Art", |d, _| { let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); if let Some(def) = d.pattern_mut(&name) { def.art = art; - if def.size_tile_to_art { - def.fit_tile_to_art(); - } + def.tile = tile; } Ok(()) })?; Ok(json!({ "name": name })) } +/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted +/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as +/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members +/// are the art. Without such a rectangle the art is `src` and there is no tile. +fn tile_and_art(src: Vec>) -> (Vec>, Option) { + let mut art = src; + if let [g] = art.as_slice() + && let NodeKind::Group { children, clip: false } = &g.kind + && children.first().is_some_and(|c| frame_marker(c).is_some()) + && **g == Node::group(g.id, children.clone()) + { + art = children.clone(); + } + match art.first().and_then(|c| frame_marker(c)) { + Some(tile) => (art.split_off(1), Some(tile)), + None => (art, None), + } +} + +/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted +/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first +/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not +/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]). +fn pattern_place_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "pattern.placeArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if def.art.is_empty() { + return Err(bad(C, "no artwork")); + } + let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0); + let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted); + let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect()); + if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Pattern Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + /// What a piece of art uses by name, for [`paints_pattern`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Uses<'a> { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..5898abc113 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -480,6 +480,7 @@ pub(super) const ALLOWED: &[&str] = &[ "pattern.delete", "pattern.list", "pattern.options", + "pattern.placeArt", "pattern.transform", "perspective.attach", "perspective.draw", diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 01f8e76fbc..d45376ae82 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -222,8 +222,9 @@ fn blue_rect(s: &mut Session) -> NodeId { } /// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo -/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the -/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +/// step: the pattern keeps its name, swatch, place and options, the tile keeps its size and moves as +/// far as the art's bounds moved, art painted with it keeps the paint, and the selected art stays on +/// the canvas, selected. Undo and Redo swap the two tiles. #[test] fn replace_art_gives_a_pattern_new_tile_art() { let mut s = session(); @@ -243,7 +244,9 @@ fn replace_art_gives_a_pattern_new_tile_art() { assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); assert_eq!(def.art[0].appearance, node(&s, blue).appearance); assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); - assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + // The red square's bounds start at (0, 0) and the blue rectangle's at (100, 100). + assert_eq!(def.tile, old.tile + vectorcraft_geom::Vec2::new(100.0, 100.0), "the tile moves with the art"); + assert_eq!((def.tile_type, &def.name), (old.tile_type, &old.name), "the options stay"); assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); @@ -282,6 +285,151 @@ fn replace_art_that_matches_the_tile_art_records_nothing() { assert_eq!(doc(&s), &before); } +/// The geometric bounds of object `id`. +fn bounds_of(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +/// Place Pattern Art places a copy of the tile art in a group with an unpainted rectangle of the +/// tile at its back, centered where it is asked for (by default the first artboard's center), in +/// the current layer, selected, as one undo step; the pattern does not change. +#[test] +fn place_art_places_the_tile_art_with_its_tile() { + let mut s = session(); + let red = make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(-5.0, -5.0, 15.0, 15.0)); + let steps = s.doc().unwrap().history.undo.len(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Place Pattern Art"))); + assert_eq!(st.selection.objects.to_vec(), vec![id], "the copy is selected"); + assert_eq!(st.doc.parent_of(id), Some(st.doc.layers[0].id), "in the current layer"); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &def, "the pattern stays as it was"); + let group = node(&s, id); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("a group: {:?}", group.kind) }; + let [marker, art] = children.as_slice() else { panic!("the tile and the art: {children:?}") }; + // The tile, centered on (200, 150), is unpainted; the art keeps its place in the tile. + assert_eq!(marker.geometric_bounds(), Some(Rect::new(190.0, 140.0, 210.0, 160.0))); + assert!(marker.appearance.fill_paint().is_none() && marker.appearance.stroke().is_none_or(|k| k.paint.is_none())); + assert_eq!(art.geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + assert_eq!(art.appearance, def.art[0].appearance); + assert!(art.id != red && art.id != def.art[0].id, "a copy with an id of its own"); + // Without a position: the first artboard's center (the document is 400 × 400). + let centered = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap()); + assert_eq!(bounds_of(&s, centered).center(), Point::new(200.0, 200.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(centered).is_none(), "Undo removes the copies"); +} + +/// The placed copy, edited and given back with Replace Pattern Art, becomes the tile art, and its +/// rectangle becomes the tile: the art keeps its place in the tile, so the pattern draws the same +/// arrangement with the new art. Given back unchanged, nothing is recorded. +#[test] +fn placed_art_given_back_keeps_its_place_in_the_tile() { + let mut s = session(); + make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 210.0, 160.0), "the rectangle is the tile"); + assert_eq!(def.art.len(), 1, "the rectangle is not part of the art: {:?}", def.art); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + let old = before.pattern("Dots").unwrap(); + let place = |tile: Rect, art: &[Arc]| vectorcraft_doc::live::nodes_bounds(art).unwrap().origin() - tile.origin(); + assert_eq!(place(def.tile, &def.art), place(old.tile, &old.art), "the art keeps its place in the tile"); + // Given back again without a change: nothing to record. + let (again, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &again); + // Edited (the art recolored and the rectangle widened, ungrouped): the new art and tile. + let NodeKind::Group { children, .. } = &node(&s, id).kind else { panic!("a group") }; + let (marker, art) = (children[0].id, children[1].id); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + sel(&mut s, &[id]); + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(marker).is_some() && doc(&s).node(art).is_some(), "ungrouped"); + s.execute("object.transform", &json!({"ids": [marker.0], "matrix": [2, 0, 0, 1, -190, 0]})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [marker.0, art.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 230.0, 160.0), "the widened rectangle is the tile"); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].appearance, node(&s, art).appearance, "the recolored art"); +} + +/// Only an unpainted rectangle at the back of the art is the tile: a painted one, or an unpainted +/// one in front of other art, is tile art like any other, and a rectangle alone leaves no art. +#[test] +fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { + let mut s = session(); + make_dots(&mut s); + let back = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let front = rect(&mut s, 110.0, 110.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [front.0], "color": "#00ff00"})).unwrap(); + // Painted: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "color": "#ffffff"})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted, but in front of the other art: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [back.0], "none": true})).unwrap(); + sel(&mut s, &[back]); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted and at the back: the tile. + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!((def.art.len(), def.tile), (1, Rect::new(100.0, 100.0, 140.0, 140.0))); + // A rectangle alone is a tile with no art. + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); +} + +/// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that +/// is not a number, a pattern with no art, while a pattern is edited and on a locked layer. +#[test] +fn place_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + doc_mut(&mut s).patterns.push(vectorcraft_doc::pattern::PatternDef::new("Empty", vec![])); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let unchanged = |s: &Session, case: &str| { + assert_eq!(doc(s), &before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + for (case, p, why) in [ + ("no name", json!({}), "missing name"), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`"), + ("x not a number", json!({"name": "Dots", "x": "100"}), "`x` must be a number"), + ("y not a number", json!({"name": "Dots", "y": true}), "`y` must be a number"), + ("no art", json!({"name": "Empty"}), "no artwork"), + ] { + let err = s.execute("pattern.placeArt", &p).unwrap_err(); + assert!(err.to_string().contains(why), "{case}: {err}"); + unchanged(&s, case); + } + let layer = doc(&s).layers[0].id; + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": true})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert_eq!(err.to_string(), "the target layer is locked or hidden"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "locked: unchanged"); + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": false})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "while editing: unchanged"); +} + /// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, /// while a pattern is edited, and for art painted with the pattern itself, directly, through /// another pattern, through a symbol, through the paints a graph stores, through a graph design a diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 9cdec919b5..898c044c35 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -57,8 +57,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` /// for a brush library's). A Brushes panel scatter, art or pattern -/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`). A chip -/// follows the pointer meanwhile. +/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`), and so +/// does a Swatches panel pattern swatch, with its tile (`pattern.placeArt`). A chip follows the +/// pointer meanwhile. pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) { crate::panels::swatches::drag_preview(app, ui.ctx()); let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return }; @@ -119,6 +120,15 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile + // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + let at = xf.to_doc(pos); + if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { + app.status(e); + } + return; + } let Some(hit) = hit else { return }; let Some(st) = app.session.active() else { return }; let (cmd, params) = match &*d { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..908f7a7844 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9842,6 +9842,50 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { } } +#[test] +fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { + use vectorcraft_color::{Color, Paint}; + use widgets::{PanelDrag, SwatchRows}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let tile = app.session.execute("shape.rectangle", &json!({"x": 300, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("object.pattern.make", &json!({"ids": [tile], "name": "Checks", "edit": false})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let swatch = |name: &str, paint: Paint| { + let rows = SwatchRows { grabbed: name.into(), names: vec![name.into()], groups: false }; + PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None } + }; + let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let undo = undo_len(&app); + // A color swatch, and a pattern from elsewhere than the Swatches panel, place nothing. + drop(&mut app, swatch("Red", Paint::solid(Color::from_hex("#ed1c24").unwrap())), Point::new(250.0, 220.0)); + drop(&mut app, PanelDrag::paint(vectorcraft_doc::pattern::pattern_paint("Checks")), Point::new(250.0, 220.0)); + assert_eq!(undo_len(&app), undo); + // The pattern swatch: a copy of its tile art and tile, centered where it lands, selected. + drop(&mut app, pattern.clone(), Point::new(250.0, 220.0)); + let st = app.session.active().unwrap(); + assert_eq!(undo_len(&app), undo + 1, "{}", app.ui.status); + assert_eq!(st.history.undo.last().unwrap().label, "Place Pattern Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // On art, the swatch fills it as before. + drop(&mut app, pattern, Point::new(100.0, 100.0)); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); + assert!(matches!(&n, Paint::Pattern { pattern, .. } if pattern == "Checks"), "{n:?}"); +} + #[test] fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..f3f2642b89 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7518,6 +7518,7 @@ breakText Glyphs Глифи Place Brush Art Поставяне на графика на четка Replace Brush Art Замяна на графика на четка Replace Pattern Art Замяна на графика на мостра + Place Pattern Art Поставяне на графика на мостра Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика? Apply to Strokes Прилагане към щрихите Leave Strokes Оставяне на щрихите diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..dfeda0bf71 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7567,6 +7567,7 @@ shape Open Otvoren Place Brush Art Postavi crtež četkice Replace Brush Art Zamijeni crtež četkice Replace Pattern Art Zamijeni crtež uzorka + Place Pattern Art Postavi crtež uzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom? Apply to Strokes Primijeni na poteze Leave Strokes Ostavi poteze diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..4fae84451b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifs Place Brush Art Col·loca l’art del pinzell Replace Brush Art Substitueix l’art del pinzell Replace Pattern Art Substitueix l’art del motiu + Place Pattern Art Col·loca l’art del motiu Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou? Apply to Strokes Aplica als traços Leave Strokes Deixa els traços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..6a003e834f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8380,6 +8380,7 @@ breakText Glyphs Glyfy Place Brush Art Umístit kresbu štětce Replace Brush Art Nahradit kresbu štětce Replace Pattern Art Nahradit kresbu vzorku + Place Pattern Art Umístit kresbu vzorku Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou? Apply to Strokes Použít na tahy Leave Strokes Ponechat tahy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..4d4e1d1791 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10436,6 +10436,7 @@ breakText Glyphs Glyffer Place Brush Art Placér penselgrafik Replace Brush Art Erstat penselgrafik Replace Pattern Art Erstat mønstergrafik + Place Pattern Art Placér mønstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik? Apply to Strokes Anvend på streger Leave Strokes Bevar streger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..9ee0901afe 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8005,6 +8005,7 @@ breakText Glyphs Glyphen Place Brush Art Pinselgrafik platzieren Replace Brush Art Pinselgrafik ersetzen Replace Pattern Art Mustergrafik ersetzen + Place Pattern Art Mustergrafik platzieren Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen? Apply to Strokes Auf Konturen anwenden Leave Strokes Konturen beibehalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..195ea82836 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Γλύφοι Place Brush Art Τοποθέτηση σχεδίου πινέλου Replace Brush Art Αντικατάσταση σχεδίου πινέλου Replace Pattern Art Αντικατάσταση σχεδίου μοτίβου + Place Pattern Art Τοποθέτηση σχεδίου μοτίβου Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο; Apply to Strokes Εφαρμογή στα περιγράμματα Leave Strokes Διατήρηση περιγραμμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..e0d1f9cad3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8357,6 +8357,7 @@ breakText Glyphs Glifos Place Brush Art Colocar ilustración del pincel Replace Brush Art Reemplazar ilustración del pincel Replace Pattern Art Reemplazar ilustración del motivo + Place Pattern Art Colocar ilustración del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración? Apply to Strokes Aplicar a los trazos Leave Strokes Dejar los trazos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..c82597b70b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8447,6 +8447,7 @@ breakText Glyphs Merkit Place Brush Art Sijoita siveltimen kuvitus Replace Brush Art Korvaa siveltimen kuvitus Replace Pattern Art Korvaa kuvion kuvitus + Place Pattern Art Sijoita kuvion kuvitus Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus? Apply to Strokes Käytä viivoihin Leave Strokes Jätä viivat ennalleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..b4a1357166 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8376,6 +8376,7 @@ breakText Glyphs Glyphes Place Brush Art Placer l’illustration de la forme Replace Brush Art Remplacer l’illustration de la forme Replace Pattern Art Remplacer l’illustration du motif + Place Pattern Art Placer l’illustration du motif Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ? Apply to Strokes Appliquer aux contours Leave Strokes Conserver les contours diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..2696806612 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5150,6 +5150,7 @@ antiAlias Sharp શાર્પ Place Brush Art બ્રશ આર્ટ પ્લેસ કરો Replace Brush Art બ્રશ આર્ટ બદલો Replace Pattern Art પેટર્ન આર્ટ બદલો + Place Pattern Art પેટર્ન આર્ટ પ્લેસ કરો Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? સ્ટ્રોક્સ આ બ્રશ વાપરે છે. તે સ્ટ્રોક્સ પર નવી આર્ટ લાગુ કરવી છે કે તેમને જેમ છે તેમ રાખીને નવી આર્ટવાળી બ્રશની નકલ ઉમેરવી છે? Apply to Strokes સ્ટ્રોક્સ પર લાગુ કરો Leave Strokes સ્ટ્રોક્સ જેમ છે તેમ રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1c00d27a9a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4531,6 +4531,7 @@ arrowhead Feather पंख Place Brush Art ब्रश आर्टवर्क रखें Replace Brush Art ब्रश आर्टवर्क बदलें Replace Pattern Art पैटर्न आर्टवर्क बदलें + Place Pattern Art पैटर्न आर्टवर्क रखें Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें? Apply to Strokes स्ट्रोक्स पर लागू करें Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..ef865a6414 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8366,6 +8366,7 @@ breakText Glyphs Glifák Place Brush Art Ecsetgrafika elhelyezése Replace Brush Art Ecsetgrafika cseréje Replace Pattern Art Mintázatgrafika cseréje + Place Pattern Art Mintázatgrafika elhelyezése Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával? Apply to Strokes Alkalmazás a körvonalakra Leave Strokes Körvonalak megtartása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..8372f7f977 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8221,6 +8221,7 @@ breakText Glyphs Glif Place Brush Art Tempatkan karya seni kuas Replace Brush Art Ganti karya seni kuas Replace Pattern Art Ganti karya seni pola + Place Pattern Art Tempatkan karya seni pola Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru? Apply to Strokes Terapkan ke Stroke Leave Strokes Biarkan Stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c2cf171f71 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8043,6 +8043,7 @@ breakText Glyphs Glifi Place Brush Art Inserisci grafica del pennello Replace Brush Art Sostituisci grafica del pennello Replace Pattern Art Sostituisci grafica del motivo + Place Pattern Art Inserisci grafica del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica? Apply to Strokes Applica alle tracce Leave Strokes Lascia le tracce diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..75bf59ef58 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9932,6 +9932,7 @@ breakText Glyphs 字形 Place Brush Art ブラシのアートを配置 Replace Brush Art ブラシのアートを置き換え Replace Pattern Art パターンのアートを置き換え + Place Pattern Art パターンのアートを配置 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか? Apply to Strokes 線に適用 Leave Strokes 線を保持 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ae0f3fea37 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10554,6 +10554,7 @@ breakText Glyphs გლიფები Place Brush Art ფუნჯის ნახატის განთავსება Replace Brush Art ფუნჯის ნახატის ჩანაცვლება Replace Pattern Art პატერნის ნახატის ჩანაცვლება + Place Pattern Art პატერნის ნახატის განთავსება Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით? Apply to Strokes კონტურებზე გამოყენება Leave Strokes კონტურების დატოვება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..0c8afe603c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8015,6 +8015,7 @@ breakText Glyphs 글리프 Place Brush Art 브러시 아트 배치 Replace Brush Art 브러시 아트 바꾸기 Replace Pattern Art 패턴 아트 바꾸기 + Place Pattern Art 패턴 아트 배치 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까? Apply to Strokes 선에 적용 Leave Strokes 선 유지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..cf3aa33af9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10274,6 +10274,7 @@ breakText Glyphs Glyphs Place Brush Art Penseelillustratie plaatsen Replace Brush Art Penseelillustratie vervangen Replace Pattern Art Patroonillustratie vervangen + Place Pattern Art Patroonillustratie plaatsen Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen? Apply to Strokes Op contouren toepassen Leave Strokes Contouren behouden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..ae16f5e361 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8239,6 +8239,7 @@ breakText Glyphs Glify Place Brush Art Umieść kompozycję pędzla Replace Brush Art Zastąp kompozycję pędzla Replace Pattern Art Zastąp kompozycję wzorka + Place Pattern Art Umieść kompozycję wzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją? Apply to Strokes Zastosuj do obrysów Leave Strokes Pozostaw obrysy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..59275fc6c3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifos Place Brush Art Colocar Arte do Pincel Replace Brush Art Substituir Arte do Pincel Replace Pattern Art Substituir Arte do Padrão + Place Pattern Art Colocar Arte do Padrão Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte? Apply to Strokes Aplicar aos Traçados Leave Strokes Manter Traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..010a3c8e26 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Глифы Place Brush Art Поместить рисунок кисти Replace Brush Art Заменить рисунок кисти Replace Pattern Art Заменить рисунок узора + Place Pattern Art Поместить рисунок узора Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком? Apply to Strokes Применить к обводкам Leave Strokes Оставить обводки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..8f5b68b23c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8415,6 +8415,7 @@ breakText Glyphs Glyfer Place Brush Art Placera penselgrafik Replace Brush Art Ersätt penselgrafik Replace Pattern Art Ersätt mönstergrafik + Place Pattern Art Placera mönstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken? Apply to Strokes Använd på konturer Leave Strokes Behåll konturer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..27abc76472 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10270,6 +10270,7 @@ breakText Glyphs Glifler Place Brush Art Fırça Çizimini Yerleştir Replace Brush Art Fırça Çizimini Değiştir Replace Pattern Art Desen Çizimini Değiştir + Place Pattern Art Desen Çizimini Yerleştir Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin? Apply to Strokes Konturlara Uygula Leave Strokes Konturları Bırak diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..41ecd25cf7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8025,6 +8025,7 @@ breakText Glyphs Гліфи Place Brush Art Розмістити малюнок пензля Replace Brush Art Замінити малюнок пензля Replace Pattern Art Замінити малюнок візерунка + Place Pattern Art Розмістити малюнок візерунка Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком? Apply to Strokes Застосувати до обведень Leave Strokes Залишити обведення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..61bfc96683 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8071,6 +8071,7 @@ breakText Glyphs Glyph Place Brush Art Đặt đối tượng của cọ Replace Brush Art Thay đối tượng của cọ Replace Pattern Art Thay đối tượng của họa tiết + Place Pattern Art Đặt đối tượng của họa tiết Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới? Apply to Strokes Áp dụng cho nét Leave Strokes Giữ nguyên nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..cf31b8b7e3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8249,6 +8249,7 @@ breakText Glyphs 字形 Place Brush Art 置入画笔图稿 Replace Brush Art 替换画笔图稿 Replace Pattern Art 替换图案图稿 + Place Pattern Art 置入图案图稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本? Apply to Strokes 应用于描边 Leave Strokes 保留描边 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..dd143d13b9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8073,6 +8073,7 @@ breakText Glyphs 字符 Place Brush Art 置入筆刷圖稿 Replace Brush Art 取代筆刷圖稿 Replace Pattern Art 取代圖樣圖稿 + Place Pattern Art 置入圖樣圖稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本? Apply to Strokes 套用至筆畫 Leave Strokes 保留筆畫 diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index da6698b6be..4f7edafc41 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -10,8 +10,10 @@ pub enum PanelDrag { /// A paint: Swatches panel tiles, a Fill/Stroke proxy, a Recent Colors chip, a Color Guide /// color or the Gradient panel's thumbnail. Art it is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; /// null for a colour group, which paints nothing) through the active proxy's - /// `paint.setFill`/`paint.setStroke`; the Gradient panel's ramp takes its colour as a stop; the - /// Swatches panel moves `rows`, or makes a swatch of a paint dragged from elsewhere. `library`: + /// `paint.setFill`/`paint.setStroke`; a Swatches panel pattern swatch dropped where there is no + /// art places a copy of its tile art there (`pattern.placeArt`); the Gradient panel's ramp takes + /// its colour as a stop; the Swatches panel moves `rows`, or makes a swatch of a paint dragged + /// from elsewhere. `library`: /// the Libraries panel colour it is (library id, colour name), which that panel moves to where /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..155232b365 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6174,9 +6174,13 @@ details are VectorCraft's own rules; the help page says only that the option mov `object.pattern.replaceArt {name, ids?}` (Replace Pattern Art) makes copies of the selected art, or of `ids`, the tile art of pattern `name`, as one undo step, and returns `{name}`. The pattern keeps its name, its swatch and the swatch's -place, its tile and its options; with `sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and -`vSpacing`. Fills and strokes name the pattern, so every object painted with it draws the new tile. The art stays on the -canvas, selected as it was. Art that matches the tile art already records no undo step. The command is off while a +place, and its options. When the backmost object of the art is a rectangle with no fill and no stroke (or the backmost +member of one selected group, as `pattern.placeArt` places it), that rectangle becomes the tile and is left out of the +tile art, and the group's members become the art. Otherwise the tile keeps its size and moves by as much as the top-left +corner of the art's bounds moved from the old tile art's, so art drawn anywhere on the canvas stays in its tile. With +`sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and `vSpacing`. Fills and strokes name the pattern, +so every object painted with it draws the new tile. The art stays on the canvas, selected as it was. Art and a tile that +match the pattern's already record no undo step. A rectangle alone leaves no art and is refused. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, changing nothing, for a missing `name`, a pattern that does not exist, no art, and art painted with the pattern itself, directly or through the symbols, other patterns, graph designs and brushes it uses, or the series and label paints a graph stores. In the Swatches panel, art dragged off the canvas and released with Alt (Option on macOS) held over a @@ -6184,7 +6188,22 @@ pattern swatch runs it with that swatch's pattern; the swatch is outlined while else in the list, or without Alt, the art becomes a new pattern swatch as before. The help page describes replacing a pattern by dragging its edited tile onto the old swatch with Alt or Option held, with the pattern updated in the file (, -archived copy). Keeping the tile, the options and the source art are VectorCraft's own rules. +archived copy). Keeping the tile's size, moving it with the art, the options and the source art are VectorCraft's own +rules. The help page describes a tile bounded by a rectangle that is the backmost object, with no fill and no stroke +(, archived copy). + +`pattern.placeArt {name, x?, y?}` (Place Pattern Art) places a copy of pattern `name`'s tile art, centered on (`x`, `y`) +(default: the center of the first artboard), in the layer new art goes into, selects it, and returns `{id}`, in one undo +step. The copy is one group: a rectangle of the pattern's tile with no fill and no stroke at its back, then the tile art +in its place in the tile, so `object.pattern.replaceArt` reads the edited copy back with the same tile. The pattern does +not change. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, +changing nothing, for a missing `name`, a pattern that does not exist, an `x` or `y` that is not a number, a pattern +with no art ("no artwork") and a locked or hidden target layer. In the app, a pattern swatch dragged from the Swatches +panel onto an empty part of the canvas runs it at the drop point; dropped on art, the swatch fills it as before. The +help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and Alt-dragging +it back onto the swatch +(, archived copy). The group, +its rectangle, the centering and the default position are VectorCraft's own rules. ```json {"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..eadaf243ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -925,7 +925,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **Cancel, Delete and rename leave no paint of a missing pattern:** the help page lists Save a Copy, Done and Cancel for leaving pattern editing (https://helpx.adobe.com/illustrator/using/create-edit-patterns.html). Canceling a pattern made for the edit removes it with every swatch of it, a color group's included. Canceling a new pattern, `pattern.delete` and a `pattern.options` rename reach every paint of the pattern: art outside the editing layer, opacity mask art, type runs, symbol definitions, graph designs, the series and label paints a graph keeps for its next redraw, other patterns' tiles (a copy Save a Copy made included), graphic and character styles, brush art, and the fill, stroke and appearance new art takes. Canceling a new pattern and Delete make those paints no paint, a VectorCraft rule; a rename renames them. Canceling the edit of an existing pattern puts its definition back as it was when editing started; after a rename in Pattern Options, it also gives the pattern its old name back with its swatches and paints, unless another pattern, swatch or color group has taken that name. Undo and Redo restore new art's paints with the document. Tests in `tests/pattern.rs` cover each command. - **Move Tile with Art:** Pattern Options has the Move Tile with Art checkbox under Size Tile to Art, and with it on, moving the tile art in pattern editing mode moves the tile with it (). VectorCraft's own rules for what the page leaves open: the tile moves only when a move takes all of the tile art, by the same offset; rotations, scales, copies and anchor moves leave it in place; the option is off for a new pattern. `pattern.options {moveTileWithArt}` sets it and `pattern.list` reports it. Tests in `tests/pattern.rs` and `panels::pattern_options::tests` cover it. -- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch, tile and options (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch and options, the tile keeps its size and moves with the art (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **A pattern swatch dragged onto empty canvas places its tile art:** the help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and dragging it back onto the swatch with Alt (, archived copy), and a tile bounded by a backmost rectangle with no fill and no stroke (). A pattern swatch released over an empty part of the canvas places a copy of the pattern's tile art at the drop point, selected, in one undo step (`pattern.placeArt`); dropped on art, it still fills that art. `object.pattern.replaceArt` reads an unpainted rectangle at the back of the art as the tile. VectorCraft's own rules: the copy is one group with an unpainted rectangle of the tile at its back, centered on the drop point, and the pattern itself does not change. Tests in `tests/pattern.rs` and `canvas::tests` cover it. - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). From e94a8aed63ce72c12780f140265119e9269b1ec1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:57 -0800 Subject: [PATCH 002/106] Swatches: a drop inside a filled shape fills it with Path Only on With Object Selection by Path Only on, a pattern swatch or a brush with art dropped inside a filled object, away from its outline, found no art under the pointer and placed a copy of the tile art or brush art there. The empty-canvas check now counts fills (and type by its area), as the mesh-point check does, so the drop fills the object instead. The unpainted tile rectangle that object.pattern.replaceArt and brush.replaceArt read also has to run around its four corners in order: a closed path through them in a crossing order is art, not the tile. --- crates/engine/src/cmd/brushsym/brushes.rs | 7 +++++-- crates/engine/src/tests/pattern.rs | 13 +++++++++++++ crates/ui-egui/src/canvas/context.rs | 15 ++++++++++++++- crates/ui-egui/src/canvas/tests.rs | 21 +++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index afdf7d9f60..efcb425091 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -769,7 +769,8 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { /// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and /// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its -/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. +/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing +/// and that has no other appearance. pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() @@ -782,7 +783,9 @@ pub(crate) fn frame_marker(n: &Node) -> Option { let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; let at_corners = sp.anchors.len() == 4 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)) + // Each side, the closing one included, joins two corners that share an edge. + && sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y); (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) } diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index d45376ae82..36403a736a 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -391,6 +391,19 @@ fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { // A rectangle alone is a tile with no art. let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); + // An unpainted path through the four corners of its bounds in a crossing order is not a + // rectangle: art. + let corners = [(200, 200), (240, 240), (240, 200), (200, 240)]; + let anchors: Vec<_> = corners.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let bowtie = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + sel(&mut s, &[bowtie]); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [bowtie.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 2, "the crossing path is art: {:?}", def.art); + assert_ne!(def.tile, Rect::new(200.0, 200.0, 240.0, 240.0), "the crossing path is not the tile"); } /// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 898c044c35..584332b8af 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -113,6 +113,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. if let (None, widgets::PanelDrag::Brush { name, def }) = (&hit, &*d) && matches!(def["type"].as_str(), Some("scatter" | "art" | "pattern")) + && no_art_at(app, xf.to_doc(pos), xf.zoom) { let at = xf.to_doc(pos); if let Err(e) = app.run("brush.placeArt", json!({"name": name, "x": at.x, "y": at.y})) { @@ -122,7 +123,9 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. - if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) + && no_art_at(app, xf.to_doc(pos), xf.zoom) + { let at = xf.to_doc(pos); if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { app.status(e); @@ -177,6 +180,16 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } } +/// Whether no art is under document point `p` at `zoom`, with fills counted even with Object +/// Selection by Path Only and type objects by their area even with Type Object Selection by Path +/// Only: a brush's or a pattern swatch's art is placed only there. +fn no_art_at(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> bool { + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..opt }) + }) + .is_none() +} + /// The selected, editable gradient mesh and its points that a solid color dropped at document /// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh /// (fills count even with Object Selection by Path Only, and clipping applies), and the points are diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 908f7a7844..8b59e2734d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9840,6 +9840,19 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Side Tile")); } } + // With Object Selection by Path Only, inside a filled rectangle and away from its outline is + // still on art: nothing is placed. (The placed copies are undone first.) + for _ in 0..3 { + app.session.execute("edit.undo", &json!({})).unwrap(); + } + app.session.execute("shape.rectangle", &json!({"x": 250, "y": 200, "width": 100, "height": 80})).unwrap(); + app.session.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + drop(&mut app, "Arrow", Point::new(300.0, 240.0)); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); } #[test] @@ -9880,6 +9893,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // With Object Selection by Path Only, inside the filled rectangle and away from its outline is + // still on art: nothing is placed. + app.session.execute("paint.setFill", &json!({"ids": [id], "color": "#ffffff"})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = undo_len(&app); + drop(&mut app, pattern.clone(), Point::new(100.0, 100.0)); + assert_eq!(undo_len(&app), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); // On art, the swatch fills it as before. drop(&mut app, pattern, Point::new(100.0, 100.0)); let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); From 71e2f35b3b65b9f6d4827eeb1fef0e2571d62d1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:41:54 -0800 Subject: [PATCH 003/106] Web: the Paintbrush records an airbrush pen's stylus wheel The web build reads Pointer Events' tangentialPressure (-1..1, https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure) for each pen sample, including the positions a fast stroke's events coalesce, and gives the Paintbrush the wheel as 0..1, as the macOS reader does. Pointer Events give 0 for a pen without a wheel, so 0 counts as no wheel until the pen has reported another value since it came near; another pen, the other end, a canceled press and leaving the hover range start afresh. Mouse and finger input reads no wheel. The canvas now pairs the feed's per-move poses with the moves of a frame that carries touch events (the web pen), keeping the touch's force as the pressure, so each move keeps its own wheel. --- apps/vectorcraft-web/src/pencil.rs | 191 ++++++++++++++++++++++++++--- crates/ui-egui/src/canvas/drag.rs | 7 +- crates/ui-egui/src/canvas/tests.rs | 59 +++++++++ docs/target-app-parity.md | 4 +- 4 files changed, 241 insertions(+), 20 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 88b85e9d50..620d38ef1f 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -50,11 +50,31 @@ pub struct Pointers { eraser: bool, /// The pen's pressure and end for the canvas (`Services::stylus`). stylus: StylusFeed, + /// The pen whose finger wheel is read ([`Pointers::wheel`]). + wheel: Option, +} + +/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential +/// pressure other than 0 since it came near. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Wheel { + id: i32, + eraser: bool, + reads: bool, } impl Default for Pointers { fn default() -> Self { - Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() } + Self { + events: vec![], + pen: None, + fingers: vec![], + primary: None, + button: None, + eraser: false, + stylus: StylusFeed::on_ui_thread(), + wheel: None, + } } } @@ -67,6 +87,8 @@ struct Input<'a> { id: i32, button: i16, pressure: f32, + /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. + tangential: f32, modifiers: egui::Modifiers, } @@ -93,9 +115,29 @@ impl Pointers { self.stylus.clone() } - /// A pen moved or pressed with `pressure`, with the end it last pressed with. - fn pen_sample(&self, pressure: f32) { - self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() })); + /// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed + /// with. With `moved`, the sample comes with one `PointerMoved` and the feed keeps it for that + /// move ([`StylusFeed::set_move`]), so the canvas pairs each move with its own wheel. + fn pen_sample(&self, pressure: f32, wheel: Option, moved: bool) { + let sample = PenSample { pressure, eraser: self.eraser, pose: PenPose { wheel, ..PenPose::default() } }; + if moved { + self.stylus.set_move(sample); + } else { + self.stylus.set_sample(Some(sample)); + } + } + + /// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with + /// Pointer Events' `tangentialPressure` (−1..1, + /// ): [`PenPose`]'s + /// wheel of 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 + /// for a pen without a wheel, so 0 reads as none until that pen, with that end, has reported a + /// value other than 0 since it came near. A value that is not a number is none. + fn wheel(&mut self, id: i32, tangential: f32) -> Option { + let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads); + let reads = known || (tangential.is_finite() && tangential != 0.0); + self.wheel = Some(Wheel { id, eraser: self.eraser, reads }); + (reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0) } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -135,7 +177,10 @@ impl Pointers { } /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). - fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { + /// + /// `coalesced` holds the positions the pen reported since the last event, each with its + /// pressure and tangential pressure, the last one at `pos`. + fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool { let id = e.id; if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is @@ -164,19 +209,24 @@ impl Pointers { if let Some(end) = end { self.eraser = end; } - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { - self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second - // on an iPad), each with its pressure, so fast strokes keep their curve. - for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { - self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1)); - self.events.push(Event::PointerMoved(c.0)); + // on an iPad), each with its pressure and wheel, so fast strokes keep + // their curve. + for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) { + let wheel = self.wheel(id, tangential); + self.pen_sample(pressure, wheel, true); + self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure)); + self.events.push(Event::PointerMoved(at)); } + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force); self.events.push(Event::PointerMoved(pos)); } @@ -190,12 +240,19 @@ impl Pointers { } // Pointer Events report no end while a pen hovers: it keeps the end it // last pressed with. - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { - let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; - self.pen_sample(0.0); + let (phase, wheel) = if kind == "pointerup" { + // Lifted, the pen hovers on and keeps what it read of its wheel. + (TouchPhase::End, self.wheel(id, e.tangential)) + } else { + self.wheel = None; + (TouchPhase::Cancel, None) + }; + self.pen_sample(0.0, wheel, false); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -205,6 +262,11 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } + // Left the hover range or canceled: the pen reads its wheel afresh. + let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + if gone && self.wheel.is_some_and(|w| w.id == id) { + self.wheel = None; + } return self.pen.is_some(); } } @@ -277,7 +339,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, let z = runner.egui_ctx().zoom_factor(); let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z); let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z); - let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove" + let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove" && e.pointer_type() == "pen" // Safari before 17 hasn't it, and calling a missing method would abort the app. && js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false) @@ -285,7 +347,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, e.get_coalesced_events() .iter() .filter_map(|c| c.dyn_into::().ok()) - .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0))) + .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure())) .collect() } else { vec![] @@ -296,6 +358,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, id: e.pointer_id(), button: e.button(), pressure: e.pressure(), + tangential: e.tangential_pressure(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -344,7 +407,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } } fn reset() { @@ -501,6 +564,100 @@ mod tests { reset(); } + fn pen_at(button: i16, tangential: f32) -> Input<'static> { + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + } + + fn wheels(feed: &StylusFeed) -> Vec> { + feed.take_moves().into_iter().map(|(_, q)| q.wheel).collect() + } + + /// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the + /// feed as 0..1 with each move, once the pen has reported a value other than 0. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] { + assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true)); + } + assert_eq!( + wheels(&feed), + [None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)], + "none until reported; then 0 is half way, past the ends is clamped and not a number is none" + ); + assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.5), "the lift keeps the wheel"); + reset(); + } + + /// The positions a fast stroke's event coalesced keep their own wheel, in order, and the + /// event's own position comes last with its own. + #[test] + fn coalesced_moves_keep_their_wheel() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0)); + assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true)); + let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)]; + assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true)); + let moved: Vec = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect(); + let kept = feed.take_moves(); + assert_eq!(moved, [Pos2::ZERO, a, b, c]); + assert_eq!(kept.iter().map(|(_, q)| q.wheel).collect::>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]); + assert_eq!(kept.iter().map(|&(f, _)| f).collect::>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too"); + reset(); + } + + /// A pen that leaves the hover range, a canceled press, another pen and the other end each + /// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel. + #[test] + fn the_wheel_is_read_afresh_for_each_pen_and_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let learn = |p: &mut Pointers, button: i16| { + assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + }; + let hover = |p: &mut Pointers, id: i32| { + let mut e = pen_at(-1, 0.0); + e.id = id; + e.pressure = 0.0; + assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true)); + }; + learn(&mut p, 0); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "a lift into hover keeps it"); + p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a canceled press"); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "after a canceled press"); + learn(&mut p, 0); + hover(&mut p, 8); + assert_eq!(wheels(&feed).last(), Some(&None), "another pen"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "the other end"); + assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] { + let mut other = pen_at(0, 0.5); + (other.pointer_type, other.id) = (pointer_type, 10); + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!(feed.pose(), None, "{pointer_type} {kind}"); + assert!(feed.take_moves().is_empty(), "{pointer_type} {kind}"); + } + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..a96873d5aa 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,7 +193,7 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any. The last move is the pointer's position; the +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, /// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that @@ -222,6 +222,11 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< _ => {} } } + // A web pen's feed kept a pose (its wheel) for each of its moves: paired from the end, + // as below, with the touch's force kept as the pressure. + for (m, &(_, q)) in moves.iter_mut().rev().zip(samples.iter().rev()) { + m.2 = Some(q); + } } else if !samples.is_empty() { // The feed's last sample is the last move's: pair them from the end. A lift's 0 is // no pressure (the press keeps its last touch). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..8a642f7667 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11983,6 +11983,65 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { } } +/// The web build's pen comes as touch events with its pressure as their force, and its feed keeps +/// a wheel for each move: [`frame_moves`] keeps the touch's force and pairs each move with its own +/// pose from the end, and the last move's pose comes second. +#[test] +fn frame_moves_pair_a_web_pens_touches_with_the_feeds_poses() { + let ctx = egui::Context::default(); + let (a, b, c) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(30.0, 40.0)); + let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat(); + let feed = StylusFeed::default(); + let wheel = |w: f32| PenPose { wheel: Some(w), ..PenPose::default() }; + for (p, w) in [(0.9, 0.0), (0.2, 0.25), (0.8, 0.5), (0.6, 0.75)] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose: wheel(w), ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), None)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.2), Some(wheel(0.25))), (b, Some(0.8), Some(wheel(0.5)))], "an older move's sample is left over"); + assert_eq!(last, Some(wheel(0.75))); +} + +/// A web pen's stroke reaches the Paintbrush with each move's pressure, from its touch, and each +/// move's finger wheel, from the feed. +#[test] +fn a_web_pens_wheel_reaches_the_paintbrush_with_each_move() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let feed = StylusFeed::default(); + app.services.stylus = Some(feed.clone()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.select_tool("paintbrush"); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); + let moved = |pressure: f32, wheel: f32| { + feed.set_move(crate::stylus::PenSample { pressure, pose: PenPose { wheel: Some(wheel), ..PenPose::default() }, ..Default::default() }) + }; + moved(0.5, 0.0); + frame(&mut app, &ctx, pen(egui::TouchPhase::Start, at(300.0), 0.5)); + let mut events = vec![]; + for (x, pressure, wheel) in [(340.0, 0.3, 0.25), (380.0, 0.7, 0.5), (420.0, 0.9, 0.75), (460.0, 0.4, 1.0)] { + moved(pressure, wheel); + events.extend(pen(egui::TouchPhase::Move, at(x), pressure)); + } + frame(&mut app, &ctx, events); + frame(&mut app, &ctx, pen(egui::TouchPhase::End, at(460.0), 0.4)); + let (cmd, p) = app.session.journal.last().unwrap().clone(); + assert_eq!(cmd, "path.freehand"); + let points = p["points"].as_array().unwrap(); + let column = |i: usize| -> Vec { points.iter().filter_map(|s| s.get(i).and_then(serde_json::Value::as_f64)).collect() }; + let (pressures, wheels) = (column(2), column(6)); + for (pressure, wheel) in [(0.3, 0.25), (0.7, 0.5), (0.9, 0.75)] { + let paired = points.iter().any(|s| { + let near = |i: usize, v: f64| s.get(i).and_then(serde_json::Value::as_f64).is_some_and(|got| (got - v).abs() < 0.01); + near(2, pressure) && near(6, wheel) + }); + assert!(paired, "{pressure} with {wheel}: {pressures:?} {wheels:?}"); + } +} + /// The last move of a frame reaches the Paintbrush with the tilt the host's feed kept for that /// move, not with a later pen sample that came without a move. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..dba4dd200d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2057,7 +2057,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2065,7 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (), for each move of a pen including the positions a fast stroke's events coalesce; Windows pointer messages have no field for it. Pointer Events give 0 for a pen without a wheel, so in the web build, as on macOS, 0 counts as no wheel until the pen has reported another value since it came near; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. That rule is VectorCraft's own. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `canvas::tests::a_web_pens_wheel_reaches_the_paintbrush_with_each_move` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 32fa158676215acf084360fd0b8e43e52b4c8fbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:20:02 -0800 Subject: [PATCH 004/106] Stylus: docs name the web build as a source of the airbrush wheel The stylus module doc and StylusFeed::set_move now say the web build reads the wheel from Pointer Events' tangentialPressure and keeps a pose for each move. The frame_moves doc comment is rewrapped. --- crates/ui-egui/src/canvas/drag.rs | 15 ++++++++------- crates/ui-egui/src/stylus.rs | 9 +++++---- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index a96873d5aa..71e09a39ff 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,13 +193,14 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the -/// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no -/// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, -/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that -/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's -/// position is the pointer's. The last move before it is left out only when it is at that -/// position; its tilt and rotation come second either way. +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). +/// The last move is the pointer's position; the tilt and rotation the feed kept for it come +/// second, if any. A mouse's moves count too, with no pressure: a fast mouse stroke otherwise keeps +/// one position a frame, a sample every few pixels, too few for a low Fidelity to follow the hand +/// (#3328). With `release`, the moves stop at that button's button-up in this frame, if it came: +/// the moves after it are hover, and the button-up's position is the pointer's. The last move +/// before it is left out only when it is at that position; its tilt and rotation come second +/// either way. pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0b27d24127..1111b5983e 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -12,8 +12,9 @@ //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. //! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the -//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on -//! Windows, whose pointer messages have no field for it, or in the web build. +//! host reads it: from XInput2 on X11, from AppKit on macOS and from Pointer Events' +//! `tangentialPressure` in the web build. The app does not read it on Windows, whose pointer +//! messages have no field for it. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before @@ -157,8 +158,8 @@ impl StylusFeed { } /// Like [`Self::set_sample`], for a pen sample that comes with one pointer move of the window, - /// read before the window handles the move (macOS): its pressure, tilt and rotation are also - /// kept for that move ([`Self::take_moves`]). + /// read before the window handles the move (macOS and the web build): its pressure, tilt, + /// rotation and wheel are also kept for that move ([`Self::take_moves`]). pub fn set_move(&self, sample: PenSample) { self.set_sample(Some(sample)); let mut pen = self.lock(); From 8833fde4a962923df8ebc4a6c15bc8bcb05fbaee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:04:53 -0800 Subject: [PATCH 005/106] Web: the stylus wheel stays learned when the pen hovers across the canvas edge A hovering pen that moved off the canvas onto another element cleared what it had read of its airbrush wheel, so back on the canvas a centered wheel (0) read as no wheel. The pen now reads its wheel afresh only when a pointerleave names no element it moved onto (relatedTarget), which is how leaving the hover range is reported, on the canvas or off it. --- apps/vectorcraft-web/src/pencil.rs | 38 ++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 620d38ef1f..f19939bde8 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -89,6 +89,9 @@ struct Input<'a> { pressure: f32, /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. tangential: f32, + /// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving + /// one element for another is still in its hover range. + entered: bool, modifiers: egui::Modifiers, } @@ -262,8 +265,10 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } - // Left the hover range or canceled: the pen reads its wheel afresh. - let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + // Left the hover range (a leave onto no element, on the canvas or off it) + // or canceled: the pen reads its wheel afresh. Moving onto another element + // keeps what it read. + let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel"; if gone && self.wheel.is_some_and(|w| w.id == id) { self.wheel = None; } @@ -359,6 +364,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, button: e.button(), pressure: e.pressure(), tangential: e.tangential_pressure(), + entered: e.related_target().is_some(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -407,7 +413,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() } } fn reset() { @@ -565,7 +571,7 @@ mod tests { } fn pen_at(button: i16, tangential: f32) -> Input<'static> { - Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() } } fn wheels(feed: &StylusFeed) -> Vec> { @@ -658,6 +664,30 @@ mod tests { reset(); } + /// A hovering pen that moves off the canvas onto another element and back keeps what it read + /// of its wheel; one that leaves the hover range off the canvas reads it afresh. + #[test] + fn the_wheel_survives_crossing_the_canvas_edge() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + let mut hover = pen_at(-1, 0.0); + hover.pressure = 0.0; + let mut onto = pen_at(-1, 0.0); + (onto.pressure, onto.entered) = (0.0, true); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false)); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "moved onto another element and back"); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + p.feed("pointerleave", &hover, Pos2::ZERO, &[], false); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range off the canvas"); + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] From 90752660adc593f619518d6882b357a0ee6fe63c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:18:50 -0800 Subject: [PATCH 006/106] Scripts: documents give scripts their variables, data sets and variable libraries A script's Document has variables, dataSets, activeDataset, variablesLocked, importVariables(file) and exportVariables(file), with the Variables, Variable, Datasets and Dataset classes and the VariableKind enumeration. Every page item has visibilityVariable, and type, placed and raster images and graphs have contentVariable. Each change runs a variable.* or dataset.* command and joins the run's undo step; a value that changes nothing runs no command. - variable.setBinding binds one object's visibility or content slot to one variable, or to none, in one undo step. - dataset.update takes a name, to update a data set that is not the active one without switching to it. - A File crosses to the host as its path under a hidden key, and a plain object that carries the key is refused. importVariables and exportVariables check the path against what the script's own File objects may read or write; the open documents' files do not count. Docs: docs/mcp.md, docs/target-app-parity.md, docs/gaps.md (G6). --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/variablecmds.rs | 89 +- crates/engine/src/file_access.rs | 3 +- crates/engine/src/script/dom.rs | 21 +- crates/engine/src/script/dom/variables.rs | 802 ++++++++++++++++++ crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_variables.rs | 433 ++++++++++ crates/js/src/file_classes.rs | 13 + crates/js/src/host.rs | 12 +- crates/js/src/host_classes.rs | 13 + crates/js/src/lib.rs | 2 +- docs/gaps.md | 3 +- docs/mcp.md | 36 +- docs/target-app-parity.md | 1 + 16 files changed, 1416 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/variables.rs create mode 100644 crates/engine/src/tests/script_variables.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..538b9e0dbf 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -952,6 +952,8 @@ pub use variablecmds::utf16_order_without_mark; /// file: its size limit, its text, its cells and the data `graph.setData` takes from them. pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +/// The kind of variable that drives an object's content (`variable.setBinding`). +pub(crate) use variablecmds::content_kind; /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..33aaab396e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -727,6 +727,7 @@ pub(super) const ALLOWED: &[&str] = &[ "variable.makeTextDynamic", "variable.makeVisibilityDynamic", "variable.rename", + "variable.setBinding", "variable.sort", "variable.unbind", ]; diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..fdd4231dc3 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -451,6 +451,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result { Ok(json!({"unbound": n})) } +/// The kind of variable that drives the content of `n`: text for type, image for an image object +/// and graph for a graph root. `None` for other objects, which have only a visibility slot. +pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option { + match &n.kind { + NodeKind::Text(_) => Some(VariableKind::Text), + NodeKind::Image(_) => Some(VariableKind::Image), + _ if n.extras().graph.is_some() => Some(VariableKind::Graph), + _ => None, + } +} + +/// The variables of `kind` bound to `id`, in the order they are defined. +fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec { + let Some(bound) = vars.bindings.get(&id) else { return Vec::new() }; + vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect() +} + +/// The slot `variable.setBinding` names: an object's visibility, or its content. +fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> { + let node = doc.node(id).ok_or(EngineError::NoNode(id))?; + match str_param(p, "slot") { + Some("visibility") => Ok(("visibility", VariableKind::Visibility)), + Some("content") => { + content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0))) + } + _ => Err(bad(cmd, "`slot` must be `visibility` or `content`")), + } +} + +/// Bind one object's visibility or content to one variable, or to none, in one undo step: the +/// object's other variables of that slot's kind are unbound. The content of type takes a text +/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded +/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing +/// changes when one fails. A call that leaves the bindings as they were adds no undo step. +fn set_binding(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.setBinding"; + let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?; + let variable = match p.get("variable") { + None | Some(Value::Null) => None, + Some(v) => Some(named(v.as_str(), "variable", C)?), + }; + let doc = &s.doc()?.doc; + let (slot, kind) = slot_kind(doc, id, p, C)?; + if let Some(name) = &variable { + let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; + if have != kind { + return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); + } + check_bindable(doc, &[id], kind, C)?; + if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); + } + } + let unbound: Vec = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect(); + let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" }; + edit_variables(s, label, |vars| { + for n in &unbound { + vars.unbind(id, n); + } + if let Some(n) = &variable { + vars.bind(id, n); + } + Ok(()) + })?; + Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound})) +} + /// The `variable` a command names, which must be defined; `None` when it names none. fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result> { let name = optional_name(p, "variable", cmd)?; @@ -690,13 +757,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// other than a visibility variable, locked or inside a locked layer or group, or, for any /// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. With every bound object locked, no value is -/// written; an update that writes no value adds no undo step. +/// update, so say so rather than picking one. `name` updates that row instead, and leaves the +/// active row as it is. With every bound object locked, no value is written; an update that +/// writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); + let given = match p.get("name") { + None => None, + Some(v) => Some(named(v.as_str(), "name", C)?), + }; let st = s.doc()?; - let Some(name) = st.doc.variables.active_dataset.clone() else { + let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else { return Err(bad(C, "no active data set")); }; if !anything_bound(&st.doc) { @@ -975,6 +1047,15 @@ pub fn specs() -> Vec { has_doc, unbind ), + cmd!( + "variable.setBinding", + "Bind Variable", + [], + None, + "{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}", + has_doc, + set_binding + ), cmd!( "variable.lock", "Lock Variables", @@ -1027,7 +1108,7 @@ pub fn specs() -> Vec { "Update Data Set", ["Window", "Variables"], None, - "{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", + "{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", has_doc, dataset_update ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..f61179f43d 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -300,7 +300,8 @@ impl ScriptGate { ScriptGate { also: Some(also), ..self.clone() } } - fn check(&self, path: &str, access: Access) -> Result<(), String> { + /// May `path` be read (or written) through this gate? + pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..a7303cf4e6 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,15 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod variables; + +pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; + +/// After each command a script runs ([`variables::after_command`]). +pub(super) fn after_command(h: &Host, id: &str) { + variables::after_command(h, id); +} + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -85,13 +94,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the `Variable` and `Dataset` objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + vars: variables::Handles, } impl State { @@ -1660,6 +1670,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + variables::define_enums(realm)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -1714,6 +1725,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(variables::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1763,7 +1775,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "tags", "uRL", "uuid", - "visibilityVariable", "wrapInside", "wrapOffset", "wrapped", @@ -1776,8 +1787,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "PageItem", m)), ); + page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(variables::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs new file mode 100644 index 0000000000..270a7cfc08 --- /dev/null +++ b/crates/engine/src/script/dom/variables.rs @@ -0,0 +1,802 @@ +//! Variables and data sets in the script object model: `Document.variables`, `dataSets`, +//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`, +//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the +//! help pages , +//! , +//! , +//! , +//! , +//! and +//! describe them. Every change runs +//! one of the `variable.*` and `dataset.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change +//! made through the object keeps the object working; once the name leaves the document any other +//! way (a delete, a rename by another command, an undo, a kind change by another command, or an +//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or +//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most +//! [`MAX_HANDLES`] of each. +//! - Collections list variables and data sets in the order the document holds them, counted from +//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`. +//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first +//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data +//! set named `Data Set 1` and so on, which becomes the active one. +//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`, +//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file +//! declared without one VectorCraft knows, and cannot be given. +//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order. +//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows +//! its values in the art, as `display()` does. +//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the +//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the +//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all. +//! An embedded image (`RasterItem`) cannot take an image variable. +//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the +//! script may read, or write, as its `File` objects may: the files of the open documents do not +//! count. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, +}; +use crate::doc::{Node, Variable, VariableKind}; +use crate::file_access::Access; + +/// The error for a `Variable` whose variable left the document, or that came from an earlier run. +pub const STALE_VARIABLE: &str = "Stale variable"; +/// The error for a `Dataset` whose data set left the document, or that came from an earlier run. +pub const STALE_DATASET: &str = "Stale data set"; +/// The most `Variable` objects, and the most `Dataset` objects, one run gives out. +pub const MAX_HANDLES: usize = 10_000; + +/// The kinds, each with the name of its `VariableKind` member. +const KINDS: [(VariableKind, &str); 5] = [ + (VariableKind::Text, "TEXTUAL"), + (VariableKind::Visibility, "VISIBILITY"), + (VariableKind::Image, "IMAGE"), + (VariableKind::Graph, "GRAPH"), + (VariableKind::Unknown, "Unknown"), +]; + +/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a +/// variable (`None` for a data set) and whether it still names it. +struct Entry { + uid: u64, + name: String, + kind: Option, + alive: bool, +} + +/// The objects of one class a run gave out: each one's handle is its index here. +#[derive(Default)] +struct Table { + entries: Vec, + /// The entry that names each document's name, while it does. + live: HashMap<(u64, String), usize>, +} + +impl Table { + /// The entry for `name` of the document `uid`, made when there is none. + fn slot(&mut self, uid: u64, name: &str, kind: Option, what: &str) -> std::result::Result { + if let Some(&at) = self.live.get(&(uid, name.to_string())) + && self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind) + { + return Ok(at); + } + if self.entries.len() >= MAX_HANDLES { + return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run"))); + } + self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true }); + let at = self.entries.len() - 1; + self.live.insert((uid, name.to_string()), at); + Ok(at) + } + + /// The entry `at` no longer names anything. + fn kill(&mut self, at: usize) { + if let Some(e) = self.entries.get_mut(at) { + e.alive = false; + let k = (e.uid, std::mem::take(&mut e.name)); + if self.live.get(&k) == Some(&at) { + self.live.remove(&k); + } + } + } + + /// The entry `at` names `name`, of `kind`, from now on: a rename made through it. + fn rename(&mut self, at: usize, name: &str, kind: Option) { + let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return }; + self.kill(at); + if let Some(e) = self.entries.get_mut(at) { + *e = Entry { uid, name: name.to_string(), kind, alive: true }; + } + self.live.insert((uid, name.to_string()), at); + } + + /// Kills each live entry `keep` refuses. + fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) { + let gone: Vec = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect(); + for at in gone { + self.kill(at); + } + } +} + +/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last +/// checked against it. +#[derive(Default)] +pub(super) struct Handles { + vars: RefCell, + sets: RefCell
, + seen: RefCell>, +} + +/// After each command a script runs: the objects whose variable or data set it removed stop +/// working, so one made again under the same name does not bring them back. A command that replaces +/// the data sets (an import) stops every `Dataset` of its document. +pub(super) fn after_command(h: &Host, id: &str) { + let hs = &h.dom.vars; + if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { + return; + } + let Ok(s) = h.session.try_borrow() else { return }; + let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); + let changed: HashSet = { + let seen = hs.seen.borrow(); + now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect() + }; + *hs.seen.borrow_mut() = now; + if changed.is_empty() && replaced.is_none() { + return; + } + let mut kinds: HashMap> = HashMap::new(); + let mut sets: HashMap> = HashMap::new(); + for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) { + let vars = &st.doc.variables; + kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect()); + sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect()); + } + hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind); + hs.sets + .borrow_mut() + .sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str())))); +} + +fn kind_text(k: VariableKind) -> Data { + let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n); + text(format!("VariableKind.{name}")) +} + +fn kind_of(d: &Data) -> std::result::Result { + let found = match d { + Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k), + _ => None, + }; + match found { + Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())), + Some(k) => Ok(k), + None => Err(HostError::Type("kind must be a VariableKind value".into())), + } +} + +/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes. +fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("the {what} is too long"))); + } + Ok(s) +} + +/// The `name` field of a command's result. +fn result_name(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }) +} + +fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer { + let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?; + Ok(host_ref("Variable", &[float(h.run), float(at as u64)])) +} + +fn set_ref(h: &Host, uid: u64, name: &str) -> Answer { + let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?; + Ok(host_ref("Dataset", &[float(h.run), float(at as u64)])) +} + +/// A variable or data set an object names: its document, its handle's index and its name. +struct Named { + doc: Doc, + at: usize, + name: String, + kind: Option, +} + +/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its +/// document. +fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result { + let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) }; + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let stale = || HostError::Error(stale.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?; + let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets }; + let (uid, name, kind) = { + let t = table.borrow(); + let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?; + (e.uid, e.name.clone(), e.kind) + }; + let doc = find_doc(h, float(h.run), float(uid)); + let there = doc.is_some_and(|doc| { + with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() } + }) + }); + match doc { + Some(doc) if there => Ok(Named { doc, at, name, kind }), + _ => { + table.borrow_mut().kill(at); + Err(stale()) + } + } +} + +fn this_var(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), true) +} + +fn this_set(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), false) +} + +/// The index argument of a collection's indexer: a whole number, or `None`. +fn index_arg(d: &Data) -> Option { + match d { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_variables(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Variables", &[float(h.run), float(doc.uid)])) +} + +fn doc_datasets(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)])) +} + +fn doc_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked))) +} + +/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so. +fn doc_set_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) }; + if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked { + on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?; + } + Ok(Data::Undefined) +} + +fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Null), + } +} + +/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active +/// one and the art already shows it. +fn display(h: &Host, set: &Named) -> Answer { + let shown = with_doc(h, set.doc, |_, st| { + let vars = &st.doc.variables; + vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values())) + }); + if !shown { + on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?; + } + Ok(Data::Undefined) +} + +fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + if handle_of(arg(a, 1), "Dataset").is_none() { + return Err(HostError::Type("activeDataset must be a Dataset".into())); + } + let set = named_of(h, arg(a, 1), false)?; + if set.doc.uid != doc.uid { + return Err(HostError::Error("the data set is in another document".into())); + } + display(h, &set) +} + +/// The path of the `File` argument of `what`, which must be a file the script may reach for +/// `access` through its own `File` objects. +fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result { + let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) }; + if path.chars().count() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(format!("{what}: the path is too long"))); + } + let gate = h.disk.borrow().gate(Vec::new()); + gate.check(path, access).map_err(HostError::Error)?; + Ok(path.to_string()) +} + +/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's +/// variables and data sets with the library's. +fn doc_import(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "importVariables", Access::Read)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +/// `exportVariables(file)`: `variable.saveLibrary` into the file. +fn doc_export(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "exportVariables", Access::Write)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +// ---- Variables ---- + +fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Variables") +} + +fn vars_typename(h: &Host, a: &[Data]) -> Answer { + vars_doc(h, a)?; + Ok(text("Variables")) +} + +fn vars_length(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64))) +} + +fn vars_parent(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn vars_at(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) { + Some(v) => var_ref(h, doc.uid, &v), + None => Ok(Data::Undefined), + } +} + +fn vars_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.variables.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.variable(name).cloned()) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v)) +} + +fn vars_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => vars_by_name(h, a), + Data::Number(_) => match vars_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the +/// first free name). → the new variable. +fn vars_add(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + (1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default() + }); + on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?; + var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text }) +} + +/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is +/// none. +fn vars_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Variable ---- + +fn var_typename(h: &Host, a: &[Data]) -> Answer { + this_var(h, a)?; + Ok(text("Variable")) +} + +fn var_parent(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(doc_ref(h, v.doc.uid)) +} + +fn var_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_var(h, a)?.name)) +} + +/// `name = text`: `variable.rename`, which trims it, with no command when the name stays. +fn var_set_name(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == v.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind); + Ok(Data::Undefined) +} + +fn var_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown))) +} + +/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot +/// hold it and drops the variable's values, with no command when the kind stays. +fn var_set_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let kind = kind_of(arg(a, 1))?; + if Some(kind) == v.kind { + return Ok(Data::Undefined); + } + on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?; + h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind)); + Ok(Data::Undefined) +} + +fn var_page_items(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + with_doc(h, v.doc, |_, st| { + let ids: Vec = + st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) + }) +} + +/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values. +fn var_remove(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?; + h.dom.vars.vars.borrow_mut().kill(v.at); + Ok(Data::Undefined) +} + +// ---- Datasets ---- + +fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Datasets") +} + +fn sets_typename(h: &Host, a: &[Data]) -> Answer { + sets_doc(h, a)?; + Ok(text("Datasets")) +} + +fn sets_length(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64))) +} + +fn sets_parent(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn sets_at(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Undefined), + } +} + +fn sets_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.datasets.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone())) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n)) +} + +fn sets_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sets_by_name(h, a), + Data::Number(_) => match sets_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new +/// data set and makes it the active one. → the new data set. +fn sets_add(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?; + let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?; + set_ref(h, doc.uid, &name) +} + +/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is +/// none. +fn sets_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Dataset ---- + +fn set_typename(h: &Host, a: &[Data]) -> Answer { + this_set(h, a)?; + Ok(text("Dataset")) +} + +fn set_parent(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + Ok(doc_ref(h, d.doc.uid)) +} + +fn set_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_set(h, a)?.name)) +} + +/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays. +fn set_set_name(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == d.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.sets.borrow_mut().rename(d.at, &name, None); + Ok(Data::Undefined) +} + +fn set_display(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + display(h, &d) +} + +/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no +/// command when it already holds what the bound objects hold. +fn set_update(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let same = with_doc(h, d.doc, |_, st| { + let doc = &st.doc; + let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()); + bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values())) + }); + if !same { + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?; + } + Ok(Data::Undefined) +} + +/// `dataset.remove()`: `dataset.delete` of this data set. +fn set_remove(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?; + h.dom.vars.sets.borrow_mut().kill(d.at); + Ok(Data::Undefined) +} + +// ---- Page items ---- + +/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its +/// content. +fn slot_kind(n: &Node, content: bool) -> std::result::Result { + if !content { + return Ok(VariableKind::Visibility); + } + crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into())) +} + +/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's +/// kind bound to the object, in the order the variables are defined, or `null`. +fn binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let found = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned()) + })?; + match found { + Some(v) => var_ref(h, item.doc.uid, &v), + None => Ok(Data::Null), + } +} + +/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of +/// the object's document, or with none for `null`. No command runs when the object already has just +/// that binding of the slot's kind. +fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let variable = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "Variable").is_some() => { + let v = named_of(h, d, true)?; + if v.doc.uid != item.doc.uid { + return Err(HostError::Error("the variable is in another document".into())); + } + Some(v.name) + } + _ => return Err(HostError::Type("give a Variable or null".into())), + }; + let same = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + let held: Vec<&str> = + vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect(); + Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::>()) + })?; + if !same { + let slot = if content { "content" } else { "visibility" }; + edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?; + } + Ok(Data::Undefined) +} + +fn item_visibility(h: &Host, a: &[Data]) -> Answer { + binding(h, a, false) +} + +fn item_set_visibility(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, false) +} + +fn item_content(h: &Host, a: &[Data]) -> Answer { + binding(h, a, true) +} + +fn item_set_content(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, true) +} + +// ---- Registration ---- + +/// The members this module adds to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("variables", get(l, doc_variables)), + ("dataSets", get(l, doc_datasets)), + ("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)), + ("variablesLocked", property(l, doc_locked, doc_set_locked)), + ("importVariables", method(l, doc_import)), + ("exportVariables", method(l, doc_export)), + ]) +} + +/// The members this module adds to `PageItem`. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))]) +} + +/// The members this module adds to the page item class `class`. +pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> { + match class { + "TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]), + _ => Vec::new(), + } +} + +/// The classes this module adds. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "Variables", + None, + named(vec![ + ("typename", get(l, vars_typename)), + ("length", get(l, vars_length)), + ("parent", get(l, vars_parent)), + ("index", method(l, vars_index)), + ("getByName", method(l, vars_by_name)), + ("add", method(l, vars_add)), + ("removeAll", method(l, vars_remove_all)), + ]), + Some(function(l, vars_at)), + ), + class( + "Variable", + None, + named(vec![ + ("typename", get(l, var_typename)), + ("parent", get(l, var_parent)), + ("name", property(l, var_name, var_set_name)), + ("kind", property(l, var_kind, var_set_kind)), + ("pageItems", get(l, var_page_items)), + ("remove", method(l, var_remove)), + ]), + None, + ), + class( + "Datasets", + None, + named(vec![ + ("typename", get(l, sets_typename)), + ("length", get(l, sets_length)), + ("parent", get(l, sets_parent)), + ("index", method(l, sets_index)), + ("getByName", method(l, sets_by_name)), + ("add", method(l, sets_add)), + ("removeAll", method(l, sets_remove_all)), + ]), + Some(function(l, sets_at)), + ), + class( + "Dataset", + None, + named(vec![ + ("typename", get(l, set_typename)), + ("parent", get(l, set_parent)), + ("name", property(l, set_name, set_set_name)), + ("display", method(l, set_display)), + ("update", method(l, set_update)), + ("remove", method(l, set_remove)), + ]), + None, + ), + ] +} + +/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings. +pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect(); + realm.define_host_object("VariableKind", items) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..0780a34e98 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1346,6 +1346,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + dom::after_command(host, &id); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..f62236f90f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_variables; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs new file mode 100644 index 0000000000..e60afb03d2 --- /dev/null +++ b/crates/engine/src/tests/script_variables.rs @@ -0,0 +1,433 @@ +//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the +//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::tests_links::{Folder, RED, place, png, write}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A document with a type object and a rectangle. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + (s, t, r) +} + +fn variables(s: &Session) -> Vec<(String, &'static str)> { + s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect() +} + +#[test] +fn variables_collection_adds_finds_renames_and_removes() { + let (mut s, _, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var v = app.activeDocument.variables; + vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename); + var a = v.add(), b = v.add(); + vc.log([a.name, b.name, a.kind, v.length].join()); + b.name = 'title'; b.kind = VariableKind.VISIBILITY; + vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join()); + vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined); + a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#, + ); + assert_eq!( + out, + vec![ + json!(0), + json!("Variables"), + json!("Document"), + json!("Variable1,Variable2,VariableKind.TEXTUAL,2"), + json!("title,VariableKind.VISIBILITY,title,Variable1,title"), + json!(true), + json!(1), + json!("Document,Variable") + ] + ); + assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index")); +} + +#[test] +fn variable_names_and_kinds_are_checked_before_anything_changes() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown")); + let long = "x".repeat(5000); + assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long")); + // Setting what the variable already has runs no command. + log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;"); + assert_eq!(undo_steps(&s), before); + assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]); +} + +#[test] +fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var v = app.activeDocument.variables.add();\ + vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\ + v.name;", + ); + assert!(e.contains("Stale variable"), "{e}"); + // A failed run keeps nothing, so the variable is defined outside the script. + s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap(); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;"); + assert!(e.contains("Stale variable"), "{e}"); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;"); + assert!(e.contains("Stale variable"), "{e}"); + // A rename through the object keeps it. + assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap(); + let e = failure(&mut s, "#targetengine keepvars\nheld.name;"); + assert!(e.contains("Stale variable"), "{e}"); +} + +#[test] +fn collections_from_an_earlier_run_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap(); + for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] { + let e = failure(&mut s, &format!("#targetengine keepcols\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn content_and_visibility_variables_bind_one_variable_per_slot() { + let (mut s, t, r) = doc(); + for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1]; + vc.log(t.contentVariable === null && t.visibilityVariable === null); + t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other'); + r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide'); + vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name); + vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename); + vc.log(r.contentVariable === undefined);"#, + ); + assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["other".to_string()])); + assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::>()), Some(vec!["hide".to_string()])); + assert_eq!(undo_steps(&s), before + 1); + // A variable of another kind is refused, and nothing changes; null unbinds that slot only. + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');"); + assert!(e.contains("visibility variable"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');"); + assert!(e.contains("text variable"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null")); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["show".to_string()])); + // Assigning the binding the object already has runs no command. + let steps = undo_steps(&s); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn an_embedded_image_cannot_take_an_image_variable() { + let dir = Folder::new("script-vars-embedded"); + let path = dir.file("red.png"); + write(&path, &png(10, 10, RED)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = place(&mut s, &path); + s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);"); + assert_eq!(out, vec![json!("photo")]); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); + assert!(e.contains("embedded image"), "{e}"); + assert!(s.active().unwrap().doc.variables.bindings.is_empty()); +} + +#[test] +fn data_sets_capture_display_update_and_remove() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, sets = d.dataSets; + vc.log(sets.length + ',' + (d.activeDataset === null)); + var one = sets.add(); + vc.run('text.setText', {id: TEXT_ID, text: 'World'}); + var two = sets.add(); + vc.log([one.name, two.name, sets.length, d.activeDataset.name].join()); + one.display(); vc.log(d.activeDataset.name); + vc.run('text.setText', {id: TEXT_ID, text: 'Again'}); + two.update(); vc.log(d.activeDataset.name); + two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name); + d.activeDataset = two; vc.log(d.activeDataset.name); + one.remove(); vc.log(sets.length);"# + .replace("TEXT_ID", &t.0.to_string()) + .as_str(), + ); + assert_eq!( + out, + vec![ + json!("0,true"), + json!("Data Set 1,Data Set 2,2,Data Set 2"), + json!("Data Set 1"), + json!("Data Set 1"), + json!("Second,Second"), + json!("Second"), + json!(1) + ] + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.datasets.len(), 1); + assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("Second")); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); + log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();"); + assert!(s.active().unwrap().doc.variables.datasets.is_empty()); + assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset")); +} + +#[test] +fn update_of_a_data_set_that_holds_the_art_runs_no_command() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap(); + assert_eq!(undo_steps(&s), before); + assert_eq!(r["slowestCommands"], json!([]), "{r}"); +} + +#[test] +fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn variables_locked_refuses_new_variables_but_not_bindings() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\ + d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);", + ); + assert_eq!(out, vec![json!(false), json!(true)]); + assert!(s.active().unwrap().doc.variables.locked); + let e = failure(&mut s, "app.activeDocument.variables.add();"); + assert!(e.contains("locked"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false")); + assert_eq!(variables(&s).len(), 1); +} + +/// A variable library of two variables and two data sets, written for these tests from the elements +/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of +/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements +/// with `dataSetName`. +const LIBRARY: &str = r#" + + + + + + + + <p>Hello</p>true + <p>World</p>false + + + +"#; + +/// A fresh folder with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// Runs `main/main.jsx` in `base` with `text`, on `s`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +#[test] +fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() { + let base = folder("import"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let r = run_file( + &mut s, + &base, + "var d = app.activeDocument; d.importVariables(new File('lib.xml'));\ + vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\ + d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!(["2,2,Two", "title"])); + assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]); + assert_eq!(s.active().unwrap().doc.story_text(t), "World"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn import_variables_takes_only_a_file_the_script_may_read() { + let base = folder("import-refused"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + std::fs::write(base.join("outside.xml"), LIBRARY).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string(); + assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File")); + assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File")); + let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/"); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));")); + assert!(e.contains("access denied"), "{e}"); + // The open document's own file is refused, though the script's commands may open it. + let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/"))); + assert!(e.contains("access denied"), "{e}"); + // A plain object cannot pass for a File. + let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);"); + assert!(e.contains("not plain data"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn import_variables_refuses_hostile_libraries_before_any_edit() { + let base = folder("import-hostile"); + let external = r#"]>"#; + std::fs::write(base.join("main/external.xml"), external).unwrap(); + let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + std::fs::write(base.join("main/deep.xml"), deep).unwrap(); + let mut big = LIBRARY.as_bytes().to_vec(); + big.resize((8 << 20) + 1, b' '); + std::fs::write(base.join("main/big.xml"), big).unwrap(); + let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\""); + std::fs::write(base.join("main/twice.xml"), twice).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] { + let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string(); + assert!(e.contains(says), "{file}: {e}"); + } + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); + assert_eq!(undo_steps(&s), before); + // Locked variables refuse a library that would delete or define one. + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn export_variables_writes_a_library_that_import_reads_back() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\ + d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\ + d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);", + ); + let xml = out[0].as_str().unwrap(); + for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "

Hello

"] { + assert!(xml.contains(part), "{part} in {xml}"); + } + assert_eq!(out[1], json!("title,Row")); +} + +#[test] +fn export_variables_writes_only_where_the_script_may_write() { + let base = folder("export-refused"); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + // The open document's own file is refused, though the script's commands may save it. + let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let before = std::fs::read(&saved).unwrap(); + let path = saved.replace('\\', "/"); + let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert_eq!(std::fs::read(&saved).unwrap(), before); + // The script's own folder is only read. + let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert!(!base.join("main/out.xml").exists()); + assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File")); + // A library that cannot be written leaves no file. + s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap(); + let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));"); + assert!(e.contains("can't be saved"), "{e}"); + let out = + log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);"); + assert_eq!(out, vec![json!(false)]); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..59f385cabb 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose +/// path is in its own slot. `None` for anything else, a `Folder` included. +pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { + let Some(c) = &i.files else { return Ok(None) }; + if i.object(id)?.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match slot(i, id, PATH)? { + Value::String(s) => Some(s.to_rust_string()), + _ => None, + }) +} + fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..26ab1e14ed 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -190,8 +190,8 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, - /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object - /// that has [`crate::HOST_REF_KEY`] is refused. + /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under + /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. hosted: bool, } @@ -261,6 +261,12 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + if r.hosted + && let Some(path) = crate::file_classes::file_path(self, id)? + { + self.charge_reading(r, path.len().saturating_add(16))?; + return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))])); + } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => { return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); @@ -313,7 +319,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..4a790957c6 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -110,6 +110,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data { Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) } +/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host +/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d`, an argument of a host class's member, stands for. +pub fn file_ref_path(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + /// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { let Data::Object(items) = d else { return None }; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..e3141d9e0f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -82,7 +82,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..4c92dafa13 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and each document's variables, data sets and variable + libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..2d35d2d0b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,29 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and + `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` + (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` + (https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/) have `length`, `parent`, `[i]`, `index(key)`, + `getByName(name)`, `add()` and `removeAll()`. A `Variable` (https://ai-scripting.docsforadobe.dev/jsobjref/Variable/) + has `name`, `kind`, `pageItems` and `remove()`, and a `Dataset` (https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/) + has `name`, `display()`, `update()` and `remove()`. Every page item has `visibilityVariable`, and a `TextFrame`, + `PlacedItem`, `RasterItem` or `GraphItem` has `contentVariable` as well + (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each change runs a `variable.*` or `dataset.*` command: + `variables.add()` runs `variable.define` of a text variable named `Variable1`, `Variable2` and so on (the first free + name), `dataSets.add()` runs `dataset.capture`, `display()` and assigning `activeDataset` run `dataset.select`, + `update()` runs `dataset.update {name}`, assigning `visibilityVariable` or `contentVariable` runs + `variable.setBinding`, `importVariables` runs `variable.loadLibrary` and `exportVariables` runs + `variable.saveLibrary`. `kind` is one of the strings of the enumeration `VariableKind` + (`"VariableKind.TEXTUAL"`, `VISIBILITY`, `IMAGE`, `GRAPH` and `Unknown`); `Unknown` cannot be assigned. + VectorCraft's own rules: a `Variable` or `Dataset` names its variable or data set by name. A rename made through + it keeps it working; once the name leaves the document any other way (a delete, an undo, a rename or kind change by + another command, or an import that replaces the data sets), it throws `Stale variable` or `Stale data set`, also + after the name comes back. A run gives out at most 10,000 of each. `visibilityVariable` and `contentVariable` give + the first bound variable of their kind in the order the variables were defined, or `null`, and `null` unbinds. + `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or + write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs + no command. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -4267,7 +4290,13 @@ already walks Image Trace. Short agent entry points: defined in. Names compare without regard to case; by object, unbound variables come first and variables bound to several objects last, and ties go by name. Another `by` value, or a `descending` that is not true or false, is an error. The sort is panel state, not saved and not an undo step; `variable.list` lists the variables in - that order and reports it as `sort: {by, descending}`. + that order and reports it as `sort: {by, descending}`. `variable.setBinding {id, slot: visibility|content, + variable?}` binds one object to `variable` for one slot and unbinds the object's other variables of that slot's + kind: `visibility` takes a visibility variable, and `content` the kind that drives the object (text for type, image + for a linked image, graph for a graph). Without `variable`, or with null, it unbinds them all. A variable of + another kind, an object of no content kind, and an embedded image for an image variable are errors, and nothing + changes. One undo step, and none when the object already has just that binding → `{id, slot, variable, + unbound}`. - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / @@ -5038,8 +5067,9 @@ locked; `skipped` counts those objects. A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. -`dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the -data set holds. A variable whose objects report no value, because they are deleted or, for a text, image or graph +`dataset.update {all?, name?}` writes what the bound objects hold now into the active data set, for each variable that +the data set holds. With `name`, it writes into that data set instead and the active data set stays as it is; a +`name` that is not a string, or names no data set, is an error. A variable whose objects report no value, because they are deleted or, for a text, image or graph variable, locked or inside a locked layer or group, or for any variable on a locked artboard, keeps the data set's value. With `all: true` it also adds every other variable that the objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..a760266f23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6db0f6c1adef609bba16c8eec4ce0a37e178d2ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:15:47 -0800 Subject: [PATCH 007/106] Scripts: visibility variables on embedded images, data sets kept after a no-op import - variable.setBinding refuses an embedded image only for an image variable, so a script can bind an embedded image's visibility. - A Dataset object stays usable after dataset.import, variable.loadLibrary or variable.import leaves the document's data sets as they were, or the import is put back; it goes stale only when the data sets change. - script.check reports a document's exportVariables as filesWritten and file.write, and the script host test lists the variable and data set names the host adds. Docs: docs/mcp.md. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/script/dom.rs | 10 +++++++-- crates/engine/src/script/dom/variables.rs | 22 ++++++++++++++----- crates/engine/src/script/mod.rs | 3 ++- crates/engine/src/tests/script_variables.rs | 19 ++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/catalog.rs | 3 +++ crates/scriptcheck/src/tests.rs | 8 +++++++ docs/mcp.md | 7 +++--- 10 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index fdd4231dc3..28022865e6 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -500,7 +500,7 @@ fn set_binding(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); } check_bindable(doc, &[id], kind, C)?; - if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a7303cf4e6..7e46779791 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,9 +42,15 @@ mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + /// After each command a script runs ([`variables::after_command`]). -pub(super) fn after_command(h: &Host, id: &str) { - variables::after_command(h, id); +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); } /// The error for a member read or called with no document open. diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs index 270a7cfc08..d36c9f1f45 100644 --- a/crates/engine/src/script/dom/variables.rs +++ b/crates/engine/src/script/dom/variables.rs @@ -46,7 +46,7 @@ use super::{ Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, }; -use crate::doc::{Node, Variable, VariableKind}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; use crate::file_access::Access; /// The error for a `Variable` whose variable left the document, or that came from an earlier run. @@ -138,16 +138,28 @@ pub(super) struct Handles { seen: RefCell>, } +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + /// After each command a script runs: the objects whose variable or data set it removed stop -/// working, so one made again under the same name does not bring them back. A command that replaces -/// the data sets (an import) stops every `Dataset` of its document. -pub(super) fn after_command(h: &Host, id: &str) { +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { let hs = &h.dom.vars; if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { return; } let Ok(s) = h.session.try_borrow() else { return }; - let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); let changed: HashSet = { let seen = hs.seen.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0780a34e98..39acd9897b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1313,6 +1313,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1346,7 +1347,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } - dom::after_command(host, &id); + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs index e60afb03d2..5ff2301bbf 100644 --- a/crates/engine/src/tests/script_variables.rs +++ b/crates/engine/src/tests/script_variables.rs @@ -188,6 +188,13 @@ fn an_embedded_image_cannot_take_an_image_variable() { let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); assert!(e.contains("embedded image"), "{e}"); assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); } #[test] @@ -259,6 +266,18 @@ fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { assert!(e.contains("Stale data set"), "{e}"); } +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + #[test] fn variables_locked_refuses_new_variables_but_not_bindings() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..4519f35c5e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -70,6 +71,23 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + // Variables and data sets. `importVariables` reads the library file it is given. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("PageItem.prototype.", "visibilityVariable visibilityVariable="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..eef0fb77c1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -301,7 +301,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..940b1db4e0 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -72,6 +72,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..1f4c9f3e70 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,14 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 2d35d2d0b9..7d454966ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,9 +2558,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, - `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, - `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `exportVariables`), + `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), + `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` + (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper From ee7576975ed005cac23c428c3de33ec47cb55050 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:10:19 -0800 Subject: [PATCH 008/106] Scripts: the script check counts exportVariables named in brackets as a file write doc['exportVariables'](f) now reports file.write and filesWritten on its line, as the dot form does. Reading the method without calling it reports nothing. --- crates/scriptcheck/src/analyze/features.rs | 10 ++++++++++ crates/scriptcheck/src/tests.rs | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index eef0fb77c1..b7630e064b 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -287,6 +287,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1f4c9f3e70..785ebf6c62 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -538,6 +538,21 @@ fn export_variables_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); } +/// `exportVariables` called with its name as a string literal in brackets writes the file too; +/// reading the method without calling it does not. +#[test] +fn export_variables_in_brackets_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['importVariables'](f);\n", + "app.activeDocument[\"exportVariables\"](f);\n", + "var d = app.activeDocument; d['exportVariables'] (f);\n", + "var n = d['exportVariables'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From e67211f07036a29014aeec2e27179b7488d416ab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:17:06 -0800 Subject: [PATCH 009/106] Fix #8583: document tab titles draw in a condensed face, so more tabs fit Desktop builds with a craft-fonts checkout that has Noto Sans Condensed SemiBold in its opt-in Latin catalog (fonts/latin-manifest.txt) embed that one face as vectorcraft_text::CONDENSED_UI_FONT. Tab titles draw in a new theme::FONT_TAB family headed by it, scaled to the x-height of the interface's semibold face, with the semibold faces after it on its baseline. In a 1280 pt window, 9 tabs named "Poster draft N" fit whole instead of 8. Without CRAFT_FONTS_DIR, on the web, or with a checkout that lacks the row (a build warning), FONT_TAB is the semibold family and tabs look as before. The tab tests that count tabs measure in the semibold face. --- crates/text/build.rs | 71 +++++++++++++++++++----- crates/text/src/craft_fonts.rs | 3 + crates/text/src/lib.rs | 11 +++- crates/ui-egui/src/chrome/tabs.rs | 9 +-- crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/tests/tab_overflow.rs | 41 +++++++++++++- crates/ui-egui/src/theme.rs | 53 +++++++++++++++++- crates/ui-egui/src/ui_fonts.rs | 2 +- docs/development.md | 6 ++ docs/ui-parity.md | 1 + 10 files changed, 171 insertions(+), 27 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 5402ddbe07..5979c6557c 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -12,6 +12,10 @@ //! `fonts//` beside the wasm instead of embedding (`cargo xtask web-fonts` copies them //! there; `apps/vectorcraft-web/src/fonts.rs` fetches them). A list line the manifest lacks is left //! out with a warning, never an error, and never costs the desktop its fonts. +//! +//! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in +//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A +//! checkout without that row leaves it `None` with a warning, never an error. use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -25,7 +29,7 @@ fn main() { println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); - let (mut fonts, mut web) = (String::new(), String::new()); + let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { let dir = from_workspace(dir); match craft_fonts(&dir) { @@ -48,8 +52,16 @@ fn main() { Err(e) if required => println!("cargo::error=web-fonts.txt: {e}"), Err(e) => println!("cargo::warning=web build fetches no craft fonts: web-fonts.txt: {e}"), } + if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { + match condensed_ui_font(&dir) { + Ok(entry) => condensed = format!("Some({entry})"), + Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + } + } } - let src = format!("pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\n"); + let src = format!( + "pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\npub static CONDENSED_UI_FONT: Option = {condensed};\n" + ); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); // Unchanged output keeps its mtime. Rewritten just before this crate compiles, it can read as // newer than that compile where cargo's recorded times lose their sub-second part (ecryptfs @@ -91,23 +103,52 @@ fn craft_fonts(dir: &Path) -> Result { if wasm && !(*family == WEB_FONT.0 && *style == WEB_FONT.1) { continue; } - let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; - // The manifest is supplier data: embed only regular files inside the checkout. - if !path.starts_with(&root) || !path.is_file() { - return Err(format!("{file}: not a file inside the font checkout")); - } - println!("cargo::rerun-if-changed={}", path.display()); - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); - let _ = writeln!( - out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", - scripts.join(", "), - path.display().to_string(), - ); + let _ = writeln!(out, " {},", craft_font(dir, &root, family, style, file, scripts)?); } Ok(out) } +/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { + let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } + println!("cargo::rerun-if-changed={}", path.display()); + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + Ok(format!( + "CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }}", + scripts.join(", "), + path.display().to_string(), + )) +} + +/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in +/// Latin catalog. +const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. +fn condensed_ui_font(dir: &Path) -> Result { + let manifest = dir.join("fonts/latin-manifest.txt"); + // A checkout without the catalog is watched through its folder, so the build runs again once + // the catalog appears. + let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; + println!("cargo::rerun-if-changed={}", watched.display()); + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; + let row = text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); + let Some([family, style, file, scripts, ..]) = row.as_deref() else { + return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + }; + craft_font(dir, &root, family, style, file, scripts) +} + /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and /// the listed faces the manifest lacks (an older craft-fonts checkout), which are left out. fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 24eef3de40..68ddc548b9 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -3,6 +3,9 @@ //! Built with `CRAFT_FONTS_DIR=`, [`CRAFT_FONTS`] holds every font in its //! manifest (Japanese UI and document fonts, Arabic fonts and Noto Sans Thai); built without it, //! it is empty and that text falls back to the installed system fonts. Release builds always set it. See `build.rs`. +//! [`CONDENSED_UI_FONT`] is the condensed face document tab titles draw in, from the checkout's +//! opt-in Latin catalog: `None` on wasm32, without `CRAFT_FONTS_DIR`, or with a checkout that +//! lacks it. /// A font from the optional craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`). pub struct CraftFont { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..2028639af4 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -37,7 +37,7 @@ pub mod thread; pub use bitmap::GlyphImage; pub use context_alternates::{ContextAlternate, ContextAlternates, alternate_changes, alternates_in_context, is_alternate_feature}; -pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; +pub use craft_fonts::{CONDENSED_UI_FONT, CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; @@ -1059,6 +1059,15 @@ pub fn line_metrics(data: &[u8], index: u32) -> Option<(f32, f32, f32, f32)> { Some((f32::from(m.units_per_em.max(1)), m.ascent, m.descent, m.leading)) } +/// The x-height of the font at `index` of `data`, at its default axis settings, in ems. `None` if +/// the font can't be read or gives no x-height. +pub fn x_height(data: &[u8], index: u32) -> Option { + use skrifa::MetadataProvider; + let f = skrifa::FontRef::from_index(data, index).ok()?; + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..1aff4fe1a9 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -190,7 +190,8 @@ fn tab_close_box(ui: &Ui, t: &Tokens, xr: egui::Rect, w: f32, id: egui::Id) -> O /// (#746). The first tab that doesn't fit whole fills the room left before the » button with its /// title shortened, when that room holds some of the title (#8584). When the active tab is among /// the last ones and the tabs from it to the end leave room, the tab before them fills that room -/// instead. An active tab wider than the whole strip is shortened to it. +/// instead. An active tab wider than the whole strip is shortened to it. Titles draw in +/// [`theme::FONT_TAB`], a condensed face in builds with craft-fonts (#8583). /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] @@ -224,7 +225,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::semibold(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); (w, text, title, galley) }) .collect(); @@ -258,7 +259,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::semibold(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..7954785e30 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1498,6 +1498,7 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_UI.into()), egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), + egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index 59af211e17..c9f9edec0a 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -44,6 +44,12 @@ fn frame_sized(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, texts } +/// The interface fonts with tab titles in the semibold face, as in a build without craft-fonts' +/// condensed face: the tab counts below are measured in it. +fn install_semibold_tab_fonts(ctx: &egui::Context) { + ctx.set_fonts(crate::theme::interface_fonts_with(None)); +} + fn click(at: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } } @@ -61,7 +67,7 @@ fn the_tab_that_does_not_fit_whole_fills_the_rest_of_the_strip() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -100,7 +106,7 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -118,6 +124,35 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { assert!(texts.iter().any(|(t, _)| t == "Tab test 2 @ 100 % (RGB/Preview)"), "the tooltip shows the whole title: {texts:?}"); } +/// With craft-fonts' condensed face, tab titles draw in it at the semibold face's x-height, and +/// more tabs fit whole in the strip of a 1280 pt window than with the semibold face (#8583). +#[test] +fn tab_titles_in_the_condensed_face_fit_more_tabs() { + let Some(condensed) = vectorcraft_text::CONDENSED_UI_FONT.as_ref() else { + eprintln!("skipped: built without craft-fonts' condensed face (set CRAFT_FONTS_DIR to a craft-fonts checkout that has it)"); + return; + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..24 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Poster draft {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + let mut whole_tabs = |face: Option<&vectorcraft_text::CraftFont>| { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(face)); + let texts = frame_sized(&mut app, &ctx, egui::vec2(1280.0, 700.0), 0.0, vec![]); + let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); + // The height of an x, in the tab font and in semibold text. + let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; + (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + }; + let (semibold, _, _) = whole_tabs(None); + let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); + assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); + assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + /// With the last document active, the tabs from it to the end leave room before the » button, and /// the tab before them fills that room with its title shortened instead of the strip ending short /// of the » button (#8584). @@ -132,7 +167,7 @@ fn with_the_last_document_active_the_tab_before_the_shown_ones_fills_the_room() app.session.set_active(7); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f539ddbe71..11e8af8e22 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -494,16 +494,29 @@ pub fn strong_selected_text(ui: &mut egui::Ui) { pub const FONT_UI: &str = "ui"; pub const FONT_UI_SEMIBOLD: &str = "ui-semibold"; pub const FONT_MONO: &str = "mono"; +/// The family document tab titles draw in. In a build with craft-fonts' condensed face +/// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the +/// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so +/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } +/// A document tab's title font ([`FONT_TAB`]). +pub fn tab_font(size: f32) -> FontId { + FontId::new(size, FontFamily::Name(FONT_TAB.into())) +} +/// Whether `family` draws semibold text and takes the bold fallback faces. +pub(crate) fn is_semibold(family: &FontFamily) -> bool { + matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) +} pub fn mono(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_MONO.into())) } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -520,6 +533,11 @@ pub fn install_fonts(ctx: &egui::Context) { /// whether egui applied them at once or deferred them to the next pass (it must not take input /// or draw with fallback metrics while they are pending). pub fn interface_fonts() -> FontDefinitions { + interface_fonts_with(vectorcraft_text::CONDENSED_UI_FONT.as_ref()) +} + +/// [`interface_fonts`] with `condensed` as the face that heads [`FONT_TAB`]. +pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFont>) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let (ui, semi, mono) = interface_faces(&mut fonts); let stack = |fonts: &FontDefinitions, family: FontFamily| fonts.families.get(&family).cloned().unwrap_or_default(); @@ -529,13 +547,42 @@ pub fn interface_fonts() -> FontDefinitions { let family = |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); - fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), family(semi, &fallback)); + let semi = family(semi, &fallback); + let tab = tab_faces(&mut fonts, &semi, condensed); + fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); fonts } +/// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first +/// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its +/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { + let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); + let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; + let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let name = craft_font_name(f); + let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); + // `baseline_copies` reads the head of each family it is given: here only this one. + let mut row = FontDefinitions::empty(); + row.font_data.insert(name.clone(), Arc::new(head.clone())); + row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + let mut faces = vec![name.clone()]; + for face in semi { + let Some(data) = fonts.font_data.get(face).cloned() else { continue }; + for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + fonts.font_data.insert(copy.clone(), Arc::new(data)); + faces.push(copy); + } + } + fonts.font_data.insert(name, Arc::new(head)); + faces +} + /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace /// faces that head their families, in order. #[cfg(feature = "interface-fonts")] @@ -587,7 +634,7 @@ fn add_craft_fonts(fonts: &mut FontDefinitions) { } } for (family, stack) in fonts.families.iter_mut() { - let bold = *family == FontFamily::Name(FONT_UI_SEMIBOLD.into()); + let bold = is_semibold(family); let copy = |f: &vectorcraft_text::CraftFont| { let name = craft_font_name(f); copies.get(&(family.clone(), name.clone())).cloned().unwrap_or(name) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 73c1a30891..cb419067e1 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -454,7 +454,7 @@ mod tests { let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, egui::Color32::WHITE)).rows[0].glyphs.clone(); for family in families { - let semibold = family == FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()); + let semibold = crate::theme::is_semibold(&family); for &(regular, bold, c) in &probes { let face = if semibold { bold } else { regular }; for size in [13.0_f32, 24.0, 40.0] { diff --git a/docs/development.md b/docs/development.md index fb30fad2bb..66f925324e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -174,6 +174,12 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- Noto Sans Georgian for the Georgian interface), after the UI fonts and before the installed fonts `ui_fonts.rs` discovers for other scripts. On the web, Noto Sans Georgian is fetched at startup and reaches the UI through `ui_fonts.rs`. +- Document tab titles: on desktop builds, `crates/text/build.rs` also reads one row of the + checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as + `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the + x-height of the interface's semibold face, so more tabs fit in the strip. Without + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab + titles draw in the semibold face. - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..8b5a9f315a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,6 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From b19d017c317132873d2f69fd9961dec383f4e3f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:46:20 -0800 Subject: [PATCH 010/106] JavaScript: Map, Set, WeakMap, WeakSet and typed arrays in ES2015 realms A realm with Options::es2015 now has Map, Set, WeakMap and WeakSet, and ArrayBuffer, DataView and the nine typed arrays from Int8Array to Float64Array with %TypedArray%.from, of and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2). A realm without the option, the ExtendScript realm included, has none of these names. - Map and Set compare keys with SameValueZero and keep insertion order. forEach and iterators skip entries deleted before they reach them and visit entries added during the walk; the collector removes holes and moves live iterators. - WeakMap and WeakSet hold their keys weakly. The collector marks a WeakMap value only once its key is reachable another way and drops the entries of unreachable keys, also when a value refers to its key. - Typed arrays store elements little-endian; DataView is big-endian unless littleEndian is true. Numeric property names are elements or nothing, with the element descriptors of later editions. Copies to the same element type keep every bit. - An ArrayBuffer longer than 2^32 - 1 bytes or than the heap limit is a RangeError before anything is allocated, and every element a method visits takes fuel. - Until the language has iterators, the collection constructors and %TypedArray%.from read an array, a string by code point or an object with a length, by index. A typed array constructor reads an array or an object with a length the same way, and converts a first argument that is not an object to a length. - The %TypedArray%.prototype methods that share an Array method use the element count, and an Array method called on a typed array reads its length property. Array methods visit every element of a typed array longer than 4,096. - Check Script counts new of these constructors as the language's. test262 runs the Map, Set, WeakMap, WeakSet, ArrayBuffer, DataView, TypedArray and TypedArrayConstructors folders in ES2015 realms. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/array.rs | 39 +- crates/js/src/builtins/binary.rs | 1143 +++++++++++++++++++++++++ crates/js/src/builtins/collections.rs | 696 +++++++++++++++ crates/js/src/collections_tests.rs | 412 +++++++++ crates/js/src/heap.rs | 328 ++++++- crates/js/src/interp.rs | 52 +- crates/js/src/lib.rs | 20 +- crates/js/tests/test262.rs | 114 ++- crates/scriptcheck/src/catalog.rs | 20 +- crates/scriptcheck/src/tests.rs | 11 + docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 13 files changed, 2832 insertions(+), 29 deletions(-) create mode 100644 crates/js/src/builtins/binary.rs create mode 100644 crates/js/src/builtins/collections.rs create mode 100644 crates/js/src/collections_tests.rs diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..6c2eff73ca 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,13 +3,16 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Map`, `Set`, `WeakMap` and +//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can //! run past [`crate::Limits`]. mod array; +pub(crate) mod binary; +pub(crate) mod collections; pub(crate) mod extensions; mod global; mod json; @@ -145,6 +148,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + collections::install(interp)?; + binary::install(interp)?; + } Ok(()) } @@ -165,8 +172,16 @@ fn key_of(n: f64) -> Key { number_to_str(n).flat() } -/// ToUint32 of an object's `length`. +/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array +/// method it shares, the typed array's length is its element count, whatever its `length` +/// property says (ECMA-262 6.0 section 22.2.3). fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + if interp.typed_length == Some(o) { + interp.typed_length = None; + if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) { + return Ok(u32::try_from(view.length).unwrap_or(u32::MAX)); + } + } let len = interp.get_from(o, &key("length"), &Value::Object(o))?; Ok(to_uint32(interp.to_number(&len)?)) } diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..1c91d602b0 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option { Some(n) } -/// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. +/// The indices a String object or a typed array holds without properties for them. +fn index_count(class: &Class) -> usize { + match class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + } +} + +/// The objects of the prototype chain from `obj`, with how many properties (and String object or +/// typed array indices) each holds. fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { let Some(o) = interp.heap.object(id) else { break }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - out.push((id, o.props.len().saturating_add(string_len))); + out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } out @@ -141,8 +149,7 @@ impl Indices { } interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?; let Some(o) = interp.heap.object(id) else { continue }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); + let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); for p in present { for map in &self.maps { let p = p as i64; @@ -335,13 +342,13 @@ fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { } /// `Array.prototype.join` (section 15.4.4.5). -fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let separator = arg(args, 0); with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item)) } /// `Array.prototype.toLocaleString` (section 15.4.4.3). -fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { +pub(super) fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } @@ -413,7 +420,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { +pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let middle = len / 2; @@ -692,7 +699,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js // ---- searching ---- /// `Array.prototype.indexOf` (section 15.4.4.14). -fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -717,7 +724,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu } /// `Array.prototype.lastIndexOf` (section 15.4.4.15). -fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -794,15 +801,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe }) } -fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Every) } -fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Some) } -fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Visit) } @@ -852,10 +859,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu }) } -fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, false) } -fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, true) } diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs new file mode 100644 index 0000000000..8c10723a74 --- /dev/null +++ b/crates/js/src/builtins/binary.rs @@ -0,0 +1,1143 @@ +//! `ArrayBuffer`, `DataView` and the typed arrays (ECMA-262 6.0 sections 24.1, 24.2 and 22.2): +//! `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, +//! `Uint32Array`, `Float32Array` and `Float64Array`, with `%TypedArray%` and its prototype's +//! methods. A realm has them with [`crate::Options::es2015`]. +//! +//! A buffer's bytes are zero when it is made and never change length; no operation detaches +//! one. Views share their buffer's bytes. Typed arrays store their elements little-endian on +//! every platform, and a `DataView` reads and writes big-endian unless `littleEndian` is true. +//! A typed array's numeric property names are its elements or nothing (section 9.4.5, with the +//! element descriptors of later editions: writable, enumerable and configurable, and an element +//! that cannot be deleted); [`crate::interp::Interp`] calls [`element`], [`set_element`] and +//! [`define_element`] for them. +//! +//! A buffer longer than the realm's heap limit, or than 2^32 - 1 bytes, is a `RangeError`, and +//! every buffer's bytes are checked against the heap before they are allocated. Every element +//! a method visits takes a unit of fuel, and a sort's comparisons take one each. +//! +//! The language has no iterators yet, so constructing from an object and `%TypedArray%.from` +//! read an array, a string (by code point) or an object with a `length`, by index. + +use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, require_callable, to_integer}; +use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; +use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; + +/// The longest buffer, in bytes. +const MAX_BUFFER: u64 = u32::MAX as u64; + +/// The bytes each item a method gathers before it writes them is charged. +const ITEM_BYTES: usize = 16; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + install_array_buffer(interp)?; + install_data_view(interp)?; + install_typed_arrays(interp) +} + +fn install_array_buffer(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.array_buffer_proto = proto; + let ctor = native(interp, "ArrayBuffer", array_buffer_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "ArrayBuffer", ctor, proto)?; + method(interp, ctor, "isView", is_view, 1)?; + getter(interp, proto, "get byteLength", buffer_byte_length)?; + method(interp, proto, "slice", buffer_slice, 2) +} + +fn install_data_view(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.data_view_proto = proto; + let ctor = native(interp, "DataView", data_view_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "DataView", ctor, proto)?; + getter(interp, proto, "get buffer", view_buffer)?; + getter(interp, proto, "get byteLength", view_byte_length)?; + getter(interp, proto, "get byteOffset", view_byte_offset)?; + let methods: [(&'static str, NativeFn, u32); 16] = [ + ("getInt8", get_int8, 1), + ("getUint8", get_uint8, 1), + ("getInt16", get_int16, 1), + ("getUint16", get_uint16, 1), + ("getInt32", get_int32, 1), + ("getUint32", get_uint32, 1), + ("getFloat32", get_float32, 1), + ("getFloat64", get_float64, 1), + ("setInt8", set_int8, 2), + ("setUint8", set_uint8, 2), + ("setInt16", set_int16, 2), + ("setUint16", set_uint16, 2), + ("setInt32", set_int32, 2), + ("setUint32", set_uint32, 2), + ("setFloat32", set_float32, 2), + ("setFloat64", set_float64, 2), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + Ok(()) +} + +fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.typed_array_proto = proto; + let ctor = native(interp, "TypedArray", abstract_ctor, 0, NativeKind::Plain, true)?; + interp.intrinsics.es2015.typed_array_ctor = ctor; + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + data(interp, proto, "constructor", Value::Object(ctor), HIDDEN)?; + method(interp, ctor, "from", typed_from, 1)?; + method(interp, ctor, "of", typed_of, 0)?; + for (name, f) in + [("get buffer", ta_buffer as NativeFn), ("get byteLength", ta_byte_length), ("get byteOffset", ta_byte_offset), ("get length", ta_length)] + { + getter(interp, proto, name, f)?; + } + let methods: [(&'static str, NativeFn, u32); 23] = [ + ("copyWithin", copy_within, 2), + ("entries", ta_entries, 0), + ("every", ta_every, 1), + ("fill", fill, 1), + ("filter", filter, 1), + ("find", find, 1), + ("findIndex", find_index, 1), + ("forEach", ta_for_each, 1), + ("indexOf", ta_index_of, 1), + ("join", ta_join, 1), + ("keys", ta_keys, 0), + ("lastIndexOf", ta_last_index_of, 1), + ("map", map, 1), + ("reduce", ta_reduce, 1), + ("reduceRight", ta_reduce_right, 1), + ("reverse", ta_reverse, 0), + ("set", set, 1), + ("slice", slice, 2), + ("some", ta_some, 1), + ("sort", sort, 1), + ("subarray", subarray, 2), + ("toLocaleString", ta_to_locale_string, 0), + ("values", ta_values, 0), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). + let array_proto = interp.intrinsics.array_proto; + let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; + interp.define(proto, key("toString"), crate::heap::Prop::Data { value: to_string, flags: HIDDEN })?; + + let ctors: [NativeFn; 9] = + [int8_ctor, uint8_ctor, uint8_clamped_ctor, int16_ctor, uint16_ctor, int32_ctor, uint32_ctor, float32_ctor, float64_ctor]; + for (elem, f) in Elem::ALL.into_iter().zip(ctors) { + let sub_proto = new_proto(interp, proto); + let sub = native(interp, elem.name(), f, 3, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(sub) { + o.proto = Some(ctor); + } + super::constructor(interp, elem.name(), sub, sub_proto)?; + #[allow(clippy::cast_precision_loss)] + let size = Value::Number(elem.size() as f64); + data(interp, sub, "BYTES_PER_ELEMENT", size.clone(), 0)?; + data(interp, sub_proto, "BYTES_PER_ELEMENT", size, 0)?; + if let Some(slot) = interp.intrinsics.es2015.typed_ctors.get_mut(elem.index()) { + *slot = sub; + } + if let Some(slot) = interp.intrinsics.es2015.typed_protos.get_mut(elem.index()) { + *slot = sub_proto; + } + } + Ok(()) +} + +// ---- elements ---- + +/// CanonicalNumericIndexString (section 7.1.16): the number a property name stands for when it +/// is the canonical text of that number, `-0` included. +pub(crate) fn canonical_index(k: &[u16]) -> Option { + if let Some(i) = array_index(k) { + return Some(f64::from(i)); + } + let first = *k.first()?; + if !(u16::from(b'0')..=u16::from(b'9')).contains(&first) && !b"-IN".iter().any(|c| u16::from(*c) == first) { + return None; + } + if k == [u16::from(b'-'), u16::from(b'0')] { + return Some(-0.0); + } + let n = string_to_number(k); + (*number_to_str(n).flat() == *k).then_some(n) +} + +/// The position of the element `n` names in a typed array of `length` elements, if it names one. +fn valid_index(n: f64, length: usize) -> Option { + if n.fract() != 0.0 || (n == 0.0 && n.is_sign_negative()) || n < 0.0 || !n.is_finite() { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = n as usize; + (i < length).then_some(i) +} + +/// The buffer's bytes. +fn bytes(interp: &Interp, buffer: ObjId) -> Option<&[u8]> { + match &interp.heap.object(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +fn bytes_mut(interp: &mut Interp, buffer: ObjId) -> Option<&mut [u8]> { + match &mut interp.heap.object_mut(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +/// Reads a value of `elem` from the start of `b` (GetValueFromBuffer, section 24.1.1.5). +fn decode(b: &[u8], elem: Elem, little: bool) -> Option { + let size = elem.size(); + let raw = b.get(..size)?; + let mut bits = 0u64; + for j in 0..size { + let byte = if little { raw.get(j) } else { raw.get(size - 1 - j) }; + bits |= u64::from(*byte?) << (8 * j); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Some(match elem { + Elem::Int8 => f64::from(bits as u8 as i8), + Elem::Uint8 | Elem::Uint8Clamped => f64::from(bits as u8), + Elem::Int16 => f64::from(bits as u16 as i16), + Elem::Uint16 => f64::from(bits as u16), + Elem::Int32 => f64::from(bits as u32 as i32), + Elem::Uint32 => f64::from(bits as u32), + Elem::Float32 => f64::from(f32::from_bits(bits as u32)), + Elem::Float64 => f64::from_bits(bits), + }) +} + +/// ToUint8Clamp (section 7.1.11): rounds to the nearest integer in 0 to 255, ties to even. +pub(crate) fn to_uint8_clamp(n: f64) -> u8 { + if n.is_nan() || n <= 0.0 { + return 0; + } + if n >= 255.0 { + return 255; + } + let f = n.floor(); + let r = if f + 0.5 < n { + f + 1.0 + } else if n < f + 0.5 || f % 2.0 == 0.0 { + f + } else { + f + 1.0 + }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = r as u8; + byte +} + +/// Writes `n` as a value of `elem` at the start of `b` (SetValueInBuffer, section 24.1.1.6). +/// The integer types keep the low bits of ToUint32, which equal those of ToInt8, ToInt16 and +/// ToInt32. +fn encode(b: &mut [u8], elem: Elem, n: f64, little: bool) { + let size = elem.size(); + let bits = match elem { + Elem::Uint8Clamped => u64::from(to_uint8_clamp(n)), + #[allow(clippy::cast_possible_truncation)] + Elem::Float32 => u64::from((n as f32).to_bits()), + Elem::Float64 => n.to_bits(), + _ => u64::from(to_uint32(n)), + }; + for j in 0..size { + let slot = if little { b.get_mut(j) } else { b.get_mut(size - 1 - j) }; + if let Some(slot) = slot { + #[allow(clippy::cast_possible_truncation)] + let byte = (bits >> (8 * j)) as u8; + *slot = byte; + } + } +} + +/// The element of `view` at the index `n`, or `None` when `n` names no element. +pub(crate) fn element(interp: &Interp, view: &View, n: f64) -> Option { + let i = valid_index(n, view.length)?; + let at = view.offset.checked_add(i.checked_mul(view.elem.size())?)?; + decode(bytes(interp, view.buffer)?.get(at..)?, view.elem, true) +} + +/// The view of the typed array `id`. +fn view_of(interp: &Interp, id: ObjId) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(view) => Some(**view), + _ => None, + } +} + +/// Writes `n` to the element at position `i` of `view`, when there is one. +fn write(interp: &mut Interp, view: &View, i: usize, n: f64) { + let Some(at) = i.checked_mul(view.elem.size()).and_then(|o| o.checked_add(view.offset)) else { return }; + if i < view.length + && let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) + { + encode(b, view.elem, n, true); + } +} + +/// Copies `count` elements of `src` from position `from` to `dst` at position `to` byte for byte, as +/// a typed array is copied to one of the same element type (sections 22.2.3.22.2, 22.2.3.23 and +/// 22.2.4.3), so every bit pattern, a NaN's included, is kept. Overlapping ranges of one buffer copy +/// correctly. Each element takes a unit of fuel. +fn copy_elements(interp: &mut Interp, src: &View, from: usize, dst: &View, to: usize, count: usize) -> JsResult<()> { + for _ in 0..count { + interp.use_fuel()?; + } + let size = src.elem.size(); + let (s, d, n) = (src.offset + from * size, dst.offset + to * size, count * size); + if src.buffer == dst.buffer { + if let Some(b) = bytes_mut(interp, src.buffer) + && s + n <= b.len() + && d + n <= b.len() + { + b.copy_within(s..s + n, d); + } + return Ok(()); + } + // The destination's bytes are moved out while the source's are read, so no third copy is made. + let mut out = match &mut interp.object_mut(dst.buffer)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(from_bytes), Some(to_bytes)) = (bytes(interp, src.buffer).and_then(|b| b.get(s..s + n)), out.get_mut(d..d + n)) { + to_bytes.copy_from_slice(from_bytes); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(dst.buffer)?.class { + *b = out; + } + Ok(()) +} + +/// The number a typed array `id`'s numeric property name `k` stands for. +pub(crate) fn typed_key(interp: &Interp, id: ObjId, k: &[u16]) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(_) => canonical_index(k), + _ => None, + } +} + +/// `[[Set]]` of a numeric name of a typed array: the value is converted with ToNumber, then +/// written when the index names an element and ignored otherwise. +pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> JsResult<()> { + let num = interp.to_number(v)?; + if let Some(view) = view_of(interp, id) + && let Some(i) = valid_index(n, view.length) + { + write(interp, &view, i, num); + } + Ok(()) +} + +/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the +/// configurable elements of later editions). +pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let view = view_of(interp, id); + let index = canonical_index(k).zip(view).and_then(|(n, view)| valid_index(n, view.length)); + let refused = + index.is_none() || desc.configurable == Some(false) || desc.enumerable == Some(false) || desc.is_accessor() || desc.writable == Some(false); + if refused { + if throw { + let name = String::from_utf16_lossy(k); + return Err(interp.type_error(&format!("cannot define property '{name}' of a typed array"))); + } + return Ok(false); + } + if let (Some(v), Some(view), Some(i)) = (&desc.value, view, index) { + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(true) +} + +// ---- making buffers and views ---- + +/// ToIndex (section 7.1.17 of later editions): `undefined` is 0, and a negative or too large +/// integer is a `RangeError`. +fn to_index(interp: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(0); + } + let n = to_integer(interp, v)?; + if !(0.0..=9_007_199_254_740_991.0).contains(&n) { + return Err(interp.throw(ErrorType::Range, &format!("{what} must be an integer from 0 to 2^53 - 1"))); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(n as u64) +} + +/// A new zeroed buffer of `len` bytes. A length past [`MAX_BUFFER`] or the heap limit is a +/// `RangeError`; otherwise the bytes and `extra` more are reserved before the buffer is +/// allocated. +fn new_buffer(interp: &mut Interp, len: u64, extra: usize) -> JsResult { + if len > MAX_BUFFER || len > interp.limits.heap_bytes as u64 { + return Err(interp.throw(ErrorType::Range, &format!("an array buffer of {len} bytes is larger than the heap limit allows"))); + } + let len = usize::try_from(len).map_err(|_| interp.throw(ErrorType::Range, "the array buffer is too large"))?; + interp.reserve_heap(OBJECT_BYTES.saturating_add(len).saturating_add(extra))?; + let mut b = Vec::new(); + if b.try_reserve_exact(len).is_err() { + return Err(interp.throw(ErrorType::Range, "the memory for the array buffer could not be allocated")); + } + b.resize(len, 0); + let proto = interp.intrinsics.es2015.array_buffer_proto; + let o = interp.heap.alloc_object(Object::new(Class::ArrayBuffer(b.into_boxed_slice()), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(len); + Ok(o) +} + +/// A new view object of `class` on a buffer that is reachable. Its heap was reserved before. +fn new_view(interp: &mut Interp, class: Class, proto: ObjId) -> ObjId { + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + o +} + +fn typed_proto(interp: &Interp, elem: Elem) -> ObjId { + interp.intrinsics.es2015.typed_protos.get(elem.index()).copied().unwrap_or(interp.intrinsics.es2015.typed_array_proto) +} + +/// A new typed array of `len` zero elements of `elem`, with a new buffer. +fn new_typed(interp: &mut Interp, elem: Elem, len: u64) -> JsResult { + let byte_len = len.saturating_mul(elem.size() as u64); + let buffer = new_buffer(interp, byte_len, OBJECT_BYTES + VIEW_BYTES)?; + let length = usize::try_from(len).unwrap_or(0); + let proto = typed_proto(interp, elem); + Ok(new_view(interp, Class::TypedArray(Box::new(View { buffer, offset: 0, length, elem })), proto)) +} + +/// `new ArrayBuffer(length)` (section 24.1.2.1). +fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("ArrayBuffer must be called with new")); + } + let len = to_index(interp, &arg(args, 0), "the length")?; + new_buffer(interp, len, 0).map(Value::Object) +} + +/// `ArrayBuffer.isView` (section 24.1.3.1). +fn is_view(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let view = + arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::DataView(_) | Class::TypedArray(_))); + Ok(Value::Bool(view)) +} + +fn this_buffer(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if bytes(interp, o).is_some() => Ok(o), + _ => Err(interp.type_error(&format!("ArrayBuffer.prototype.{name} was called on a value that is not an ArrayBuffer"))), + } +} + +fn buffer_len(interp: &Interp, o: ObjId) -> usize { + bytes(interp, o).map_or(0, <[u8]>::len) +} + +fn buffer_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "byteLength")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(buffer_len(interp, o) as f64)) +} + +/// A relative index (as `slice` reads its arguments): negative counts from `len`, and the result +/// is clamped to 0 to `len`. `undefined` gives `default`. +fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(default); + } + let n = to_integer(interp, v)?; + #[allow(clippy::cast_precision_loss)] + let len_f = len as f64; + let r = if n < 0.0 { (len_f + n).max(0.0) } else { n.min(len_f) }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(r as usize) +} + +/// `ArrayBuffer.prototype.slice` (section 24.1.4.3). +fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "slice")?; + let len = buffer_len(interp, o); + let first = relative(interp, &arg(args, 0), len, 0)?; + let last = relative(interp, &arg(args, 1), len, len)?; + let count = last.saturating_sub(first); + // Each copied byte takes a unit of fuel, charged before the copy is made. + for _ in 0..count { + interp.use_fuel()?; + } + let new = interp.rooted(std::slice::from_ref(&this), |i| new_buffer(i, count as u64, 0))?; + // The new buffer's bytes are moved out while the source's are read, so no third copy is made. + let mut dst = match &mut interp.object_mut(new)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(src), Some(to)) = (bytes(interp, o).and_then(|b| b.get(first..first + count)), dst.get_mut(..count)) { + to.copy_from_slice(src); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(new)?.class { + *b = dst; + } + Ok(Value::Object(new)) +} + +// ---- DataView ---- + +/// `new DataView(buffer, byteOffset, byteLength)` (section 24.2.2.1). +fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("DataView must be called with new")); + } + let buffer = match arg(args, 0).as_object() { + Some(o) if bytes(interp, o).is_some() => o, + _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), + }; + let offset = to_index(interp, &arg(args, 1), "the byte offset")?; + let len = buffer_len(interp, buffer) as u64; + if offset > len { + return Err(interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer")); + } + let view_len = match arg(args, 2) { + Value::Undefined => len - offset, + v => to_index(interp, &v, "the byte length")?, + }; + if offset.saturating_add(view_len) > len { + return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = interp.intrinsics.es2015.data_view_proto; + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; + Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) +} + +fn this_data_view(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + if let Some(Class::DataView(view)) = this.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + return Ok(**view); + } + Err(interp.type_error(&format!("DataView.prototype.{name} was called on a value that is not a DataView"))) +} + +fn view_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_data_view(interp, &this, "buffer")?.buffer)) +} + +fn view_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteLength")?.length as f64)) +} + +fn view_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteOffset")?.offset as f64)) +} + +/// The byte position in the buffer of a `DataView` access of `elem` at `index`, or a +/// `RangeError` when it does not fit in the view (sections 24.2.1.1 and 24.2.1.2). +fn view_position(interp: &mut Interp, view: &View, index: u64, elem: Elem) -> JsResult { + let end = index.saturating_add(elem.size() as u64); + if end > view.length as u64 { + return Err(interp.throw(ErrorType::Range, "the offset is outside the bounds of the DataView")); + } + Ok(view.offset + usize::try_from(index).unwrap_or(0)) +} + +/// GetViewValue (section 24.2.1.1). +fn view_get(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let little = arg(args, 1).truthy(); + let at = view_position(interp, &view, index, elem)?; + let n = bytes(interp, view.buffer).and_then(|b| b.get(at..)).and_then(|b| decode(b, elem, little)).unwrap_or(0.0); + Ok(Value::Number(n)) +} + +/// SetViewValue (section 24.2.1.2): the offset, then the value, then `littleEndian` are read +/// before the bounds are checked. +fn view_set(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let n = interp.to_number(&arg(args, 1))?; + let little = arg(args, 2).truthy(); + let at = view_position(interp, &view, index, elem)?; + if let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) { + encode(b, elem, n, little); + } + Ok(Value::Undefined) +} + +macro_rules! view_methods { + ($($get:ident, $set:ident, $elem:ident, $getname:literal, $setname:literal;)*) => { + $( + fn $get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_get(interp, &this, args, Elem::$elem, $getname) + } + + fn $set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_set(interp, &this, args, Elem::$elem, $setname) + } + )* + }; +} + +view_methods! { + get_int8, set_int8, Int8, "getInt8", "setInt8"; + get_uint8, set_uint8, Uint8, "getUint8", "setUint8"; + get_int16, set_int16, Int16, "getInt16", "setInt16"; + get_uint16, set_uint16, Uint16, "getUint16", "setUint16"; + get_int32, set_int32, Int32, "getInt32", "setInt32"; + get_uint32, set_uint32, Uint32, "getUint32", "setUint32"; + get_float32, set_float32, Float32, "getFloat32", "setFloat32"; + get_float64, set_float64, Float64, "getFloat64", "setFloat64"; +} + +// ---- typed array constructors ---- + +/// `%TypedArray%` itself (section 22.2.1.1) cannot be called or constructed. +fn abstract_ctor(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(interp.type_error("TypedArray cannot be called or constructed; use a typed array constructor such as Uint8Array")) +} + +/// `new Int8Array(…)` and the other typed array constructors (section 22.2.4). +fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Elem) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{} must be called with new", elem.name()))); + } + let first = arg(args, 0); + let Value::Object(o) = first else { + let len = to_index(interp, &first, "the length")?; + return new_typed(interp, elem, len).map(Value::Object); + }; + if bytes(interp, o).is_some() { + return typed_on_buffer(interp, o, &arg(args, 1), &arg(args, 2), elem).map(Value::Object); + } + if let Some(src) = view_of(interp, o) { + let ta = new_typed(interp, elem, src.length as u64)?; + let dst = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if src.elem == elem { + copy_elements(interp, &src, 0, &dst, 0, src.length)?; + return Ok(Value::Object(ta)); + } + for i in 0..src.length { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let n = element(interp, &src, i as f64).unwrap_or(0.0); + write(interp, &dst, i, n); + } + return Ok(Value::Object(ta)); + } + let len = length_of(interp, o)?; + let ta = new_typed(interp, elem, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; + Ok(Value::Object(ta)) +} + +/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, +/// each converted with ToNumber. +fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { + let Value::Object(o) = src else { return Ok(()) }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(()) +} + +/// A typed array on part of `buffer` (section 22.2.4.5). +fn typed_on_buffer(interp: &mut Interp, buffer: ObjId, offset: &Value, length: &Value, elem: Elem) -> JsResult { + let size = elem.size() as u64; + let offset = to_index(interp, offset, "the byte offset")?; + if !offset.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the byte offset of a {} must be a multiple of {size}", elem.name()))); + } + let new_length = match length { + Value::Undefined => None, + v => Some(to_index(interp, v, "the length")?), + }; + let buf_len = buffer_len(interp, buffer) as u64; + let byte_len = match new_length { + None => { + if !buf_len.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the buffer's length must be a multiple of {size}"))); + } + buf_len.checked_sub(offset).ok_or_else(|| interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer"))? + } + Some(n) => n.saturating_mul(size), + }; + if offset.saturating_add(byte_len) > buf_len { + return Err(interp.throw(ErrorType::Range, "the typed array does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = typed_proto(interp, elem); + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(byte_len / size).unwrap_or(0), elem }; + Ok(new_view(interp, Class::TypedArray(Box::new(view)), proto)) +} + +macro_rules! typed_ctors { + ($($f:ident, $elem:ident;)*) => { + $( + fn $f(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + typed_ctor(interp, args, constructing, Elem::$elem) + } + )* + }; +} + +typed_ctors! { + int8_ctor, Int8; + uint8_ctor, Uint8; + uint8_clamped_ctor, Uint8Clamped; + int16_ctor, Int16; + uint16_ctor, Uint16; + int32_ctor, Int32; + uint32_ctor, Uint32; + float32_ctor, Float32; + float64_ctor, Float64; +} + +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let ctors = interp.intrinsics.es2015.typed_ctors; + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) +} + +/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). +fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !interp.is_callable(&this) { + return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); + } + let map_fn = arg(args, 1); + let mapping = !matches!(map_fn, Value::Undefined); + if mapping { + require_callable(interp, &map_fn, "the map function")?; + } + let this_arg = arg(args, 2); + let source = arg(args, 0); + if !matches!(source, Value::String(_)) { + // An array-like source: each element is read, mapped and written before the next is read. + let src = interp.to_object(&source)?; + let src_value = Value::Object(src); + let len = length_of(interp, src)?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(Value::Object(ta)) + }); + } + // A string is read by code point first, as an iterable source is, and then mapped. + let mark = interp.temp_roots.len(); + let mut held = crate::interp::HeldBytes::new(interp); + let gathered = for_each_item(interp, &source, false, |interp, item| { + held.add(interp, ITEM_BYTES)?; + interp.temp_roots.push(item); + Ok(()) + }); + let result = gathered.and_then(|()| { + let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; + interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, item) in items.into_iter().enumerate() { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }); + interp.temp_roots.truncate(mark); + drop(held); + result +} + +/// `%TypedArray%.of(...items)` (section 22.2.2.2). +fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(ta)], |interp| { + for (i, v) in args.iter().enumerate() { + interp.use_fuel()?; + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }) +} + +// ---- %TypedArray%.prototype ---- + +/// The typed array a method was called on (ValidateTypedArray, section 22.2.3.5.1). +fn this_typed(interp: &mut Interp, this: &Value, name: &str) -> JsResult<(ObjId, View)> { + if let Some(o) = this.as_object() + && let Some(view) = view_of(interp, o) + { + return Ok((o, view)); + } + Err(interp.type_error(&format!("TypedArray.prototype.{name} was called on a value that is not a typed array"))) +} + +fn ta_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_typed(interp, &this, "buffer")?.1.buffer)) +} + +fn ta_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let view = this_typed(interp, &this, "byteLength")?.1; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number((view.length * view.elem.size()) as f64)) +} + +fn ta_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "byteOffset")?.1.offset as f64)) +} + +fn ta_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "length")?.1.length as f64)) +} + +/// The element at position `i`, 0 past the end. +fn at(interp: &Interp, view: &View, i: usize) -> f64 { + #[allow(clippy::cast_precision_loss)] + element(interp, view, i as f64).unwrap_or(0.0) +} + +/// Runs the array prototype's generic method `f` on a typed array, after checking `this`. +/// The array method reads the typed array's element count as its length, not its `length` +/// property. +fn generic(interp: &mut Interp, this: Value, args: &[Value], name: &str, f: NativeFn) -> JsResult { + let (o, _) = this_typed(interp, &this, name)?; + let saved = interp.typed_length.replace(o); + let result = f(interp, this, args, false); + interp.typed_length = saved; + result +} + +macro_rules! generic_methods { + ($($f:ident, $name:literal, $array:path;)*) => { + $( + fn $f(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + generic(interp, this, args, $name, $array) + } + )* + }; +} + +generic_methods! { + ta_every, "every", array::every; + ta_some, "some", array::some; + ta_for_each, "forEach", array::for_each; + ta_index_of, "indexOf", array::index_of; + ta_last_index_of, "lastIndexOf", array::last_index_of; + ta_join, "join", array::join; + ta_reduce, "reduce", array::reduce; + ta_reduce_right, "reduceRight", array::reduce_right; + ta_reverse, "reverse", array::reverse; + ta_to_locale_string, "toLocaleString", array::to_locale_string; +} + +fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { + let (o, _) = this_typed(interp, this, name)?; + new_iter(interp, o, IterSource::Array, kind, None).map(Value::Object) +} + +fn ta_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Keys, "keys") +} + +fn ta_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Values, "values") +} + +fn ta_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Entries, "entries") +} + +/// `fill(value, start, end)` (section 22.2.3.8): the value is converted once, before the range. +fn fill(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "fill")?; + let n = interp.to_number(&arg(args, 0))?; + let start = relative(interp, &arg(args, 1), view.length, 0)?; + let end = relative(interp, &arg(args, 2), view.length, view.length)?; + for i in start..end { + interp.use_fuel()?; + write(interp, &view, i, n); + } + Ok(this) +} + +/// Calls `f(element, index, array)` for each element in order until `stop` says the result is +/// found; returns the index and the element. +fn search(interp: &mut Interp, this: &Value, args: &[Value], name: &str) -> JsResult> { + let (_, view) = this_typed(interp, this, name)?; + let f = arg(args, 0); + require_callable(interp, &f, "the predicate")?; + let this_arg = arg(args, 1); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + return Ok(Some((i, v))); + } + } + Ok(None) +} + +/// `find` (section 22.2.3.10). +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + Ok(search(interp, &this, args, "find")?.map_or(Value::Undefined, |(_, v)| Value::Number(v))) +} + +/// `findIndex` (section 22.2.3.11). +fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(search(interp, &this, args, "findIndex")?.map_or(-1.0, |(i, _)| i as f64))) +} + +/// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. +fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "map")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let out = new_typed(interp, view.elem, view.length as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(out)], |interp| { + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + let n = interp.to_number(&r)?; + write(interp, &dst, i, n); + } + Ok(Value::Object(out)) + }) +} + +/// A new typed array of `elem` holding `values`. +fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResult { + let out = new_typed(interp, elem, values.len() as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, n) in values.iter().enumerate() { + write(interp, &dst, i, *n); + } + Ok(out) +} + +/// `filter` (section 22.2.3.9). +fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "filter")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let mut held = crate::interp::HeldBytes::new(interp); + let mut kept = Vec::new(); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + held.add(interp, 8)?; + kept.push(v); + } + } + let out = typed_from_values(interp, view.elem, &kept)?; + drop(held); + Ok(Value::Object(out)) +} + +/// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. +fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "slice")?; + let start = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + let count = end.saturating_sub(start); + let out = new_typed(interp, view.elem, count as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + copy_elements(interp, &view, start, &dst, 0, count)?; + Ok(Value::Object(out)) +} + +/// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. +fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "subarray")?; + let begin = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; + let proto = typed_proto(interp, view.elem); + Ok(Value::Object(new_view(interp, Class::TypedArray(Box::new(sub)), proto))) +} + +/// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like +/// object's elements converted with ToNumber, starting at `offset`. A source that does not fit +/// is a `RangeError`. A typed array source is read in full before anything is written, so a +/// source on the same buffer copies correctly. +fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "set")?; + let offset = to_integer(interp, &arg(args, 1))?; + if offset < 0.0 { + return Err(interp.throw(ErrorType::Range, "the offset must not be negative")); + } + let source = arg(args, 0); + let src_view = source.as_object().and_then(|o| view_of(interp, o)); + let src_len = match (&source, src_view) { + (_, Some(v)) => v.length as u64, + (Value::Object(o), None) => length_of(interp, *o)?, + _ => { + let o = interp.to_object(&source)?; + length_of(interp, o)? + } + }; + #[allow(clippy::cast_precision_loss)] + if offset + src_len as f64 > view.length as f64 { + return Err(interp.throw(ErrorType::Range, "the source does not fit in the typed array at that offset")); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let offset = offset as usize; + let count = usize::try_from(src_len).unwrap_or(0); + if let Some(src) = src_view.filter(|src| src.elem == view.elem) { + copy_elements(interp, &src, 0, &view, offset, count)?; + return Ok(Value::Undefined); + } + if let Some(src) = src_view { + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, count.saturating_mul(8))?; + let mut values = Vec::with_capacity(count); + for i in 0..count { + interp.use_fuel()?; + values.push(at(interp, &src, i)); + } + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + let src = interp.to_object(&source)?; + interp.rooted(&[Value::Object(src)], |interp| { + for i in 0..count { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(src, &super::key_of(i as f64), &Value::Object(src))?; + let n = interp.to_number(&v)?; + write(interp, &view, offset + i, n); + } + Ok(Value::Undefined) + }) +} + +/// `copyWithin(target, start, end)` (section 22.2.3.5): moves the bytes of the range within the +/// buffer, overlapping ranges included. +fn copy_within(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "copyWithin")?; + let len = view.length; + let to = relative(interp, &arg(args, 0), len, 0)?; + let from = relative(interp, &arg(args, 1), len, 0)?; + let end = relative(interp, &arg(args, 2), len, len)?; + let count = end.saturating_sub(from).min(len - to); + copy_elements(interp, &view, from, &view, to, count)?; + Ok(this) +} + +/// The default order of `sort` (section 22.2.3.25): numeric, with `-0` before `+0` and `NaN` +/// last. +fn default_order(a: f64, b: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a.is_nan(), b.is_nan()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + _ if a == 0.0 && b == 0.0 => b.is_sign_negative().cmp(&a.is_sign_negative()), + _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal), + } +} + +/// Whether `b` goes before `a`: by `compare` when it is a function, the default order otherwise. +/// Each comparison takes a unit of fuel. +fn goes_before(interp: &mut Interp, compare: &Value, a: f64, b: f64) -> JsResult { + interp.use_fuel()?; + if matches!(compare, Value::Undefined) { + return Ok(default_order(b, a) == std::cmp::Ordering::Less); + } + let r = interp.call(compare, &Value::Undefined, &[Value::Number(a), Value::Number(b)])?; + let n = interp.to_number(&r)?; + Ok(n > 0.0) +} + +/// Sorts `values` stably with a merge sort whose comparisons may fail. +fn merge_sort(interp: &mut Interp, values: &mut Vec, compare: &Value) -> JsResult<()> { + let n = values.len(); + let mut buf = values.clone(); + let mut width = 1; + while width < n { + let mut lo = 0; + while lo < n { + let mid = (lo + width).min(n); + let hi = (lo + 2 * width).min(n); + let (mut i, mut j) = (lo, mid); + for slot in buf.iter_mut().take(hi).skip(lo) { + let take_right = match (values.get(i), values.get(j)) { + (Some(&a), Some(&b)) if i < mid && j < hi => goes_before(interp, compare, a, b)?, + _ => i >= mid, + }; + let pick = if take_right { &mut j } else { &mut i }; + *slot = values.get(*pick).copied().unwrap_or(0.0); + *pick += 1; + } + lo = hi; + } + std::mem::swap(values, &mut buf); + width *= 2; + } + Ok(()) +} + +/// `sort(comparefn)` (section 22.2.3.25). +fn sort(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let compare = arg(args, 0); + if !matches!(compare, Value::Undefined) { + require_callable(interp, &compare, "the comparison function")?; + } + let (_, view) = this_typed(interp, &this, "sort")?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, view.length.saturating_mul(16))?; + let mut values: Vec = (0..view.length).map(|i| at(interp, &view, i)).collect(); + merge_sort(interp, &mut values, &compare)?; + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, i, n); + } + Ok(this) +} diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs new file mode 100644 index 0000000000..1798707aff --- /dev/null +++ b/crates/js/src/builtins/collections.rs @@ -0,0 +1,696 @@ +//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator +//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections +//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`]. +//! +//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order +//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries +//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet +//! entries hold their key weakly: the collector removes an entry once its key is reachable only +//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. +//! +//! The language has no iterators yet, so the constructors read their argument by index: an +//! array or an object with a `length`, or a string by code point. Every entry added is checked +//! against the heap limit before it is added, and every entry visited takes a unit of fuel. + +use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use crate::heap::{ + COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, + PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, +}; +use crate::interp::{Abrupt, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::{Str, Value}; + +/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does +/// to the globals. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Es2015 { + pub(crate) map_proto: ObjId, + pub(crate) set_proto: ObjId, + pub(crate) weak_map_proto: ObjId, + pub(crate) weak_set_proto: ObjId, + pub(crate) map_iter_proto: ObjId, + pub(crate) set_iter_proto: ObjId, + pub(crate) array_iter_proto: ObjId, + pub(crate) array_buffer_proto: ObjId, + pub(crate) data_view_proto: ObjId, + /// `%TypedArray%` and its prototype (section 22.2.1). + pub(crate) typed_array_ctor: ObjId, + pub(crate) typed_array_proto: ObjId, + /// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`]. + pub(crate) typed_ctors: [ObjId; 9], + pub(crate) typed_protos: [ObjId; 9], +} + +impl Es2015 { + pub(crate) fn placeholder() -> Self { + let o = ObjId(0); + Self { + map_proto: o, + set_proto: o, + weak_map_proto: o, + weak_set_proto: o, + map_iter_proto: o, + set_iter_proto: o, + array_iter_proto: o, + array_buffer_proto: o, + data_view_proto: o, + typed_array_ctor: o, + typed_array_proto: o, + typed_ctors: [o; 9], + typed_protos: [o; 9], + } + } + + pub(crate) fn all(&self) -> Vec { + let mut v = vec![ + self.map_proto, + self.set_proto, + self.weak_map_proto, + self.weak_set_proto, + self.map_iter_proto, + self.set_iter_proto, + self.array_iter_proto, + self.array_buffer_proto, + self.data_view_proto, + self.typed_array_ctor, + self.typed_array_proto, + ]; + v.extend(self.typed_ctors); + v.extend(self.typed_protos); + v + } +} + +/// A new ordinary object with `proto`, for a prototype. +pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId { + interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))) +} + +/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors +/// of ECMAScript 2015 are. +pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> { + let g = native(interp, name, f, 0, NativeKind::Plain, false)?; + let prop_name = name.strip_prefix("get ").unwrap_or(name); + interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE }) +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + + let map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.map_proto = map_proto; + let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Map", map, map_proto)?; + let map_methods: [(&'static str, NativeFn, u32); 9] = [ + ("get", map_get, 1), + ("set", map_set, 2), + ("has", map_has, 1), + ("delete", map_delete, 1), + ("clear", map_clear, 0), + ("forEach", map_for_each, 1), + ("keys", map_keys, 0), + ("values", map_values, 0), + ("entries", map_entries, 0), + ]; + for (name, f, length) in map_methods { + method(interp, map_proto, name, f, length)?; + } + getter(interp, map_proto, "get size", map_size)?; + + let set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.set_proto = set_proto; + let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Set", set, set_proto)?; + let set_methods: [(&'static str, NativeFn, u32); 7] = [ + ("has", set_has, 1), + ("add", set_add, 1), + ("delete", set_delete, 1), + ("clear", set_clear, 0), + ("entries", set_entries, 0), + ("forEach", set_for_each, 1), + ("values", set_values, 0), + ]; + for (name, f, length) in set_methods { + method(interp, set_proto, name, f, length)?; + } + getter(interp, set_proto, "get size", set_size)?; + // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). + let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; + interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + + let weak_map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_map_proto = weak_map_proto; + let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakMap", weak_map, weak_map_proto)?; + let weak_map_methods: [(&'static str, NativeFn, u32); 4] = + [("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)]; + for (name, f, length) in weak_map_methods { + method(interp, weak_map_proto, name, f, length)?; + } + + let weak_set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_set_proto = weak_set_proto; + let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakSet", weak_set, weak_set_proto)?; + let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)]; + for (name, f, length) in weak_set_methods { + method(interp, weak_set_proto, name, f, length)?; + } + + for source in [IterSource::Map, IterSource::Set, IterSource::Array] { + let proto = new_proto(interp, object_proto); + let next: NativeFn = match source { + IterSource::Map => map_iterator_next, + IterSource::Set => set_iterator_next, + IterSource::Array => array_iterator_next, + }; + method(interp, proto, "next", next, 0)?; + match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto, + } + } + Ok(()) +} + +// ---- keys ---- + +/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap. +fn coll_key(interp: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => CollKey::Undefined, + Value::Null => CollKey::Null, + Value::Bool(b) => CollKey::Bool(*b), + Value::Number(n) => CollKey::number(*n), + Value::String(s) => CollKey::String(flat_charged(interp, s)?), + Value::Object(o) => CollKey::Object(o.0), + }) +} + +/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1). +fn stored_key(v: Value) -> Value { + match v { + // `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`. + Value::Number(n) => Value::Number(n + 0.0), + v => v, + } +} + +// ---- reading a list ---- + +/// ToLength (section 7.1.15) of an object's `length`. +pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + let len = interp.get_from(o, &key("length"), &Value::Object(o))?; + let n = super::to_integer(interp, &len)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) +} + +/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, +/// or a string's code points. Any other value is a `TypeError`, and so is an object without a +/// `length` when `need_length` is true. Each item takes a unit of fuel. +pub(crate) fn for_each_item( + interp: &mut Interp, + list: &Value, + need_length: bool, + mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, +) -> JsResult<()> { + match list { + Value::Object(o) => { + if need_length && !interp.has_property(*o, &key("length"))? { + return Err(interp.type_error("the value is not an array, a string or an object with a length")); + } + let len = length_of(interp, *o)?; + let mut i = 0u64; + while i < len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(*o, &key_of(i as f64), list)?; + f(interp, item)?; + i += 1; + } + Ok(()) + } + Value::String(s) => { + let units = flat_charged(interp, s)?; + let mut i = 0; + while i < units.len() { + interp.use_fuel()?; + let width = match (units.get(i), units.get(i + 1)) { + (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, + _ => 1, + }; + let piece = units.get(i..i + width).unwrap_or_default().to_vec(); + let bytes = string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + f(interp, Value::String(Str::from_units(piece)))?; + i += width; + } + Ok(()) + } + _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), + } +} + +/// Adds the items of `list` to the new collection `target` with its `adder` method, as the +/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item +/// as a `[key, value]` entry. +fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { + if list.is_nullish() { + return Ok(()); + } + let this = Value::Object(target); + interp.rooted(&[this.clone(), list.clone()], |interp| { + let add = interp.get_from(target, &key(adder), &this)?; + require_callable(interp, &add, adder)?; + interp.rooted(std::slice::from_ref(&add), |interp| { + for_each_item(interp, list, true, |interp, item| { + if !pairs { + return interp.call(&add, &this, &[item]).map(drop); + } + let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) }; + let k = interp.get_from(entry, &key("0"), &item)?; + let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?; + interp.call(&add, &this, &[k, v]).map(drop) + }) + }) + }) +} + +/// A new collection object of `class` with `proto`, filled from `args[0]`. +fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{name} must be called with new"))); + } + interp.reserve_heap(OBJECT_BYTES)?; + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + let (adder, pairs) = match name { + "Map" | "WeakMap" => ("set", true), + _ => ("add", false), + }; + fill(interp, o, &arg(args, 0), adder, pairs)?; + Ok(Value::Object(o)) +} + +fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.map_proto; + construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) +} + +fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.set_proto; + construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto) +} + +fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_map_proto; + construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto) +} + +fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_set_proto; + construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto) +} + +// ---- Map and Set ---- + +/// The Map (or with `set`, the Set) a method was called on. +fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true)) + { + return Ok(*o); + } + let name = if set { "Set" } else { "Map" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> { + match &interp.object(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> { + match &mut interp.object_mut(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +/// Adds or replaces the entry of `k`, reserving the heap for a new one first. +fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> { + let ck = coll_key(interp, &k)?; + if !coll(interp, o)?.has(&ck) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES); + } + coll_mut(interp, o)?.set(ck, stored_key(k), v); + Ok(()) +} + +fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "get")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined)) +} + +fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "set")?; + coll_put(interp, o, arg(args, 0), arg(args, 1))?; + Ok(this) +} + +fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "has")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll(interp, o)?.has(&k))) +} + +fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "delete")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll_mut(interp, o)?.delete(&k))) +} + +fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "clear")?; + let slots = coll(interp, o)?.slots(); + // Clearing visits every position, and each takes a unit of fuel. + for _ in 0..slots { + interp.use_fuel()?; + } + coll_mut(interp, o)?.clear(); + Ok(Value::Undefined) +} + +fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "size")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(coll(interp, o)?.len() as f64)) +} + +fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, false) +} + +fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, false) +} + +fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, false) +} + +fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, false) +} + +fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, true, "add")?; + coll_put(interp, o, arg(args, 0), Value::Undefined)?; + Ok(this) +} + +fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, true) +} + +fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, true) +} + +fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, true) +} + +fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, true) +} + +/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a +/// Set, the value again) and the collection, in order, visiting entries added while it runs. The +/// position is kept in an iterator object, so a collection that removes holes moves it. +fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "forEach")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let source = if set { IterSource::Set } else { IterSource::Map }; + let it = new_iter(interp, o, source, IterKind::Entries, None)?; + interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| { + while let Some((k, v)) = advance(interp, it)? { + let v = if set { k.clone() } else { v }; + interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?; + } + Ok(Value::Undefined) + }) +} + +fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, false) +} + +fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, true) +} + +// ---- iterators ---- + +/// A new iterator over `target`, with `proto` (by default the prototype for `source`). +pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option) -> JsResult { + interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = proto.unwrap_or(match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto, + }); + let state = IterState { source, kind, target: Some(target), pos: 0 }; + let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + Ok(it) +} + +/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position +/// passed takes a unit of fuel. +fn advance(interp: &mut Interp, it: ObjId) -> JsResult> { + loop { + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) }; + let c = coll(interp, target)?; + let found = (pos < c.slots()).then(|| c.entry(pos).cloned()); + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + match found { + None => { + state.target = None; + return Ok(None); + } + Some(entry) => { + state.pos = pos + 1; + if let Some(entry) = entry { + return Ok(Some(entry)); + } + } + } + } +} + +/// An iterator result object `{ value, done }` (section 7.4.7). +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?; + let o = interp.new_object(); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new array `[a, b]`. +pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult { + interp.rooted(&[a.clone(), b.clone()], |interp| { + let arr = new_array(interp, 0)?; + interp.rooted(&[Value::Object(arr)], |interp| { + create_at(interp, arr, 0.0, a.clone())?; + create_at(interp, arr, 1.0, b.clone())?; + Ok(Value::Object(arr)) + }) + }) +} + +/// The iterator a `next` method was called on, when it goes through `source`. +fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> { + if let Value::Object(o) = this + && let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class) + && state.source == source + { + return Ok((*o, state.kind)); + } + Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator"))) +} + +fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult { + let (it, kind) = this_iter(interp, this, source, name)?; + let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) }; + let value = match (kind, source) { + (IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k, + (IterKind::Values, _) => v, + (IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?, + (IterKind::Entries, _) => pair(interp, k, v)?, + }; + iter_result(interp, value, false) +} + +fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Map, "Map") +} + +fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Set, "Set") +} + +/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays. +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?; + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (target, pos) = (state.target, state.pos); + let element = match target { + Some(t) => match &interp.object(t)?.class { + Class::TypedArray(view) => super::binary::element(interp, view, pos as f64), + _ => None, + }, + None => None, + }; + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let Some(element) = element else { + state.target = None; + return iter_result(interp, Value::Undefined, true); + }; + state.pos = pos + 1; + #[allow(clippy::cast_precision_loss)] + let index = Value::Number(pos as f64); + let value = match kind { + IterKind::Keys => index, + IterKind::Values => Value::Number(element), + IterKind::Entries => pair(interp, index, Value::Number(element))?, + }; + iter_result(interp, value, false) +} + +fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult { + let o = this_coll(interp, this, set, name)?; + let source = if set { IterSource::Set } else { IterSource::Map }; + new_iter(interp, o, source, kind, None).map(Value::Object) +} + +fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Keys, "keys") +} + +fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Values, "values") +} + +fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Entries, "entries") +} + +fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Values, "values") +} + +fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Entries, "entries") +} + +// ---- WeakMap and WeakSet ---- + +fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true)) + { + return Ok(*o); + } + let name = if set { "WeakSet" } else { "WeakMap" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> { + match &interp.object(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> { + match &mut interp.object_mut(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`. +fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> { + let Value::Object(key_obj) = k else { + let what = if set { "a WeakSet value" } else { "a WeakMap key" }; + return Err(interp.type_error(&format!("{what} must be an object"))); + }; + if !weak(interp, o)?.entries.contains_key(&key_obj.0) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES); + } + weak_mut(interp, o)?.entries.insert(key_obj.0, v); + Ok(()) +} + +fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "get")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) }; + Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined)) +} + +fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "set")?; + weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?; + Ok(this) +} + +fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "has")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0))) +} + +fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "delete")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some())) +} + +fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, false) +} + +fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, false) +} + +fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, true, "add")?; + weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?; + Ok(this) +} + +fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, true) +} + +fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, true) +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs new file mode 100644 index 0000000000..7c00b29532 --- /dev/null +++ b/crates/js/src/collections_tests.rs @@ -0,0 +1,412 @@ +use crate::heap::{Class, key}; +use crate::value::Value; +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn realm() -> Realm { + Realm::with_options(es2015(), Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match realm().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +fn limit(limits: &Limits, src: &str) -> LimitKind { + match Realm::with_options(es2015(), limits.clone()).run(src) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k, + other => panic!("{src}: {other:?}"), + } +} + +/// The object a global variable holds. +fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId { + let interp = realm.interp(); + let global = interp.global; + match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) { + Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o, + _ => panic!("{name} is not an object"), + } +} + +// ---- realms ---- + +#[test] +fn realms_without_the_option_keep_the_es5_globals() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \ + Uint32Array Float32Array Float64Array"; + for name in names.split_whitespace() { + assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}"); + } + } + truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'"); +} + +// ---- Map and Set ---- + +#[test] +fn keys_compare_with_same_value_zero() { + truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1"); + truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity"); + truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity"); + truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'"); + truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined"); + truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1"); +} + +#[test] +fn entries_keep_the_order_they_were_added_in() { + assert_eq!( + string( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \ + var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()" + ), + "a9true,c3true,b4true" + ); + assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy"); +} + +#[test] +fn for_each_skips_deleted_entries_and_visits_added_ones() { + assert_eq!( + string( + "var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \ + m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()" + ), + "a,c,d" + ); + assert_eq!( + string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"), + "1,2,3,4,5" + ); + assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1"); +} + +#[test] +fn iterators_step_through_live_entries() { + truth( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \ + var second = it.next(), third = it.next(), last = it.next(); \ + first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \ + last.done && last.value === undefined && it.next().done", + ); + truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values"); + truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'"); + throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError"); +} + +#[test] +fn constructors_read_arrays_strings_and_array_likes() { + truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); + truth("new Set('ab\u{1F600}b').size === 3"); + truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + truth("new Map(null).size === 0 && new Set(undefined).size === 0"); + truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); + throws("Map()", "TypeError"); + throws("Set([])", "TypeError"); + throws("new Map([1])", "TypeError"); + throws("new Set(5)", "TypeError"); + throws("new Map({})", "TypeError"); + throws("new WeakSet({})", "TypeError"); + truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); + // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). + truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); + throws("Map.prototype.get.call({}, 1)", "TypeError"); + throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); + // The constructor adds through the prototype's method, as section 23.1.1.1 says. + truth( + "var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \ + new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2", + ); + truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); +} + +// ---- WeakMap and WeakSet ---- + +#[test] +fn weak_collections_take_object_keys_only() { + truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)"); + truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)"); + truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)"); + throws("new WeakMap().set(1, 2)", "TypeError"); + throws("new WeakSet().add('x')", "TypeError"); + throws("new WeakMap([[1, 2]])", "TypeError"); + truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'"); +} + +#[test] +fn a_weak_map_entry_does_not_keep_its_key_alive() { + let mut realm = realm(); + realm + .run( + "var wm = new WeakMap(), ws = new WeakSet(), kept = {}; + (function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })(); + wm.set(kept, {back: kept}); ws.add(kept);", + ) + .unwrap(); + let wm = global_object(&mut realm, "wm"); + let ws = global_object(&mut realm, "ws"); + let before = realm.interp().heap.live_cells(); + realm.interp().collect_garbage(); + let after = realm.interp().heap.live_cells(); + let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) { + Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(), + _ => panic!("not a weak collection"), + }; + assert_eq!(count(&mut realm, wm), 1); + assert_eq!(count(&mut realm, ws), 1); + // Each dropped key and its value were freed. + assert!(before - after >= 100, "{before} -> {after}"); + assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_weak_map_value_reachable_through_another_key_is_kept() { + let mut realm = realm(); + realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap(); + realm.interp().collect_garbage(); + assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0)); +} + +#[test] +fn weak_maps_of_dropped_keys_stay_within_the_heap() { + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(es2015(), limits); + let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'"); + assert_eq!(r.unwrap(), JsValue::String("done".into())); + assert!(realm.interp().heap.collections > 0); +} + +#[test] +fn collections_of_millions_end_at_the_limits() { + let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); + assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); + let fuel = Limits { fuel: 100_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; + assert_eq!(limit(&fuel, m), LimitKind::Fuel); +} + +#[test] +fn a_collection_removes_holes_and_moves_live_iterators() { + let mut realm = realm(); + realm + .run( + "var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2); + var it = m.values(); it.next(); it.next(); + for (var j = 0; j < 90; j++) m.delete(j);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)), + _ => panic!("not a Map"), + } + let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap(); + assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); +} + +// ---- ArrayBuffer ---- + +#[test] +fn array_buffers_are_zeroed_and_sliced() { + truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0"); + truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'"); + truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))"); + truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2"); + throws("ArrayBuffer(1)", "TypeError"); + throws("new ArrayBuffer(-1)", "RangeError"); +} + +#[test] +fn a_huge_array_buffer_is_refused_before_it_is_allocated() { + throws("new ArrayBuffer(1e15)", "RangeError"); + throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError"); + throws("new Float64Array(Math.pow(2, 40))", "RangeError"); + truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught"); + // Larger than the realm's heap limit: a catchable RangeError, not an allocation. + let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() }); + assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into())); + // Within the limit but not within what is left of it: the heap limit. + assert_eq!( + limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"), + LimitKind::Heap + ); +} + +// ---- DataView ---- + +#[test] +fn data_views_read_and_write_both_byte_orders() { + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294"); + truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200"); + truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b"); + throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 5)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError"); + throws("new DataView({})", "TypeError"); + throws("DataView(new ArrayBuffer(1))", "TypeError"); +} + +// ---- typed arrays ---- + +#[test] +fn uint8_clamped_rounds_half_to_even() { + assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255"); + assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44"); +} + +#[test] +fn element_types_convert_their_values() { + assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1"); + assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0"); + assert_eq!(string("new Int32Array([4294967295]).join()"), "-1"); + assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295"); + assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000"); + assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN"); + truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8"); + truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'"); +} + +#[test] +fn views_share_their_buffer_little_endian() { + truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1"); + truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1"); + truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4"); + throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError"); + throws("new Int32Array(new ArrayBuffer(6))", "RangeError"); + throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError"); +} + +#[test] +fn numeric_names_are_elements_or_nothing() { + truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'"); + truth( + "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", + ); + truth("Int8Array.prototype[0] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[0]; r"); + truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); + // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. + truth( + "var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2", + ); + truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]"); + throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError"); + // An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]]. + truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined"); + truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable"); + truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5"); + throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError"); + throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError"); + throws("Object.freeze(new Uint8Array(1))", "TypeError"); + truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'"); + truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'"); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_typed_array() { + truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999"); + truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999"); + // The element count, not a `length` property defined on the array, bounds the methods. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \ + a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })", + ); + // A generic array method called on the typed array reads its `length` property. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \ + Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'", + ); +} + +#[test] +fn typed_array_methods() { + assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN"); + truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity"); + assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3"); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3"); + assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0"); + throws("new Uint8Array(2).set([1, 2, 3])", "RangeError"); + throws("new Uint8Array(2).set([1], -1)", "RangeError"); + assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5"); + assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0"); + assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7"); + truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1"); + truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1"); + truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'"); + truth( + "var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done", + ); + truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9"); + truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); + truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); + truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + truth( + "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", + ); + throws("Object.getPrototypeOf(Int8Array)()", "TypeError"); + throws("Int8Array(1)", "TypeError"); + throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError"); + throws("Int8Array.from.call(Object, [1])", "TypeError"); + throws("Int8Array.from.call({}, [1])", "TypeError"); + // The source's length is read before the constructor is checked to be a typed array's. + throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); + // A copy to the same element type keeps every bit, a signaling NaN's included. + truth( + "var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \ + function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \ + var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \ + bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \ + new DataView(g.buffer).getUint32(8, true) === 0x7f800001", + ); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); +} + +#[test] +fn typed_array_work_takes_fuel() { + let fuel = Limits { fuel: 50_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..4aed4b9c9b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,231 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. + Map(Box), + /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. + Set(Box), + /// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key + /// reachable, and its value is reachable only while its key is. + WeakMap(Box), + /// A `WeakSet` (section 23.4): objects that it does not keep reachable. + WeakSet(Box), + /// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5). + Iter(Box), + /// An `ArrayBuffer` (section 24.1) and its bytes, which never change length. + ArrayBuffer(Box<[u8]>), + /// A `DataView` (section 24.2): a range of a buffer's bytes. + DataView(Box), + /// A typed array (section 22.2): elements of one type in a range of a buffer's bytes. + TypedArray(Box), +} + +/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0` +/// equals `+0`, strings compare by their code units and objects by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum CollKey { + Undefined, + Null, + Bool(bool), + /// The bits of the number, with every `NaN` as one value and `-0` as `+0`. + Number(u64), + String(Rc<[u16]>), + Object(u32), +} + +impl CollKey { + /// The key of a number. + pub(crate) fn number(n: f64) -> Self { + CollKey::Number(if n.is_nan() { + f64::NAN.to_bits() + } else if n == 0.0 { + 0 + } else { + n.to_bits() + }) + } +} + +/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole, +/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes +/// the holes of a collection with more holes than entries and moves its live iterators with them. +#[derive(Clone, Default)] +pub(crate) struct Coll { + entries: Vec>, + index: HashMap, +} + +impl Coll { + /// The number of entries. + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + /// The number of positions, holes included. + pub(crate) fn slots(&self) -> usize { + self.entries.len() + } + + pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, v)| v) + } + + pub(crate) fn has(&self, k: &CollKey) -> bool { + self.index.contains_key(k) + } + + /// Sets the value under `k`, keeping its position when it is there already. Returns whether + /// a new entry was added. + pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool { + if let Some(&i) = self.index.get(&k) + && let Some(Some((_, v))) = self.entries.get_mut(i) + { + *v = value; + return false; + } + self.index.insert(k, self.entries.len()); + self.entries.push(Some((key, value))); + true + } + + /// Deletes the entry under `k`; returns whether there was one. + pub(crate) fn delete(&mut self, k: &CollKey) -> bool { + let Some(i) = self.index.remove(k) else { return false }; + if let Some(slot) = self.entries.get_mut(i) { + *slot = None; + } + true + } + + /// Deletes every entry, leaving the positions in place. + pub(crate) fn clear(&mut self) { + self.index.clear(); + self.entries.iter_mut().for_each(|e| *e = None); + } + + /// The entry at position `i`, or `None` for a hole or a position past the end. + pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> { + self.entries.get(i)?.as_ref() + } + + fn values(&self) -> impl Iterator { + self.entries.iter().flatten().flat_map(|(k, v)| [k, v]) + } + + fn should_compact(&self) -> bool { + let holes = self.entries.len() - self.index.len(); + holes > 16 && holes > self.index.len() + } + + /// Removes the holes. Returns, for each old position and the position past the end, the new + /// position of the first entry at or after it. + fn compact(&mut self) -> Vec { + let mut moved = Vec::with_capacity(self.entries.len() + 1); + let mut live = 0usize; + for e in &self.entries { + moved.push(live); + live += usize::from(e.is_some()); + } + moved.push(live); + self.entries.retain(Option::is_some); + for slot in self.index.values_mut() { + *slot = moved.get(*slot).copied().unwrap_or(*slot); + } + moved + } +} + +/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are +/// `undefined`. +#[derive(Clone, Default)] +pub(crate) struct WeakColl { + pub(crate) entries: HashMap, +} + +/// What an iterator object goes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterSource { + Map, + Set, + /// A typed array, by index. + Array, +} + +/// What each step of an iterator gives: the key, the value or a `[key, value]` array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. `target` is `None` once the iterator has finished. +#[derive(Clone, Debug)] +pub(crate) struct IterState { + pub(crate) source: IterSource, + pub(crate) kind: IterKind, + pub(crate) target: Option, + pub(crate) pos: usize, +} + +/// The element type of a typed array (section 22.2, table 50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Elem { + Int8, + Uint8, + Uint8Clamped, + Int16, + Uint16, + Int32, + Uint32, + Float32, + Float64, +} + +impl Elem { + pub(crate) const ALL: [Elem; 9] = + [Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64]; + + /// The bytes of one element. + pub(crate) fn size(self) -> usize { + match self { + Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1, + Elem::Int16 | Elem::Uint16 => 2, + Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4, + Elem::Float64 => 8, + } + } + + /// The name of the constructor. + pub(crate) fn name(self) -> &'static str { + match self { + Elem::Int8 => "Int8Array", + Elem::Uint8 => "Uint8Array", + Elem::Uint8Clamped => "Uint8ClampedArray", + Elem::Int16 => "Int16Array", + Elem::Uint16 => "Uint16Array", + Elem::Int32 => "Int32Array", + Elem::Uint32 => "Uint32Array", + Elem::Float32 => "Float32Array", + Elem::Float64 => "Float64Array", + } + } + + /// The position of the type in [`Elem::ALL`]. + pub(crate) fn index(self) -> usize { + Elem::ALL.iter().position(|e| *e == self).unwrap_or(0) + } +} + +/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting +/// `offset` bytes into `buffer`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct View { + pub(crate) buffer: ObjId, + pub(crate) offset: usize, + pub(crate) length: usize, + pub(crate) elem: Elem, } /// What an XML value is. @@ -322,6 +547,18 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::Map(_) => "Map", + Class::Set(_) => "Set", + Class::WeakMap(_) => "WeakMap", + Class::WeakSet(_) => "WeakSet", + Class::Iter(state) => match state.source { + IterSource::Map => "Map Iterator", + IterSource::Set => "Set Iterator", + IterSource::Array => "Array Iterator", + }, + Class::ArrayBuffer(_) => "ArrayBuffer", + Class::DataView(_) => "DataView", + Class::TypedArray(view) => view.elem.name(), } } } @@ -397,6 +634,12 @@ pub(crate) const XML_REF_BYTES: usize = 8; pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; +/// The estimated bytes of a Map or Set position, with its entry in the hash index. +pub(crate) const COLL_ENTRY_BYTES: usize = 96; +/// The estimated bytes of a WeakMap or WeakSet entry. +pub(crate) const WEAK_ENTRY_BYTES: usize = 64; +/// The estimated bytes of the state of an iterator, a typed array or a `DataView`. +pub(crate) const VIEW_BYTES: usize = 48; pub(crate) fn string_bytes(len: usize) -> usize { 32 + 2 * len @@ -476,11 +719,18 @@ impl Heap { /// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is /// the estimated size of what is left, strings reachable from it included. + /// + /// A WeakMap's entry marks its value only once its key is marked by another path, and the + /// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so + /// a value that refers back to its own key does not keep it alive. Values waiting for their + /// key are kept by key, so the marking stays linear in the number of entries. pub(crate) fn collect(&mut self, roots: &Roots<'_>) { let mut marks = vec![false; self.cells.len()]; let mut work: Vec = Vec::new(); let mut strings = StringSizes::default(); let mut live = 0usize; + let mut pending: HashMap> = HashMap::new(); + let mut weak: Vec = Vec::new(); for v in &roots.values { mark_value(v, &mut work, &mut strings); } @@ -495,21 +745,80 @@ impl Heap { continue; } *mark = true; + if let Some(values) = pending.remove(&i) { + for v in &values { + mark_value(v, &mut work, &mut strings); + } + } match self.cells.get(i as usize) { - Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings), + Some(Cell::Object(o)) => { + live += trace_object(o, &mut work, &mut strings); + match &o.class { + Class::WeakMap(w) => { + weak.push(i); + for (k, v) in &w.entries { + if marks.get(*k as usize).copied().unwrap_or(false) { + mark_value(v, &mut work, &mut strings); + } else if matches!(v, Value::Object(_) | Value::String(_)) { + pending.entry(*k).or_default().push(v.clone()); + } + } + } + Class::WeakSet(_) => weak.push(i), + _ => {} + } + } Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings), _ => {} } } + for i in weak { + if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize) + && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class + { + w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + live += WEAK_ENTRY_BYTES * w.entries.len(); + } + } for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() { if !marked && !matches!(cell, Cell::Free) { *cell = Cell::Free; self.free.push(u32::try_from(i).unwrap_or(u32::MAX)); } } + live = live.saturating_sub(self.compact_collections()); self.bytes = live + strings.bytes; self.collections += 1; } + + /// Removes the holes of the Maps and Sets that have more holes than entries, and moves the + /// positions of their iterators with them. Returns the bytes the holes held. + fn compact_collections(&mut self) -> usize { + let mut moved: HashMap> = HashMap::new(); + let mut freed = 0usize; + for (i, cell) in self.cells.iter_mut().enumerate() { + if let Cell::Object(o) = cell + && let Class::Map(c) | Class::Set(c) = &mut o.class + && c.should_compact() + { + freed += COLL_ENTRY_BYTES * (c.slots() - c.len()); + moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact()); + } + } + if moved.is_empty() { + return 0; + } + for cell in &mut self.cells { + if let Cell::Object(o) = cell + && let Class::Iter(state) = &mut o.class + && state.source != IterSource::Array + && let Some(map) = state.target.and_then(|t| moved.get(&t.0)) + { + state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0); + } + } + freed + } } /// What the collector starts from. @@ -680,6 +989,23 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Map(c) | Class::Set(c) => { + for v in c.values() { + mark_value(v, work, strings); + } + extra = COLL_ENTRY_BYTES * c.slots(); + } + // Their entries are marked and counted by the collector's weak pass. + Class::WeakMap(_) | Class::WeakSet(_) => {} + Class::Iter(state) => { + work.extend(state.target.iter().map(|o| o.0)); + extra = VIEW_BYTES; + } + Class::ArrayBuffer(bytes) => extra = bytes.len(), + Class::DataView(view) | Class::TypedArray(view) => { + work.push(view.buffer.0); + extra = VIEW_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..b90c354347 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -103,6 +103,8 @@ pub(crate) struct Intrinsics { pub(crate) xml_list_proto: ObjId, pub(crate) namespace_proto: ObjId, pub(crate) qname_proto: ObjId, + /// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]). + pub(crate) es2015: crate::builtins::collections::Es2015, } impl Intrinsics { @@ -125,6 +127,7 @@ impl Intrinsics { xml_list_proto: o, namespace_proto: o, qname_proto: o, + es2015: crate::builtins::collections::Es2015::placeholder(), } } @@ -160,6 +163,7 @@ impl Intrinsics { self.qname_proto, ]; v.extend(self.error_protos); + v.extend(self.es2015.all()); v } } @@ -251,6 +255,9 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// The typed array whose element count the next array method reads as its length, set while a + /// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read. + pub(crate) typed_length: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, /// The clock and time zone `Date` reads. @@ -517,6 +524,7 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + typed_length: None, files: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -1380,6 +1388,12 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + // A numeric name of a typed array is an element or nothing (section 9.4.5.1). + Class::TypedArray(view) => { + if let Some(n) = crate::builtins::binary::canonical_index(k) { + return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN })); + } + } _ => {} } Ok(o.props.get(k).cloned()) @@ -1393,6 +1407,10 @@ impl Interp { if let Some(p) = self.get_own_property(o, k)? { return Ok(Some(p)); } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok(None); + } cur = self.object(o)?.proto; steps += 1; if steps > 1_000_000 { @@ -1490,6 +1508,9 @@ impl Interp { } self.define_ordinary(id, k, desc, throw) } + Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => { + crate::builtins::binary::define_element(self, id, &k, desc, throw) + } Class::Arguments(map) => { let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned(); if !self.define_ordinary(id, k.clone(), desc, false)? { @@ -1642,7 +1663,12 @@ impl Interp { /// list is checked first. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { let o = self.object(id)?; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; + // A typed array's indices come first, as a String object's do (section 9.4.5.6). + let string_len = match &o.class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + }; let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); @@ -1684,6 +1710,9 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { + return crate::builtins::binary::set_element(self, id, n, &v); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -1759,6 +1788,18 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + // A typed array's element cannot be deleted, and a numeric name it has no element for + // is not a property it can hold (section 9.4.5.6 of later editions). + if crate::builtins::binary::typed_key(self, id, k).is_some() { + if self.get_own_property(id, k)?.is_none() { + return Ok(true); + } + if throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array"))); + } + return Ok(false); + } match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -2121,8 +2162,12 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { let obj = self.object(o)?; - let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; - let is_array = matches!(obj.class, Class::Array { .. }); + let string_len = match &obj.class { + Class::String(s) => Some(s.len()), + Class::TypedArray(view) => Some(view.length), + _ => None, + }; + let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_)); if let Some(len) = string_len { self.reserve_heap(index_keys_bytes(len))?; for i in 0..len { @@ -2132,7 +2177,6 @@ impl Interp { out.push(k); } } - seen.insert(key("length")); } if is_array { seen.insert(key("length")); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..34284a6fd9 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,18 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins +//! (): `Map` and `Set` (sections 23.1 and 23.2), whose +//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting +//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the +//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine +//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with +//! a `next` method. Until the language has iterators, the collection constructors and +//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by +//! index. A typed array constructor reads an array or an object with a `length` the same way, and +//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] pub mod ast; @@ -100,11 +112,15 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the ECMAScript 2015 built-ins this engine has: `Map`, `Set`, `WeakMap`, + /// `WeakSet`, `ArrayBuffer`, `DataView` and the typed arrays. Off, a realm has the ES5.1 + /// built-ins only, as ExtendScript scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -203,6 +219,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod collections_tests; +#[cfg(test)] mod extension_tests; #[cfg(test)] mod host_tests; diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..2b273d6359 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -28,6 +28,11 @@ //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. //! +//! A fifth test runs the tests under the folders [`ES2015_BUILT_INS`] names (`Map`, `Set`, +//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in +//! realms with [`Options::es2015`], each test whose feature tags are all in [`ES2015_FEATURES`]; its +//! failures go to `es2015-failures.txt`. It fails when the interpreter panics. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -444,7 +449,12 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool { /// Runs one test in a new realm; `Err` describes a failure. fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> { - let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + run_in(Options::default(), script, negative_type) +} + +/// Runs one test in a new realm with `options`; `Err` describes a failure. +fn run_in(options: Options, script: &str, negative_type: Option<&str>) -> Result<(), String> { + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); match (realm.run(script), negative_type) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), @@ -590,6 +600,108 @@ fn run_text_builtins(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections +/// and binary data, which run in a realm with [`Options::es2015`]. +const ES2015_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"]; + +/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides. +const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array"; + +/// The feature tags a test under [`ES2015_BUILT_INS`] may have and still run: the built-ins +/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of +/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or +/// detached buffers, `BigInt` and later additions) are counted as skipped. +const ES2015_FEATURES: &[&str] = &[ + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "TypedArray", + "Int8Array", + "Uint8Array", + "Float64Array", + "stable-typedarray-sort", +]; + +#[test] +fn es2015_collections_and_binary_data_run() { + let Some(dir) = suite_dir() else { + println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under the folders [`ES2015_BUILT_INS`] names in realms with +/// [`Options::es2015`], prints each folder's counts and writes the failures to +/// `es2015-failures.txt` beside the suite. +fn run_es2015_built_ins(dir: &Path) { + let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]); + let mut report = String::new(); + let mut panicked = 0; + for name in ES2015_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_es2015_tests(dir, &root, &missing); + println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary()); + report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures)); + panicked += counts.panicked; + } + let path = dir.join("es2015-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 ECMAScript 2015 built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the tests under `root` whose feature tags are all in [`ES2015_FEATURES`], as +/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`]. +fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts { + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let known = meta.features.iter().all(|f| ES2015_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype.")); + if !known || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_in(Options { es2015: true, ..Options::default() }, &script, negative_type.as_deref())) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + counts +} + /// Runs the tests under `root` that have no feature tag and are not module, asynchronous or /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..58c4525d84 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -87,8 +87,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa /// Text an action set written out at run time holds. pub(crate) const ACTION_TEXT: &str = "/actionCount"; -/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition, -/// section 13), and the platform's own: `new` of these is no document-model type. +/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary +/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and +/// the platform's own: `new` of these is no document-model type. pub(crate) const CONSTRUCTORS: &[&str] = &[ "Object", "Function", @@ -105,6 +106,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[ "SyntaxError", "TypeError", "URIError", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", "Namespace", "QName", "XML", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..676232545f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1392,6 +1392,17 @@ fn type_names_compared_or_created_are_listed() { assert_eq!(r.needs, [Need::Dom]); } +#[test] +fn collections_and_typed_arrays_are_not_type_names() { + let r = report(concat!( + "var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n", + "var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n", + "var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n", + "var f = [new Float32Array(1), new Float64Array(1)];\n", + )); + assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::>()); +} + #[test] fn menu_commands_are_counted_with_their_lines() { let r = report(concat!( diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..7204bf97a9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2616,8 +2616,10 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and -`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. An ES5.1 script does not +have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the typed arrays; the JavaScript engine's +ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. The +script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..32a682ab00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 99c4a82b3088efaebb181d065f2c2b9d090e99b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:43:40 -0800 Subject: [PATCH 011/106] Tabs: fallback glyphs in tab titles sit on the condensed face's baseline The tab family's copies of the semibold faces took the copy made for egui's empty Proportional family, which has no baseline shift, instead of the one made for the tab family. They now take the tab family's copy. egui's own faces stay under their own names, as in the semibold family: egui skips some of their characters (the Ubuntu logo, two symbols in its emoji face) only under those names. ui_fonts::baseline_copies measured a fallback face without its own FontTweak scale, while egui draws the face and its y_offset_factor at that scale. The shift now uses it, so a scaled fallback (Inter SemiBold at 0.92) sits on the row's baseline. Faces added before this change are at scale 1 and keep their shift. Without the condensed face the tab family is no longer bound, and tabs draw in theme::tab_title_font: the tab family when the context's fonts bind it, otherwise the semibold family as it is. Fonts an embedder adds to the semibold family then reach tab titles too, and an embedder's own definitions that bind only the other families keep working. The condensed face and the lookup of its catalog row move to build/condensed_ui_face.rs, which the crate's tests include. With CRAFT_FONTS_REQUIRED=1, an unreadable catalog, a malformed row for the face or a row whose file can't be embedded is a build error; a checkout without the catalog or the row still gives a warning. A checkout whose catalog names the condensed face without its file is watched through the file's folder inside the checkout, so the build runs again once the file appears. docs/development.md lists FONT_TAB among the families an embedder adds fonts to. ASSETS.md and NOTICE name the face, and the docs/ui-parity.md row says official builds wait for the craft-fonts pin to move. Tests: with the monospace face standing in for the condensed face, and without craft-fonts, one test checks the tab family's x-height, the baseline of a character only the semibold face has, and that the characters egui skips draw in a tab title as in semibold text. Two tab-strip tests check that titles are laid out in the tab family with a stand-in face and in the semibold family without one. The condensed-face test checks the x-height at 200 pt, the shortened-title test also runs in the tab font, the install_fonts test checks the tab family, and ui_fonts' no-craft-fonts test allows the condensed face, which a checkout can give alone. A text-crate test finds the face's row as craft-fonts' catalog has it and rejects malformed rows for it. Two comments use American spelling. --- ASSETS.md | 2 +- NOTICE | 2 + crates/text/build.rs | 52 +++++++----- crates/text/build/condensed_ui_face.rs | 45 ++++++++++ crates/text/src/lib.rs | 3 + crates/ui-egui/src/chrome/tabs.rs | 7 +- crates/ui-egui/src/chrome/tests.rs | 22 ++--- crates/ui-egui/src/i18n/tests.rs | 3 + crates/ui-egui/src/tests/tab_overflow.rs | 79 +++++++++++++++++- crates/ui-egui/src/theme.rs | 101 +++++++++++++++++++---- crates/ui-egui/src/ui_fonts.rs | 26 +++--- crates/ui-egui/tests/install_fonts.rs | 14 +++- docs/development.md | 8 +- docs/ui-parity.md | 2 +- 14 files changed, 299 insertions(+), 67 deletions(-) create mode 100644 crates/text/build/condensed_ui_face.rs diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..b949197d4c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -24,7 +24,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/NOTICE b/NOTICE index 434cd3e524..99470afd8e 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/crates/text/build.rs b/crates/text/build.rs index 5979c6557c..2658094965 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -14,12 +14,16 @@ //! out with a warning, never an error, and never costs the desktop its fonts. //! //! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in -//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A -//! checkout without that row leaves it `None` with a warning, never an error. +//! (`build/condensed_ui_face.rs`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. +//! A checkout without the catalog or that row leaves it `None` with a warning, never an error; an +//! unreadable catalog, a malformed row or a file that can't be embedded is an error with +//! `CRAFT_FONTS_REQUIRED=1`. use std::fmt::Write as _; use std::path::{Path, PathBuf}; +#[path = "build/condensed_ui_face.rs"] +mod condensed_ui_face; #[path = "build/web_fonts.rs"] mod web_fonts; @@ -28,6 +32,7 @@ fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); + println!("cargo::rerun-if-changed=build/condensed_ui_face.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { @@ -55,7 +60,8 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { match condensed_ui_font(&dir) { Ok(entry) => condensed = format!("Some({entry})"), - Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, true)) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, _)) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } } @@ -108,7 +114,7 @@ fn craft_fonts(dir: &Path) -> Result { Ok(out) } -/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +/// The `CraftFont { .. }` initializer of one manifest row of the checkout `dir` (canonical `root`). fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; // The manifest is supplier data: embed only regular files inside the checkout. @@ -124,29 +130,33 @@ fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, sc )) } -/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in -/// Latin catalog. -const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); - -/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. -fn condensed_ui_font(dir: &Path) -> Result { +/// The `CraftFont { .. }` initializer of the condensed face's row in `fonts/latin-manifest.txt` +/// (`build/condensed_ui_face.rs`). The error says whether the checkout is broken: one without the +/// catalog or the row is an older craft-fonts, and an unreadable catalog, a malformed row or a row +/// whose file can't be embedded is broken. +fn condensed_ui_font(dir: &Path) -> Result { + let (family, style) = condensed_ui_face::FACE; let manifest = dir.join("fonts/latin-manifest.txt"); // A checkout without the catalog is watched through its folder, so the build runs again once // the catalog appears. let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; println!("cargo::rerun-if-changed={}", watched.display()); - let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; - let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; - let row = text - .lines() - .map(str::trim) - .filter(|l| !l.is_empty() && !l.starts_with('#')) - .map(|l| l.split(" | ").map(str::trim).collect::>()) - .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); - let Some([family, style, file, scripts, ..]) = row.as_deref() else { - return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + let text = std::fs::read_to_string(&manifest).map_err(|e| { + let older = e.kind() == std::io::ErrorKind::NotFound; + (format!("{}: {e}{}", manifest.display(), if older { " (an older craft-fonts?)" } else { "" }), !older) + })?; + let row = condensed_ui_face::row(&text).map_err(|e| (format!("{}: {e}", manifest.display()), true))?; + let Some((file, scripts)) = row else { + return Err((format!("{family} {style} not in {} (an older craft-fonts?)", manifest.display()), false)); }; - craft_font(dir, &root, family, style, file, scripts) + let root = dir.canonicalize().map_err(|e| (format!("{}: {e}", dir.display()), true))?; + // A row whose file is missing is watched through the file's folder inside the checkout (or the + // checkout's `fonts/`), so the build runs again once the file appears. + craft_font(dir, &root, family, style, file, scripts).map_err(|e| { + let inside = dir.join(file).parent().and_then(|p| p.canonicalize().ok()).filter(|p| p.starts_with(&root) && p.is_dir()); + println!("cargo::rerun-if-changed={}", inside.unwrap_or_else(|| dir.join("fonts")).display()); + (e, true) + }) } /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and diff --git a/crates/text/build/condensed_ui_face.rs b/crates/text/build/condensed_ui_face.rs new file mode 100644 index 0000000000..c70e2cb2a4 --- /dev/null +++ b/crates/text/build/condensed_ui_face.rs @@ -0,0 +1,45 @@ +//! The condensed craft-fonts face document tab titles draw in, and its row in the checkout's opt-in +//! Latin catalog (`fonts/latin-manifest.txt`). Shared by `build.rs` and the crate's tests +//! (`#[path]`-included by both, so it has no dependencies). + +/// The condensed face's family and style. +pub const FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The file and scripts fields of [`FACE`]'s row in the catalog `text`: `None` when no row names +/// the face, and an error when the row that names it does not have the catalog's 8 fields or leaves +/// the file or scripts empty. +pub fn row(text: &str) -> Result, String> { + for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + match fields.as_slice() { + [family, style, file, scripts, _, _, _, _] if (*family, *style) == FACE && !file.is_empty() && !scripts.is_empty() => { + return Ok(Some((*file, *scripts))); + } + [family, style, ..] if (*family, *style) == FACE => return Err(format!("malformed manifest line: {line}")), + _ => {} + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The face's row as storytold/craft-fonts#72 adds it to the catalog is found, rows for other + /// faces are not taken for it, and a row naming it without its file or scripts, or with one of + /// them empty, is an error. + #[test] + fn the_catalog_row_names_the_face() { + let catalog = "# Latin presentation fonts for the Crafting Apps (opt-in).\n\ + Inter | SemiBold | fonts/inter/Inter-SemiBold.ttf | Latn | OFL-1.1 | fonts/inter/OFL.txt | 78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3 | https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip#extras/ttf/Inter-SemiBold.ttf\n\ + Noto Sans | Condensed SemiBold | fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf | Latn | OFL-1.1 | fonts/noto-sans-condensed/OFL.txt | b41ecd0838ecd17b706432a01c0d63f8bf977d851cc2cf37242324233edb9294 | https://github.com/notofonts/latin-greek-cyrillic/releases/download/NotoSans-v2.015/NotoSans-v2.015.zip#NotoSans/unhinted/ttf/NotoSans-CondensedSemiBold.ttf\n"; + assert_eq!(row(catalog), Ok(Some(("fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf", "Latn")))); + let rest = "OFL-1.1 | fonts/a/OFL.txt | 00 | https://example.com/a.zip"; + assert_eq!(row(&format!("Noto Sans | SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "another style"); + assert_eq!(row(&format!("# Noto Sans | Condensed SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "a comment"); + assert_eq!(row("Inter | Bold\n"), Ok(None), "a short row for another face"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | {rest}\n")).is_err(), "a row without its scripts"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | | {rest}\n")).is_err(), "a row with empty scripts"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2028639af4..d1e82be440 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -1068,6 +1068,9 @@ pub fn x_height(data: &[u8], index: u32) -> Option { m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) } +#[cfg(test)] +#[path = "../build/condensed_ui_face.rs"] +mod condensed_ui_face_build; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 1aff4fe1a9..782309a3f0 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_title_font(ui, title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -213,6 +213,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); + let title_font = theme::tab_title_font(ui, title_size); // The windows under the tabs, with the text each tab shows, its whole title and the text laid // out; `active` is the position of the highlighted one. An inactive tab shows the name alone, // without the zoom and the mode in parentheses (color mode and view, or the opacity mask being @@ -225,7 +226,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), title_font.clone(), color); (w, text, title, galley) }) .collect(); @@ -259,7 +260,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, title_font.clone(), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b78968442e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -29,27 +29,29 @@ fn the_tabs_after_the_leading_one_are_drawn_whole() { assert_eq!(super::tab_room(None, false, 120.0, 119.99), 119.99, "no leading tab"); } -/// A shortened title shows at every width that holds "…", fractional ones included (#8584). +/// A shortened title shows at every width that holds "…", fractional ones included (#8584), in the +/// semibold face and in the tab titles' face (the condensed one in a build with craft-fonts, #8583). #[test] fn a_shortened_title_fits_at_fractional_widths() { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let font = crate::theme::semibold(13.0); let title = "Untitled-12 @ 66.67 % (RGB/Preview)"; let mut too_wide = vec![]; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); - let mut width = ellipsis.size().x.ceil() + 1.0; - while width < 200.0 { - let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); - if !fits { - too_wide.push((width, galley.size().x)); + for font in [crate::theme::semibold(13.0), crate::theme::tab_title_font(ui, 13.0)] { + let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); + let mut width = ellipsis.size().x.ceil() + 1.0; + while width < 200.0 { + let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); + if !fits { + too_wide.push((font.family.clone(), width, galley.size().x)); + } + width += 0.25; } - width += 0.25; } }); output.textures_delta.clear(); - assert!(too_wide.is_empty(), "shortened titles wider than their room (room, width): {too_wide:?}"); + assert!(too_wide.is_empty(), "shortened titles wider than their room (family, room, width): {too_wide:?}"); } /// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7954785e30..6136913184 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1501,6 +1501,9 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; + // The tab family is bound only in builds with craft-fonts' condensed face. + let tab = egui::FontFamily::Name(crate::theme::FONT_TAB.into()); + let families: Vec = families.into_iter().filter(|f| *f != tab || fonts.definitions().families.contains_key(f)).collect(); for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let cjk_checked = japanese_ui_font && l.code == "ja"; diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index c9f9edec0a..7b389001d5 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -145,12 +145,87 @@ fn tab_titles_in_the_condensed_face_fit_more_tabs() { let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); // The height of an x, in the tab font and in semibold text. let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; - (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + let tab = if face.is_some() { crate::theme::tab_font(200.0) } else { crate::theme::semibold(200.0) }; + (whole, x(tab), x(crate::theme::semibold(200.0))) }; let (semibold, _, _) = whole_tabs(None); let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); - assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ by + // about 8 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + +/// The tab strip lays its titles out in the tab family's own face when it has one: the monospace +/// face stands in for craft-fonts' condensed face, which CI's craft-fonts checkout does not have +/// (#8583). +#[test] +fn tab_titles_draw_in_the_tab_familys_face() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "name": "Tab test"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(Some(&stand_in))); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 1, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_TAB.into()), "{title}"); + } +} + +/// The fonts the tab strip lays its "Tab test" titles out in. +fn title_fonts(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::FontId)> { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), ..Default::default() }, |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::FontId)>) { + match s { + egui::Shape::Text(t) if t.galley.text().starts_with("Tab test") => { + v.extend(t.galley.job.sections.first().map(|s| (t.galley.text().to_owned(), s.format.font_id.clone()))); + } + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut fonts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut fonts); + } + fonts +} + +/// Without the condensed face the tab family is not bound, and tab titles draw in the semibold +/// family as it is, with a face added to it later (#8583). +#[test] +fn tab_titles_draw_in_semibold_where_the_tab_family_is_not_bound() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..3 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Tab test {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + // A face put at the head of the semibold family after the interface's, as an embedder may. + let mut fonts = crate::theme::interface_fonts_with(None); + let added = "Added semibold".to_owned(); + fonts.font_data.insert( + added.clone(), + std::sync::Arc::new(egui::FontData::from_static(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"))), + ); + fonts.families.entry(egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into())).or_default().insert(0, added); + let ctx = egui::Context::default(); + ctx.set_fonts(fonts); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 3, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), "{title}"); + } } /// With the last document active, the tabs from it to the end leave room before the » button, and diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 11e8af8e22..2743922495 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -497,16 +497,23 @@ pub const FONT_MONO: &str = "mono"; /// The family document tab titles draw in. In a build with craft-fonts' condensed face /// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the /// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so -/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +/// more tabs fit in the strip (#8583). Without it the family is not bound, and tab titles draw in +/// [`FONT_UI_SEMIBOLD`] ([`tab_title_font`]). pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } -/// A document tab's title font ([`FONT_TAB`]). -pub fn tab_font(size: f32) -> FontId { +/// A font in [`FONT_TAB`], which is bound only with the condensed face: see [`tab_title_font`]. +pub(crate) fn tab_font(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_TAB.into())) } +/// The font document tab titles draw in on `ui`: the [`FONT_TAB`] family when `ui`'s fonts bind +/// it (with the condensed face), otherwise [`semibold`]. +pub fn tab_title_font(ui: &egui::Ui, size: f32) -> FontId { + let font = tab_font(size); + if ui.ctx().fonts(|f| f.definitions().families.contains_key(&font.family)) { font } else { semibold(size) } +} /// Whether `family` draws semibold text and takes the bold fallback faces. pub(crate) fn is_semibold(family: &FontFamily) -> bool { matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) @@ -516,7 +523,7 @@ pub fn mono(size: f32) -> FontId { } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`], and [`FONT_TAB`] with the condensed face). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -548,9 +555,10 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); let semi = family(semi, &fallback); - let tab = tab_faces(&mut fonts, &semi, condensed); + if let Some(tab) = tab_faces(&mut fonts, &semi, condensed) { + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); + } fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); - fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); @@ -559,28 +567,38 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon /// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first /// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its -/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. -fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { +/// baseline. egui's own faces are listed under their own names, uncopied, as in the semibold +/// family: egui skips some of their characters (the Ubuntu logo, for one) only under those names. +/// `None` without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Option> { let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); - let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); - let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; - let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data))?; + let f = condensed?; + let own = vectorcraft_text::x_height(f.bytes, 0)?; let name = craft_font_name(f); let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); - // `baseline_copies` reads the head of each family it is given: here only this one. + // `baseline_copies` reads the head of each family it is given. `row` also has egui's empty + // Proportional and Monospace families, whose copies are not this family's. + let tab = FontFamily::Name(FONT_TAB.into()); let mut row = FontDefinitions::empty(); row.font_data.insert(name.clone(), Arc::new(head.clone())); - row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + row.families.insert(tab.clone(), vec![name.clone()]); let mut faces = vec![name.clone()]; for face in semi { + if FontDefinitions::builtin_font_names().contains(&face.as_str()) { + faces.push(face.clone()); + continue; + } let Some(data) = fonts.font_data.get(face).cloned() else { continue }; - for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + for (copy, data, _) in + crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data).into_iter().filter(|(_, _, f)| f.contains(&tab)) + { fonts.font_data.insert(copy.clone(), Arc::new(data)); faces.push(copy); } } fonts.font_data.insert(name, Arc::new(head)); - faces + Some(faces) } /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace @@ -831,4 +849,57 @@ mod tests { assert_eq!(ctx.global_style().interaction.tooltip_delay, f32::INFINITY); assert_eq!(ctx.global_style().visuals.window_fill, Tokens::for_brightness(Brightness::Light).panel); } + + /// The face heading the tab family draws an x as tall as the semibold face does, and a + /// character it lacks falls back to the semibold face (drawn at its own 0.92 scale) on its + /// baseline (#8583). The monospace face stands in for craft-fonts' condensed face, which CI's + /// craft-fonts checkout does not have. + #[cfg(feature = "interface-fonts")] + #[test] + fn the_tab_family_keeps_the_semibold_x_height_and_baseline() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut defs = interface_fonts_with(Some(&stand_in)); + assert_eq!(defs.families[&FontFamily::Name(FONT_TAB.into())][0], craft_font_name(&stand_in)); + // The semibold face alone, as it draws a character in its own family. + defs.families.insert(FontFamily::Name("probe".into()), vec!["Inter-SemiBold".to_owned()]); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + ctx.set_fonts(defs); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, Color32::WHITE)).rows[0].glyphs.clone(); + let x = |font: FontId| glyphs("x", font)[0].uv_rect.size.y; + let (x_tab, x_semibold) = (x(tab_font(200.0)), x(semibold(200.0))); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ + // by about 10 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // egui skips some characters of its own faces (the Ubuntu logo, two symbols in its emoji + // face); a tab title draws them as semibold text does. + for c in ['\u{534D}', '\u{5350}', '\u{E0FF}', '\u{EFFD}', '\u{F0FF}', '\u{F200}'] { + let has = |font: FontId| ctx.fonts_mut(|f| f.has_glyph(&font, c)); + let name = format!("U+{:04X}", u32::from(c)); + assert_eq!(has(tab_font(13.0)), has(semibold(13.0)), "{name} has a glyph in a tab title as in semibold text"); + if has(semibold(13.0)) { + // Both families take it from the same fallback face, which draws it at one size. + let size = |font: FontId| glyphs(&c.to_string(), font).first().map(|g| g.uv_rect.size); + assert_eq!(size(tab_font(13.0)), size(semibold(13.0)), "{name} draws at the same size in a tab title as in semibold text"); + } + } + let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; + // U+0182, which Inter has and the monospace face lacks. + let c = 'Ƃ'; + for size in [13.0_f32, 24.0, 40.0, 100.0] { + let own = glyphs(&c.to_string(), FontId::new(size, FontFamily::Name("probe".into()))); + let row = glyphs(&format!("H{c}"), tab_font(size)); + assert_eq!((own.len(), row.len()), (1, 2), "{c} lays out as one glyph"); + // Half a point: one device pixel at 2 pixels per point, for each glyph's rounding. + let drift = (bottom(&row[1]) - row[0].pos.y) - (bottom(&own[0]) - own[0].pos.y); + assert!(drift.abs() <= 0.5, "at {size} pt, {c} ends {drift:.2} pt below the tab family's baseline"); + } + } } diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index cb419067e1..8e2d07ff5c 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -239,7 +239,7 @@ pub(crate) fn baseline_copies(defs: &FontDefinitions, name: &str, data: &FontDat let mut copies: Vec<(String, FontData, Vec)> = vec![]; for (family, stack) in &defs.families { let head = stack.first().and_then(|head| Some((head.as_str(), defs.font_data.get(head)?))); - let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, (*data.font).as_ref(), data.index)); + let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, data)); if let Some((_, _, families)) = copies.iter_mut().find(|(_, copy, _)| copy.tweak.y_offset_factor.to_bits() == shift.to_bits()) { families.push(family.clone()); continue; @@ -266,15 +266,19 @@ fn em_metrics(data: &[u8], index: u32) -> Option<(f32, f32)> { Some((ascent / upem, (ascent - descent + gap) / upem)) } -/// The `y_offset_factor` that puts the glyphs of the face at `index` of `face` on the baseline of -/// the row's first face, whose ascent, row height and offset in ems are `row`. egui draws a -/// fallback glyph's baseline at its face's ascent plus half the difference between the two row -/// heights, so a face with a taller ascent or descent sits off the baseline by the shift computed -/// here, in ems of the font size, limited to half an em either way. -fn baseline_shift(row: (f32, f32, f32), face: &[u8], index: u32) -> f32 { +/// The `y_offset_factor` that puts the glyphs of the fallback face `data` on the baseline of the +/// row's first face, whose ascent, row height and offset in ems are `row`. egui draws a fallback +/// glyph's baseline at its face's ascent plus half the difference between the two row heights, so a +/// face with a taller ascent or descent sits off the baseline by the shift computed here, in ems of +/// the font size, limited to half an em either way. egui scales the face's metrics and its +/// `y_offset_factor` by the face's own `FontTweak` scale, so both are measured at that scale. +fn baseline_shift(row: (f32, f32, f32), data: &FontData) -> f32 { let (row_ascent, row_height, row_offset) = row; - let shift = em_metrics(face, index).map_or(0.0, |(ascent, height)| row_ascent + row_offset - (ascent + 0.5 * (row_height - height))); - if shift.is_finite() { shift.clamp(-0.5, 0.5) } else { 0.0 } + let scale = data.tweak.scale; + let shift = em_metrics((*data.font).as_ref(), data.index) + .map_or(0.0, |(ascent, height)| row_ascent + row_offset - scale * ascent - 0.5 * (row_height - scale * height)); + let factor = if shift.is_finite() { shift.clamp(-0.5, 0.5) / scale } else { 0.0 }; + if factor.is_finite() { factor } else { 0.0 } } /// Call `f` with the text of `shape` and the shapes it holds. @@ -375,8 +379,10 @@ mod tests { fonts.finish(&ctx); frame(&ctx, &mut fonts, "日本語の文字 Layer 1"); if vectorcraft_text::CRAFT_FONTS.is_empty() { + // The condensed tab face is read from its own catalog, so a checkout can give it alone. + let condensed = vectorcraft_text::CONDENSED_UI_FONT.as_ref().map(crate::theme::craft_font_name); let names: Vec = ctx.fonts(|f| f.definitions().font_data.keys().cloned().collect()); - assert!(names.iter().all(|n| !n.starts_with("craft-fonts")), "{names:?}"); + assert!(names.iter().all(|n| !n.starts_with("craft-fonts") || Some(n) == condensed.as_ref()), "{names:?}"); } assert!(has_glyph(&ctx, 'L')); } diff --git a/crates/ui-egui/tests/install_fonts.rs b/crates/ui-egui/tests/install_fonts.rs index d7ebcaab27..56d49bc3bc 100644 --- a/crates/ui-egui/tests/install_fonts.rs +++ b/crates/ui-egui/tests/install_fonts.rs @@ -33,7 +33,8 @@ fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) { fn every_family_the_panels_draw_in_is_bound() { let ctx = context(); frame(&ctx, |ui| { - for font in [theme::semibold(12.0), theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { + let tab = theme::tab_title_font(ui, 12.0); + for font in [theme::semibold(12.0), tab, theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { ui.label(egui::RichText::new("Gaussian Blur").font(font)); } }); @@ -45,6 +46,17 @@ fn every_family_the_panels_draw_in_is_bound() { let installed: Vec<&str> = INTERFACE_FACES.into_iter().filter(|face| definitions.font_data.contains_key(*face)).collect(); let family = |family: FontFamily| definitions.families[&family].clone(); let named = |name: &str| family(FontFamily::Name(name.into())); + // The tab family is bound, headed by craft-fonts' condensed face and followed by the semibold + // faces, when the build has that face and both faces give an x-height to match. + let x_height = |name: &String| definitions.font_data.get(name).and_then(|d| vectorcraft_text::x_height((*d.font).as_ref(), d.index)); + let semibold_head = named(theme::FONT_UI_SEMIBOLD).first().and_then(x_height); + match vectorcraft_text::CONDENSED_UI_FONT.as_ref().filter(|f| vectorcraft_text::x_height(f.bytes, 0).is_some() && semibold_head.is_some()) { + None => assert!(!definitions.families.contains_key(&FontFamily::Name(theme::FONT_TAB.into()))), + Some(f) => { + assert_eq!(named(theme::FONT_TAB)[0], format!("craft-fonts {} {}", f.family, f.style)); + assert!(named(theme::FONT_TAB).len() > named(theme::FONT_UI_SEMIBOLD).len(), "the semibold faces follow the condensed one"); + } + } if cfg!(feature = "interface-fonts") { assert_eq!(installed, INTERFACE_FACES); assert_eq!(named(theme::FONT_UI)[0], "Inter"); diff --git a/docs/development.md b/docs/development.md index 66f925324e..950b996ed9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,8 +178,9 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the x-height of the interface's semibold face, so more tabs fit in the strip. Without - `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab - titles draw in the semibold face. + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), + `theme::FONT_TAB` is not bound and tab titles draw in the semibold family + (`theme::tab_title_font`). - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. @@ -205,7 +206,8 @@ font that has them to each of the families below (`ctx.add_font` with an `Insert family). The panels and dialogs draw in their own egui families (`theme::FONT_UI`, `FONT_UI_SEMIBOLD`, -`FONT_MONO`), and egui panics drawing text in a family no font is bound to. `VectorcraftApp::logic` +`FONT_MONO`, and `FONT_TAB` for document tab titles in builds with the condensed face), and egui +panics drawing text in a family no font is bound to. `VectorcraftApp::logic` binds them on its first frame; an embedder that draws the panels or dialogs without it calls `theme::install_fonts` once on its context, with or without `interface-fonts`. It replaces the context's font definitions, so the embedder's own fonts are added after it. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8b5a9f315a..b6fa3393c1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,7 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`, `theme::tests::the_tab_family_keeps_the_semibold_x_height_and_baseline`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From f3916773e8c35740eab0d674816a5313294d23cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:32:17 -0800 Subject: [PATCH 012/106] JavaScript: release pruned collection storage and follow ES2015 in typed array methods - A collection that removes the holes of a Map or Set releases the room its entries and index held, and a WeakMap or WeakSet whose table has far more room than entries after pruning releases the extra room, so the heap estimate covers what the tables still hold. - %TypedArray%.from throws a TypeError for a receiver that is not a constructor before it reads the source (section 22.2.2.1 step 2). - %TypedArray%.from and of make their result with any constructor they are called on (TypedArrayCreate, section 22.2.4.6): the result must be a typed array with room for every element, or the call is a TypeError. - %TypedArray%.prototype.toLocaleString calls each element's method on the number itself (section 22.2.3.27); Array.prototype.toLocaleString still calls it on the element's object. - ArrayBuffer.prototype.slice and the typed array map, filter, slice and subarray read the receiver's constructor where SpeciesConstructor does (section 7.3.20): a getter's error propagates, and a value that is neither undefined nor an object is a TypeError. filter reads it before its callback runs. - sort charges a unit of fuel for each element it reads and each it writes back, before it starts. - set between typed arrays on different buffers writes each element as it reads it, without holding a copy of the source. - The binary data module comment says a constructor reads a primitive string as a length and from reads it by code point, and a prototype test puts its value at the index it checks. --- crates/js/src/builtins/array.rs | 23 +++++++- crates/js/src/builtins/binary.rs | 94 +++++++++++++++++++++--------- crates/js/src/collections_tests.rs | 90 +++++++++++++++++++++++++++- crates/js/src/heap.rs | 14 +++++ crates/js/src/interp.rs | 61 +++++++++++++++++++ 5 files changed, 251 insertions(+), 31 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 1c91d602b0..f4f2a161bc 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -331,13 +331,26 @@ fn join_item(interp: &mut Interp, v: Value) -> JsResult> { /// An element as `toLocaleString` writes it (section 15.4.4.3). fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, false) +} + +/// An element as `%TypedArray%.prototype.toLocaleString` writes it (ECMA-262 6.0 section +/// 22.2.3.27): the method is called on the element's value, not on its object. +fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, true) +} + +/// Calls the element's `toLocaleString`, looked up on its object, with the value itself as `this` +/// when `on_value` is true and with the object otherwise. +fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; require_callable(interp, &f, "an element's toLocaleString")?; - let s = interp.call(&f, &Value::Object(e), &[])?; + let this = if on_value { v } else { Value::Object(e) }; + let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } @@ -348,10 +361,16 @@ pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } /// `Array.prototype.toLocaleString` (section 15.4.4.3). -pub(super) fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { +fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } +/// `%TypedArray%.prototype.toLocaleString` (ECMA-262 6.0 section 22.2.3.27), the array method +/// with each element's method called on the element's value. +pub(super) fn typed_to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, typed_locale_item)) +} + // ---- methods that change the object ---- /// `Array.prototype.concat` (section 15.4.4.4). diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 8c10723a74..be2fe8258d 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -15,8 +15,9 @@ //! every buffer's bytes are checked against the heap before they are allocated. Every element //! a method visits takes a unit of fuel, and a sort's comparisons take one each. //! -//! The language has no iterators yet, so constructing from an object and `%TypedArray%.from` -//! read an array, a string (by code point) or an object with a `length`, by index. +//! The language has no iterators yet, so constructing from an object reads an array or an object +//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A +//! constructor given a primitive string reads it as a length. use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; use super::{arg, array, data, method, native, require_callable, to_integer}; @@ -462,12 +463,24 @@ fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsRes Ok(r as usize) } +/// The `constructor` steps of SpeciesConstructor (section 7.3.20): reads `o.constructor` and +/// throws a `TypeError` when it is neither `undefined` nor an object. The language has no +/// `@@species`, so the result is always made with the intrinsic constructor. +fn species_check(interp: &mut Interp, o: ObjId, name: &str) -> JsResult<()> { + let c = interp.get_from(o, &key("constructor"), &Value::Object(o))?; + if matches!(c, Value::Undefined | Value::Object(_)) { + return Ok(()); + } + Err(interp.type_error(&format!("{name}: the constructor property is not an object"))) +} + /// `ArrayBuffer.prototype.slice` (section 24.1.4.3). fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let o = this_buffer(interp, &this, "slice")?; let len = buffer_len(interp, o); let first = relative(interp, &arg(args, 0), len, 0)?; let last = relative(interp, &arg(args, 1), len, len)?; + species_check(interp, o, "ArrayBuffer.prototype.slice")?; let count = last.saturating_sub(first); // Each copied byte takes a unit of fuel, charged before the copy is made. for _ in 0..count { @@ -705,21 +718,31 @@ typed_ctors! { float64_ctor, Float64; } -/// The element type of the typed array constructor `this`, as `from` and `of` need. -fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { +/// TypedArrayCreate (section 22.2.4.6), as `from` and `of` need: a new typed array of `len` +/// elements made by the constructor `c`. One of the nine typed array constructors makes it +/// directly; any other constructor is called, and its result must be a typed array with at +/// least `len` elements. +fn typed_create(interp: &mut Interp, c: &Value, len: u64, name: &str) -> JsResult<(ObjId, View)> { let ctors = interp.intrinsics.es2015.typed_ctors; - if let Some(o) = this.as_object() - && let Some(i) = ctors.iter().position(|c| *c == o) - && let Some(elem) = Elem::ALL.get(i) - { - return Ok(*elem); - } - Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) + let elem = c.as_object().and_then(|o| ctors.iter().position(|t| *t == o)).and_then(|i| Elem::ALL.get(i).copied()); + let ta = match elem { + Some(elem) => new_typed(interp, elem, len)?, + None => { + #[allow(clippy::cast_precision_loss)] + let made = interp.construct(c, &[Value::Number(len as f64)])?; + match made.as_object() { + Some(o) if view_of(interp, o).is_some_and(|v| v.length as u64 >= len) => o, + _ => return Err(interp.type_error(&format!("TypedArray.{name}: the constructor did not make a typed array long enough"))), + } + } + }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + Ok((ta, view)) } /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - if !interp.is_callable(&this) { + if !interp.is_constructor(&this) { return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); } let map_fn = arg(args, 1); @@ -734,9 +757,7 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe let src = interp.to_object(&source)?; let src_value = Value::Object(src); let len = length_of(interp, src)?; - let elem = ctor_elem(interp, &this, "from")?; - let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + let (ta, view) = interp.rooted(std::slice::from_ref(&src_value), |interp| typed_create(interp, &this, len, "from"))?; return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { for i in 0..len { interp.use_fuel()?; @@ -760,10 +781,8 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe }); let result = gathered.and_then(|()| { let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let elem = ctor_elem(interp, &this, "from")?; - let ta = new_typed(interp, elem, items.len() as u64)?; + let (ta, view) = typed_create(interp, &this, items.len() as u64, "from")?; interp.temp_roots.push(Value::Object(ta)); - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; for (i, item) in items.into_iter().enumerate() { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] @@ -780,9 +799,10 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let (ta, view) = typed_create(interp, &this, args.len() as u64, "of")?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { interp.use_fuel()?; @@ -862,7 +882,7 @@ generic_methods! { ta_reduce, "reduce", array::reduce; ta_reduce_right, "reduceRight", array::reduce_right; ta_reverse, "reverse", array::reverse; - ta_to_locale_string, "toLocaleString", array::to_locale_string; + ta_to_locale_string, "toLocaleString", array::typed_to_locale_string; } fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { @@ -927,10 +947,11 @@ fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "map")?; + let (o, view) = this_typed(interp, &this, "map")?; let f = arg(args, 0); require_callable(interp, &f, "the callback")?; let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.map")?; let out = new_typed(interp, view.elem, view.length as u64)?; let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(out)], |interp| { @@ -958,10 +979,11 @@ fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResul /// `filter` (section 22.2.3.9). fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "filter")?; + let (o, view) = this_typed(interp, &this, "filter")?; let f = arg(args, 0); require_callable(interp, &f, "the callback")?; let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.filter")?; let mut held = crate::interp::HeldBytes::new(interp); let mut kept = Vec::new(); for i in 0..view.length { @@ -981,10 +1003,11 @@ fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult /// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "slice")?; + let (o, view) = this_typed(interp, &this, "slice")?; let start = relative(interp, &arg(args, 0), view.length, 0)?; let end = relative(interp, &arg(args, 1), view.length, view.length)?; let count = end.saturating_sub(start); + species_check(interp, o, "TypedArray.prototype.slice")?; let out = new_typed(interp, view.elem, count as u64)?; let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; copy_elements(interp, &view, start, &dst, 0, count)?; @@ -993,9 +1016,10 @@ fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< /// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "subarray")?; + let (o, view) = this_typed(interp, &this, "subarray")?; let begin = relative(interp, &arg(args, 0), view.length, 0)?; let end = relative(interp, &arg(args, 1), view.length, view.length)?; + species_check(interp, o, "TypedArray.prototype.subarray")?; interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; let proto = typed_proto(interp, view.elem); @@ -1004,8 +1028,8 @@ fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu /// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like /// object's elements converted with ToNumber, starting at `offset`. A source that does not fit -/// is a `RangeError`. A typed array source is read in full before anything is written, so a -/// source on the same buffer copies correctly. +/// is a `RangeError`. A typed array source on the same buffer is read in full before anything is +/// written, so it copies correctly. fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (_, view) = this_typed(interp, &this, "set")?; let offset = to_integer(interp, &arg(args, 1))?; @@ -1033,6 +1057,16 @@ fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult = (0..view.length).map(|i| at(interp, &view, i)).collect(); merge_sort(interp, &mut values, &compare)?; for (i, n) in values.into_iter().enumerate() { diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index 7c00b29532..a5180291e6 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -236,6 +236,36 @@ fn a_collection_removes_holes_and_moves_live_iterators() { assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); } +#[test] +fn a_collection_releases_the_storage_of_removed_entries() { + let mut realm = realm(); + realm + .run( + "var m = new Map(), wm = new WeakMap(), kept = {}; + for (var i = 0; i < 1000; i++) m.set(i, i); + m.clear(); m.set('a', 1); + (function () { for (var i = 0; i < 1000; i++) wm.set({}, i); })(); + wm.set(kept, 1);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + let wm = global_object(&mut realm, "wm"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => { + let (entries, index) = c.capacity(); + assert_eq!(c.slots(), 1); + assert!(entries < 64 && index < 64, "{entries} {index}"); + } + _ => panic!("not a Map"), + } + match realm.interp().heap.object(wm).map(|o| &o.class) { + Some(Class::WeakMap(w)) => assert!(w.entries.len() == 1 && w.entries.capacity() < 64, "{}", w.entries.capacity()), + _ => panic!("not a WeakMap"), + } + assert_eq!(realm.run("m.get('a') + wm.get(kept)").unwrap(), JsValue::Number(2.0)); +} + // ---- ArrayBuffer ---- #[test] @@ -319,7 +349,7 @@ fn numeric_names_are_elements_or_nothing() { truth( "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", ); - truth("Int8Array.prototype[0] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[0]; r"); + truth("Int8Array.prototype[3] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[3]; r"); truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. truth( @@ -378,6 +408,14 @@ fn typed_array_methods() { truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + // A typed array calls each element's toLocaleString on the number (section 22.2.3.27); an array + // calls it on the element's object (section 15.4.4.3). + assert_eq!( + string( + "Number.prototype.toLocaleString = function () { 'use strict'; return typeof this; }; new Uint8Array([7, 8]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number,number;object" + ); truth( "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", ); @@ -388,6 +426,19 @@ fn typed_array_methods() { throws("Int8Array.from.call({}, [1])", "TypeError"); // The source's length is read before the constructor is checked to be a typed array's. throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). + throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); + // Any other constructor makes the result (TypedArrayCreate, section 22.2.4.6), which must be a + // typed array with room for every element. + truth( + "var lens = []; function C(n) { lens.push(n); return new Int16Array(n + 1); } \ + var a = Uint8Array.from.call(C, [300, 2]), b = Int8Array.of.call(C, 7), c = Int8Array.from.call(C, 'xy', function (v) { return v.length; }); \ + a instanceof Int16Array && a.join() === '300,2,0' && b.join() === '7,0' && c.join() === '1,1,0' && lens.join() === '2,1,2'", + ); + truth("var B = Int8Array.bind(null); Int8Array.of.call(B, 1, 2).join() === '1,2'"); + throws("Int8Array.from.call(function () { return new Int8Array(1); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(function () {}, 1)", "TypeError"); + throws("Int8Array.of.call(Math.max, 1)", "TypeError"); truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); // A copy to the same element type keeps every bit, a signaling NaN's included. truth( @@ -398,6 +449,30 @@ fn typed_array_methods() { new DataView(g.buffer).getUint32(8, true) === 0x7f800001", ); assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); + assert_eq!( + string("var b = new ArrayBuffer(4); var a = new Int8Array(b); a.set([1, 2]); new Uint16Array(b).set(a.subarray(0, 2)); a.join()"), + "1,0,2,0" + ); + assert_eq!(string("var a = new Int8Array(3); a.set(new Uint8Array([200, 1]), 1); a.join()"), "0,-56,1"); +} + +#[test] +fn derived_buffers_and_typed_arrays_read_the_constructor_first() { + // SpeciesConstructor (section 7.3.20) reads `constructor` before the result is made, and + // before filter's callback runs. + for call in ["a.slice()", "a.subarray(0)", "a.map(function (v) { return v; })", "a.filter(function () { n++; })", "a.buffer.slice(0)"] { + let getter = format!( + "var n = 0; var a = new Int8Array([1, 2]); var g = {{get: function () {{ throw new RangeError('c'); }}}}; \ + Object.defineProperty(a, 'constructor', g); Object.defineProperty(a.buffer, 'constructor', g); {call}" + ); + throws(&getter, "RangeError"); + throws(&format!("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; a.buffer.constructor = null; {call}"), "TypeError"); + } + truth("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; try { a.filter(function () { n++; }); } catch (e) {} n === 0"); + truth( + "var a = new Int8Array([1, 2]); a.constructor = undefined; a.buffer.constructor = undefined; a.slice().join() === '1,2' && a.subarray(1)[0] === 2 && a.buffer.slice(1).byteLength === 1", + ); + truth("var a = new Int8Array([1, 2]); a.constructor = Array; a.map(function (v) { return v; }) instanceof Int8Array"); } #[test] @@ -409,4 +484,17 @@ fn typed_array_work_takes_fuel() { assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); + // A sort of 2^16 equal elements makes 2^19 comparisons, and reading and writing back its + // elements takes 2^17 units more. + let sort = "new Uint8Array(1 << 16).sort(); 'sorted'"; + assert_eq!(limit(&Limits { fuel: 600_000, ..Limits::default() }, sort), LimitKind::Fuel); + let mut enough = Realm::with_options(es2015(), Limits { fuel: 700_000, ..Limits::default() }); + assert_eq!(enough.run(sort).unwrap(), JsValue::String("sorted".into())); +} + +#[test] +fn a_copy_between_buffers_holds_no_snapshot() { + let mut realm = Realm::with_options(es2015(), Limits { heap_bytes: 6 << 20, ..Limits::default() }); + let r = realm.run("var a = new Uint8Array(1 << 20), b = new Int8Array(1 << 20); a[5] = 200; b.set(a); b[5]"); + assert_eq!(r.unwrap(), JsValue::Number(-56.0)); } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 4aed4b9c9b..e3aa6a6240 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -374,11 +374,20 @@ impl Coll { } moved.push(live); self.entries.retain(Option::is_some); + // The storage the holes held is released along with their charge. + self.entries.shrink_to_fit(); + self.index.shrink_to_fit(); for slot in self.index.values_mut() { *slot = moved.get(*slot).copied().unwrap_or(*slot); } moved } + + /// The positions the entries and the index have room for, for tests. + #[cfg(test)] + pub(crate) fn capacity(&self) -> (usize, usize) { + (self.entries.capacity(), self.index.capacity()) + } } /// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are @@ -777,6 +786,11 @@ impl Heap { && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class { w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + // Only the entries left are charged, and a table with far more room than entries + // releases the extra room. + if w.entries.capacity() > 2 * w.entries.len() + 16 { + w.entries.shrink_to_fit(); + } live += WEAK_ENTRY_BYTES * w.entries.len(); } } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b90c354347..3f15d6adda 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2239,6 +2239,20 @@ impl Interp { v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_))) } + /// Whether `new` can construct with `v` (section 7.2.4): a function written in JavaScript, a + /// built-in constructor, or a bound function whose target is one, as `op_new` accepts. + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut f = v.as_object(); + while let Some(o) = f { + match self.heap.object(o).map(|o| &o.class) { + Some(Class::Function(Func::Closure { .. } | Func::Native { constructor: true, .. })) => return true, + Some(Class::Function(Func::Bound { target, .. })) => f = Some(*target), + _ => return false, + } + } + false + } + fn func_of(&self, v: &Value) -> Option { match &self.heap.object(v.as_object()?)?.class { Class::Function(f) => Some(f.clone()), @@ -2580,6 +2594,53 @@ impl Interp { r } + /// Constructs with `f` as `new f(...args)` does (`[[Construct]]`, sections 13.2.2 and + /// 15.3.4.5.2), for a built-in that constructs with a value it is given. + pub(crate) fn construct(&mut self, f: &Value, args: &[Value]) -> JsResult { + if self.reentry >= self.limits.reentry { + return Err(Abrupt::Limit(LimitKind::Reentry)); + } + let saved = self.stack.len(); + self.stack.push(f.clone()); + self.stack.extend(args.iter().cloned()); + self.reentry += 1; + let r = self.construct_rooted(f.clone(), args.to_vec(), saved); + self.reentry -= 1; + self.stack.truncate(saved); + r + } + + fn construct_rooted(&mut self, mut f: Value, mut args: Vec, saved: usize) -> JsResult { + // The bound function on the stack keeps its arguments reachable. + while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { + self.use_fuel()?; + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + f = Value::Object(target); + } + match self.func_of(&f) { + Some(Func::Closure { code, env }) => { + let Some(callee) = f.as_object() else { return internal("callee is not an object") }; + let proto = match self.get_from(callee, &key("prototype"), &f)? { + Value::Object(p) => p, + _ => self.intrinsics.object_proto, + }; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + self.stack.truncate(saved); + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args }, Some(obj), true)?; + self.execute() + } + Some(Func::Native { f: native, constructor: true, .. }) => { + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + r + } + _ => Err(self.type_error("the value is not a constructor")), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), From 287dd7230929f5b04f98b4fcd572602283b3a401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:51:57 -0800 Subject: [PATCH 013/106] JavaScript: typed array from and of take only the typed array constructors %TypedArray%.from and of make their result with AllocateTypedArray in the 6th edition (sections 22.2.2.1.1, 22.2.2.2 and 22.2.1.2.1), which looks for a typed array constructor on the receiver's prototype chain and throws a TypeError when it finds none. A function that returns a typed array, or a bound typed array constructor, is refused again instead of being called. Later editions call the receiver through TypedArrayCreate. --- crates/js/src/builtins/binary.rs | 43 ++++++++++++--------------- crates/js/src/collections_tests.rs | 15 +++------- crates/js/src/interp.rs | 47 ------------------------------ 3 files changed, 22 insertions(+), 83 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index be2fe8258d..2e87c889c8 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -718,26 +718,16 @@ typed_ctors! { float64_ctor, Float64; } -/// TypedArrayCreate (section 22.2.4.6), as `from` and `of` need: a new typed array of `len` -/// elements made by the constructor `c`. One of the nine typed array constructors makes it -/// directly; any other constructor is called, and its result must be a typed array with at -/// least `len` elements. -fn typed_create(interp: &mut Interp, c: &Value, len: u64, name: &str) -> JsResult<(ObjId, View)> { +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { let ctors = interp.intrinsics.es2015.typed_ctors; - let elem = c.as_object().and_then(|o| ctors.iter().position(|t| *t == o)).and_then(|i| Elem::ALL.get(i).copied()); - let ta = match elem { - Some(elem) => new_typed(interp, elem, len)?, - None => { - #[allow(clippy::cast_precision_loss)] - let made = interp.construct(c, &[Value::Number(len as f64)])?; - match made.as_object() { - Some(o) if view_of(interp, o).is_some_and(|v| v.length as u64 >= len) => o, - _ => return Err(interp.type_error(&format!("TypedArray.{name}: the constructor did not make a typed array long enough"))), - } - } - }; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - Ok((ta, view)) + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). @@ -757,7 +747,9 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe let src = interp.to_object(&source)?; let src_value = Value::Object(src); let len = length_of(interp, src)?; - let (ta, view) = interp.rooted(std::slice::from_ref(&src_value), |interp| typed_create(interp, &this, len, "from"))?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { for i in 0..len { interp.use_fuel()?; @@ -781,8 +773,10 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe }); let result = gathered.and_then(|()| { let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let (ta, view) = typed_create(interp, &this, items.len() as u64, "from")?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; for (i, item) in items.into_iter().enumerate() { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] @@ -799,10 +793,9 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - if !interp.is_constructor(&this) { - return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); - } - let (ta, view) = typed_create(interp, &this, args.len() as u64, "of")?; + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { interp.use_fuel()?; diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index a5180291e6..3fe01a3327 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -428,17 +428,10 @@ fn typed_array_methods() { throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); - // Any other constructor makes the result (TypedArrayCreate, section 22.2.4.6), which must be a - // typed array with room for every element. - truth( - "var lens = []; function C(n) { lens.push(n); return new Int16Array(n + 1); } \ - var a = Uint8Array.from.call(C, [300, 2]), b = Int8Array.of.call(C, 7), c = Int8Array.from.call(C, 'xy', function (v) { return v.length; }); \ - a instanceof Int16Array && a.join() === '300,2,0' && b.join() === '7,0' && c.join() === '1,1,0' && lens.join() === '2,1,2'", - ); - truth("var B = Int8Array.bind(null); Int8Array.of.call(B, 1, 2).join() === '1,2'"); - throws("Int8Array.from.call(function () { return new Int8Array(1); }, [1, 2])", "TypeError"); - throws("Int8Array.of.call(function () {}, 1)", "TypeError"); - throws("Int8Array.of.call(Math.max, 1)", "TypeError"); + // A constructor that is not a typed array's is refused (AllocateTypedArray, section 22.2.1.2.1), + // a function that returns a typed array and a bound typed array constructor included. + throws("Int8Array.from.call(function () { return new Int8Array(2); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(Int8Array.bind(null), 1)", "TypeError"); truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); // A copy to the same element type keeps every bit, a signaling NaN's included. truth( diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3f15d6adda..b5cf225517 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2594,53 +2594,6 @@ impl Interp { r } - /// Constructs with `f` as `new f(...args)` does (`[[Construct]]`, sections 13.2.2 and - /// 15.3.4.5.2), for a built-in that constructs with a value it is given. - pub(crate) fn construct(&mut self, f: &Value, args: &[Value]) -> JsResult { - if self.reentry >= self.limits.reentry { - return Err(Abrupt::Limit(LimitKind::Reentry)); - } - let saved = self.stack.len(); - self.stack.push(f.clone()); - self.stack.extend(args.iter().cloned()); - self.reentry += 1; - let r = self.construct_rooted(f.clone(), args.to_vec(), saved); - self.reentry -= 1; - self.stack.truncate(saved); - r - } - - fn construct_rooted(&mut self, mut f: Value, mut args: Vec, saved: usize) -> JsResult { - // The bound function on the stack keeps its arguments reachable. - while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { - self.use_fuel()?; - let mut all = bound_args.to_vec(); - all.append(&mut args); - args = all; - f = Value::Object(target); - } - match self.func_of(&f) { - Some(Func::Closure { code, env }) => { - let Some(callee) = f.as_object() else { return internal("callee is not an object") }; - let proto = match self.get_from(callee, &key("prototype"), &f)? { - Value::Object(p) => p, - _ => self.intrinsics.object_proto, - }; - let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); - self.stack.truncate(saved); - self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args }, Some(obj), true)?; - self.execute() - } - Some(Func::Native { f: native, constructor: true, .. }) => { - let held = self.held_bytes; - let r = native(self, Value::Undefined, &args, true); - self.held_bytes = held; - r - } - _ => Err(self.type_error("the value is not a constructor")), - } - } - fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), From abb1fa5f5765caaaf93308175fea5f4b178ddcad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:02:26 -0800 Subject: [PATCH 014/106] JavaScript: typed array toLocaleString looks its method up with the number as receiver %TypedArray%.prototype.toLocaleString invokes each element's method (Invoke, section 7.3.18), so a getter for toLocaleString on Number.prototype now gets the number as this, as the call already does. Array.prototype.toLocaleString keeps the element's object for both. --- crates/js/src/builtins/array.rs | 9 +++++---- crates/js/src/collections_tests.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index f4f2a161bc..9b7ca4bfa5 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -340,16 +340,17 @@ fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { locale_call(interp, v, true) } -/// Calls the element's `toLocaleString`, looked up on its object, with the value itself as `this` -/// when `on_value` is true and with the object otherwise. +/// Calls the element's `toLocaleString`, looked up on its object. With `on_value`, the value +/// itself is `this` for the lookup's getter and for the call (Invoke, section 7.3.18); otherwise +/// the object is. fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; - let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; - require_callable(interp, &f, "an element's toLocaleString")?; let this = if on_value { v } else { Value::Object(e) }; + let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &this)?; + require_callable(interp, &f, "an element's toLocaleString")?; let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index 3fe01a3327..62bf45e03b 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -416,6 +416,14 @@ fn typed_array_methods() { ), "number,number;object" ); + // A getter for the method gets the number as `this` too (Invoke, section 7.3.18). + assert_eq!( + string( + "Object.defineProperty(Number.prototype, 'toLocaleString', {get: function () { 'use strict'; var t = typeof this; \ + return function () { return t; }; }}); new Uint8Array([7]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number;object" + ); truth( "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", ); From add7c0f48bf5f4202e58a12c3e1dfe928008202b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:42:05 -0800 Subject: [PATCH 015/106] Toolbars: a toolbar made with New Toolbar holds menu command buttons A toolbar made with Window > Toolbars > New Toolbar held tools only. Its Add Tool... menu now ends in an Add Command submenu that searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels); a pick adds a button after the tools, and Remove Command in the same menu lists the buttons by their full names and takes one off. - A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in an ellipsis opens its dialog; while the item is dimmed, the button is dimmed and a click runs nothing and the status line says why. - Each command is asked whether it can run once per app state, at most 12 in a frame, and again on a click or a key press. - The button's context menu has Move Up, Move Down and Remove from Toolbar. - The buttons are saved with the toolbar (`commands`, left out when empty, so older layouts load unchanged), and Manage Toolbars' copy keeps them. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. - `toolbar.addCommand {command, toolbar, at?}` adds or moves a button, `toolbar.removeCommand {command, toolbar}` takes one off, and `window.toolbar.list` reports `commands`. `toolbar.reset` with `toolbar` clears them along with the tools. A UI command that fails without params, such as `toolbar.addTool`, is not listed and cannot be added. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons. Command buttons are VectorCraft's own. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 14 +- crates/ui-egui/src/custom_toolbars.rs | 363 ++++++++++++++++++++++- crates/ui-egui/src/edit_toolbar.rs | 6 +- crates/ui-egui/src/edit_toolbar/tests.rs | 240 ++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 14 +- crates/ui-egui/src/palette.rs | 72 ++++- crates/ui-egui/src/palette/search.rs | 11 +- crates/ui-egui/src/shortcut_editor.rs | 10 + crates/ui-egui/src/state.rs | 5 + docs/control-protocol.md | 13 +- docs/mcp.md | 20 ++ docs/target-app-parity.md | 1 + 12 files changed, 748 insertions(+), 21 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..d3fce19fda 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -613,6 +613,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -671,7 +683,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 2b70748c9c..72edd613ae 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -3,9 +3,12 @@ //! All Tools drawer beside it, and tools dragged from the drawer fill it (`edit_toolbar`, with the //! `toolbar` param of its commands). The + button above it opens Add Tool…, a menu of every tool //! where a click adds the tool at the end, and whose Remove Tool items take tools out: VectorCraft's -//! own way to fill a toolbar without a drag. Its title bar moves it, its × hides it and its double -//! arrow shows its tools in one column or two. Each toolbar is listed under Window › Toolbars, where its -//! item shows or hides it, and is kept with the workspace it was made in (`Workspace::toolbars`). +//! own way to fill a toolbar without a drag. The same menu's Add Command submenu searches the Command +//! Palette's results and adds a command button after the tools, which runs what the command's menu +//! item runs (`toolbar.addCommand`, `toolbar.removeCommand`); command buttons are VectorCraft's own. +//! Its title bar moves it, its × hides it and its double arrow shows its tools in one column or +//! two. Each toolbar is listed under Window › Toolbars, where its item shows or hides it, and is +//! kept with the workspace it was made in (`Workspace::toolbars`). //! Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, copies and deletes them. //! //! A toolbar docks in a lane along the window's left or right edge (on the left, right of the Tools @@ -42,6 +45,8 @@ use crate::{VectorcraftApp, icons, widgets}; pub(crate) const MAX: usize = 64; /// The most characters a toolbar's name has. const MAX_NAME: usize = 200; +/// The most command buttons a toolbar holds. +const MAX_COMMANDS: usize = 200; /// Width of a toolbar of one column of tool buttons, inside its border. const WIDTH: f32 = 44.0; /// Width a second column of tool buttons adds. @@ -129,6 +134,7 @@ pub(crate) fn create(ui: &mut UiState, name: &str) -> Result { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }); show_alone_after_tab(ui, name); Ok(name.to_string()) @@ -333,8 +339,10 @@ pub(crate) fn delete(ui: &mut UiState, ctx: Option<&egui::Context>, name: &str) /// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of /// known tools, each once in its toolbar, at a position that is a number, with one strip per group -/// torn off them, each group's tool chosen last only when the group holds it, and the docked ones -/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). +/// torn off them, each group's tool chosen last only when the group holds it, at most +/// [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and the docked ones +/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). A command that is +/// not known now stays: it may be an uninstalled plug-in's. pub(crate) fn sanitize(bars: &mut Vec) { let mut names = std::collections::BTreeSet::new(); bars.retain_mut(|b| { @@ -344,6 +352,9 @@ pub(crate) fn sanitize(bars: &mut Vec) { s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone())); } b.slots.retain(|s| !s.is_empty()); + let mut commands = std::collections::BTreeSet::new(); + b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone())); + b.commands.truncate(MAX_COMMANDS); let slots = &b.slots; b.slot_tool.retain(|first, id| slots.iter().any(|s| s.first() == Some(first) && s.contains(id))); crate::state::FloatingFlyout::sanitize(&mut b.floating); @@ -371,6 +382,41 @@ pub(crate) fn keep_strips(bar: &mut CustomToolbar) { }); } +/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names, +/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only. +fn command_target(ui: &UiState, p: &Value) -> Result { + let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?; + index(ui, &name) +} + +/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there +/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command +/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI +/// command that fails without params, can't be added. +pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option) -> Result<(), String> { + if id.starts_with("tool:") { + return Err(format!("`{id}` is a tool: toolbar.addTool adds tools")); + } + if crate::shortcut_editor::ui_command_needs_params(id) { + return Err(format!("`{id}` needs params, which a click on a button does not give")); + } + if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) { + return Err(format!("unknown command `{id}`")); + } + let mut list: Vec = bar.commands.iter().filter(|c| *c != id).cloned().collect(); + if list.len() >= MAX_COMMANDS { + return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands")); + } + let at = match at { + None => list.len(), + Some(n) if n <= list.len() => n, + Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())), + }; + list.insert(at, id.to_string()); + bar.commands = list; + Ok(()) +} + /// The commands of the toolbars made with New Toolbar; `None` for other ids. pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { Some(match id { @@ -464,13 +510,30 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?), + }; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + add_command(bar, id, at).map(|_| json!(bar.commands)) + })(), + "toolbar.removeCommand" => (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + bar.commands.retain(|c| c != id); + Ok(json!(bar.commands)) + })(), "window.toolbar.list" => Ok(json!( app.ui .custom_toolbars .iter() .map(|b| { let side = if b.dock_right { "right" } else { "left" }; - json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "floating": b.dock.is_none(), "side": side, "order": b.dock}) + json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "commands": b.commands, "floating": b.dock.is_none(), "side": side, "order": b.dock}) }) .collect::>() )), @@ -730,6 +793,130 @@ enum Action { Dock(String, bool), /// Float Toolbar in the title bar's context menu. Float(String), + /// A click on a command button: the Command Palette result it runs. + RunCommand(String), + /// A command picked in the Add Command submenu of Add Tool…'s menu, added at the end of the + /// toolbar named. + AddCommand(String, String), + /// A command button moved to another place among the toolbar's command buttons (Move Up and + /// Move Down in its context menu). + MoveCommand(String, String, usize), + /// A command taken out of the toolbar named: Remove Command in Add Tool…'s menu, or Remove + /// from Toolbar in the button's context menu. + RemoveCommand(String, String), +} + +/// What a command button shows, worked out before its toolbar is drawn. +#[derive(Clone, Debug)] +struct CommandLook { + /// The Command Palette result it runs. + id: String, + /// Its label, name and shortcut; none while the palette lists no result with its id (an + /// uninstalled plug-in's command). + text: Option, + /// Why it can't run now, in English; none while it can. + why: Option, +} + +impl CommandLook { + /// The label the button shows: the command's, or its id while the command is gone. + fn label(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str()) + } + + /// Its full name, with the menu path that tells it apart from a command of the same label, or + /// its id while the command is gone. + fn name(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str()) + } +} + +/// The most commands the toolbars ask in one frame whether they can run. An engine check can take +/// tens of milliseconds on a large selection, and during a drag the state changes on every frame. +const ASKS_PER_FRAME: usize = 12; + +/// The command buttons' [`crate::palette::unavailable`] answers for the state `key` they were read +/// in ([`crate::palette::availability_key`]): each command is asked once per state, and at most +/// [`ASKS_PER_FRAME`] are asked in a frame. A command not asked yet in this state shows its answer +/// from an earlier state (`stale`), or is dimmed when it has none, and is asked in a later frame. +#[derive(Clone, Default)] +struct Known { + key: u64, + why: std::collections::HashMap>, + stale: std::collections::HashMap>, + /// How many more commands this frame may ask. + budget: usize, + /// Is a command still waiting to be asked in this state? + pending: bool, +} + +impl Known { + /// The answers for the state now. The state leaves out a panel shown and a tool chosen, so a + /// frame with a pointer button release or a key press asks every command again, as the Command + /// Palette asks its results again on a click. + fn load(app: &VectorcraftApp, ctx: &egui::Context) -> Known { + let key = crate::palette::availability_key(app); + let mut known = ctx.data(|d| d.get_temp::(known_id())).unwrap_or_default(); + let again = ctx.input(|i| { + i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: true, .. })) + }); + if known.key != key || again { + let old = std::mem::take(&mut known.why); + known.stale.extend(old); + known.key = key; + } + known.budget = ASKS_PER_FRAME; + known.pending = false; + known + } + + /// Why the result `id`, shown as `name`, can't run now, in English, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, id: &str, name: &str) -> Option { + if let Some(why) = self.why.get(id) { + return why.clone(); + } + if self.budget == 0 { + // Dimmed until it is asked, unless an earlier state's answer is known. + self.pending = true; + return self.stale.get(id).cloned().unwrap_or_else(|| Some(format!("checking whether `{id}` can run"))); + } + self.budget -= 1; + let why = crate::palette::unavailable(app, id, name); + self.stale.remove(id); + self.why.insert(id.to_string(), why.clone()); + why + } +} + +fn known_id() -> egui::Id { + egui::Id::unique("custom-toolbar-command-availability") +} + +/// How many commands have their answer for the state now, and is one still waiting to be asked? +#[cfg(test)] +pub(crate) fn asked(ctx: &egui::Context) -> (usize, bool) { + ctx.data(|d| d.get_temp::(known_id())).map_or((0, false), |k| (k.why.len(), k.pending)) +} + +/// How each command button of `bar` looks now, its answers kept in `known` (read for the current +/// state the first time a toolbar with command buttons is drawn in a frame). +fn command_looks(app: &VectorcraftApp, ctx: &egui::Context, bar: &CustomToolbar, known: &mut Option) -> Vec { + if bar.commands.is_empty() { + return vec![]; + } + let known = known.get_or_insert_with(|| Known::load(app, ctx)); + let native = app.services.native_menu.is_some(); + bar.commands + .iter() + .map(|id| { + let text = crate::palette::is_command(id).then(|| crate::palette::button_text(ctx, native, id)).flatten(); + let why = match &text { + None => Some(format!("command `{id}` is not available right now")), + Some(t) => known.why(app, id, &t.name), + }; + CommandLook { id: id.clone(), text, why } + }) + .collect() } /// The lane along the window's right edge (true) or left edge where docked toolbars show, as last @@ -1001,9 +1188,14 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Where the drawer opens (the toolbar's bounds and its ••• button): beside the toolbar it // edits, or beside the one whose ••• button was just clicked. let (mut anchor, mut clicked_anchor) = (None, None); + let mut known = None; + let native = app.services.native_menu.is_some(); for k in 0..app.ui.custom_toolbars.len() { let Some(bar) = app.ui.custom_toolbars.get(k).filter(|b| b.shown).cloned() else { continue }; let id = area_id(&bar.name); + let looks = command_looks(app, ctx, &bar, &mut known); + // Add Tool…'s menu lists them under Remove Command and searches the commands it can add. + ctx.data_mut(|d| d.insert_temp(add_menu_id(&bar.name).with("commands"), (native, looks.clone()))); let cols = if bar.double { 2 } else { 1 }; let width = WIDTH + BUTTON * (cols - 1) as f32; // Docked: where its lane puts it, its tools scrolling in its share of the lane, or only its @@ -1137,6 +1329,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // The command buttons, after its tools. + command_buttons(ui, &t, width - 6.0, middle, &bar.name, &looks, &mut actions); ui.add_space(4.0); // Add Tool…: a menu of the tools, which adds one to this toolbar or takes one out. let add = ui.vertical_centered(|ui| widgets::icon_button(ui, "plus", "Add Tool…", false, 26.0)).inner; @@ -1182,6 +1376,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } } + if let Some(known) = known { + // The commands not asked yet are asked in the next frames. + if known.pending { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(known_id(), known)); + } if let Some((bounds, button)) = clicked_anchor.or(anchor) { ctx.data_mut(|d| { d.insert_temp(crate::edit_toolbar::toolbar_id(), bounds); @@ -1245,6 +1446,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.status(e); } } + a @ (Action::RunCommand(_) | Action::AddCommand(..) | Action::MoveCommand(..) | Action::RemoveCommand(..)) => command_action(app, a), } } end_move(); @@ -1369,6 +1571,143 @@ pub(crate) fn shown_tool(bar: &CustomToolbar, active: &'static str, tools: &[&'s Some(bar.slot_tool.get(first).and_then(|id| tools.iter().copied().find(|t| t == id)).unwrap_or(first)) } +/// What a press on a command button, its context menu or Add Tool…'s command rows did. +fn command_action(app: &mut VectorcraftApp, a: Action) { + let done = match a { + // It runs what the command's menu item runs, as a pick in the Command Palette does: a + // command whose item ends in … opens its dialog, and a dimmed one runs nothing and the + // status line says why. + Action::RunCommand(id) if crate::palette::is_command(&id) => { + crate::palette::run_pick(app, &id); + Ok(Value::Null) + } + Action::RunCommand(id) => Err(format!("command `{id}` is not available right now")), + Action::AddCommand(name, id) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name })), + Action::MoveCommand(name, id, at) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name, "at": at })), + Action::RemoveCommand(name, id) => app.run("toolbar.removeCommand", json!({ "command": id, "toolbar": name })), + _ => Ok(Value::Null), + }; + if let Err(e) = done { + app.status(e); + } +} + +/// The command buttons of the toolbar named `bar` (`looks`), one per row across its `width`, with +/// `middle` the toolbar's middle: [`command_button`]. +fn command_buttons(ui: &mut egui::Ui, t: &Tokens, width: f32, middle: f32, bar: &str, looks: &[CommandLook], actions: &mut Vec) { + if looks.is_empty() { + return; + } + ui.add_space(4.0); + for (i, look) in looks.iter().enumerate() { + ui.horizontal(|ui| { + ui.add_space((middle - width / 2.0 - ui.cursor().min.x).max(0.0)); + command_button(ui, t, width, bar, look, (i, looks.len()), actions); + }); + } +} + +/// Height of a command button. +const COMMAND_HEIGHT: f32 = 30.0; + +/// A command button `width` points wide on the toolbar named `bar`: the command's label, on up to +/// two lines and cut short with … when it is longer; its name and shortcut on hover. A click runs +/// the command. While the command can't run now, the button is dimmed and its hover says why. Its +/// context menu moves it up or down among the toolbar's command buttons (`place`: its place and +/// how many there are) and takes it out. +fn command_button(ui: &mut egui::Ui, t: &Tokens, width: f32, bar: &str, look: &CommandLook, place: (usize, usize), actions: &mut Vec) { + let (rect, resp) = ui.allocate_exact_size(vec2(width, COMMAND_HEIGHT), Sense::click()); + let on = look.why.is_none(); + if resp.hovered() || resp.has_focus() { + ui.painter().rect_filled(rect.shrink(1.0), CornerRadius::same(4), t.hover); + } + let color = if on { t.text } else { t.text_disabled }; + let font = egui::FontId::proportional(10.0); + let mut job = egui::text::LayoutJob::simple(look.label().to_owned(), font, color, rect.width() - 4.0); + job.wrap = egui::text::TextWrapping { max_width: rect.width() - 4.0, max_rows: 2, break_anywhere: false, overflow_character: Some('…') }; + job.halign = egui::Align::Center; + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(rect.center().x, rect.center().y - galley.size().y / 2.0), galley, color); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, look.label())); + let mut tip = look.text.as_ref().map_or(look.id.clone(), |t| t.name.clone()); + if let Some(shortcut) = look.text.as_ref().map(|t| t.shortcut.as_str()).filter(|s| !s.is_empty()) { + tip = format!("{tip} {shortcut}"); + } + if let Some(why) = &look.why { + tip = format!("{tip}\n{}", crate::i18n::msg(why)); + } + let resp = resp.on_hover_text(tip); + if resp.clicked() { + actions.push(Action::RunCommand(look.id.clone())); + } + let (i, n) = place; + resp.context_menu(|ui| { + if widgets::menu_item(ui, tl!("Move Up"), i > 0, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i.saturating_sub(1))); + ui.close(); + } + if widgets::menu_item(ui, tl!("Move Down"), i + 1 < n, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i + 1)); + ui.close(); + } + if widgets::menu_item(ui, tl!("Remove from Toolbar"), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + ui.close(); + } + }); +} + +/// The most commands Add Tool…'s menu lists for a search. +const COMMAND_RESULTS: usize = 30; + +/// Add Tool…'s command rows, for the toolbar named `bar`: under Remove Command the toolbar's +/// command buttons by their full names, which a click takes out, then the Add Command submenu +/// ([`command_search`]). +fn command_section(ui: &mut egui::Ui, t: &Tokens, bar: &str, actions: &mut Vec) { + let Some((native, looks)) = ui.data(|d| d.get_temp::<(bool, Vec)>(add_menu_id(bar).with("commands"))) else { return }; + ui.separator(); + if !looks.is_empty() { + ui.label(egui::RichText::new(crate::i18n::colon(tl!("Remove Command"))).size(12.0).color(t.text_strong)); + for look in &looks { + if widgets::menu_item_name(ui, look.name(), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + } + } + ui.separator(); + } + // A click in the search field leaves the submenu open; a pick closes the whole menu. + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + egui::containers::menu::SubMenuButton::new(tl!("Add Command")).config(config).ui(ui, |ui| command_search(ui, t, bar, native, &looks, actions)); +} + +/// The Add Command submenu: a search field over the Command Palette's results other than tools +/// (`native`: with the native menu bar), whose first [`COMMAND_RESULTS`] matches a click adds at +/// the end of the toolbar named `bar` (dimmed: one of its command buttons, `looks`, already). +fn command_search(ui: &mut egui::Ui, t: &Tokens, bar: &str, native: bool, looks: &[CommandLook], actions: &mut Vec) { + widgets::menu_min_width(ui, 260.0); + let q = widgets::search_field(ui, command_query_id(bar), tl!("Search Commands")); + if q.trim().is_empty() { + ui.label(egui::RichText::new(tl!("Type to find a command")).color(t.text_dim)); + return; + } + let found = crate::palette::command_matches(ui.ctx(), native, &q, COMMAND_RESULTS); + if found.is_empty() { + ui.label(egui::RichText::new(tl!("No matching commands")).color(t.text_dim)); + } + for (id, name) in found { + let held = looks.iter().any(|l| l.id == id); + if widgets::menu_item_name(ui, &name, !held, false) { + actions.push(Action::AddCommand(bar.to_string(), id)); + ui.close(); + } + } +} + +/// Where Add Tool…'s menu on the toolbar named `name` keeps the text of its command search field. +pub(crate) fn command_query_id(name: &str) -> egui::Id { + add_menu_id(name).with("query") +} + /// The area of Add Tool…'s menu on the toolbar named `name`. pub(crate) fn add_menu_id(name: &str) -> egui::Id { egui::Id::unique(("custom-toolbar-add", key(name))) @@ -1376,8 +1715,9 @@ pub(crate) fn add_menu_id(name: &str) -> egui::Id { /// Add Tool…'s menu, which the + button on the toolbar `bar` opens: under Remove Tool the tools in /// the toolbar, where a click takes one out; then every tool under the All Tools drawer's headings, -/// where a click adds one at the end (dimmed: in the toolbar already). It scrolls past the window's -/// bottom bars, as other long menus do ([`widgets::menu_scroll`]). +/// where a click adds one at the end (dimmed: in the toolbar already); then its command rows +/// ([`command_section`]). It scrolls past the window's bottom bars, as other long menus do +/// ([`widgets::menu_scroll`]). fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &mut Vec) { egui::Popup::menu(button).id(add_menu_id(&bar.name)).show(|ui| { widgets::menu_min_width(ui, 200.0); @@ -1401,6 +1741,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & } } } + command_section(ui, t, &bar.name, actions); }); }); } @@ -1480,7 +1821,7 @@ mod tests { let names: Vec<&str> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect(); assert_eq!(names, ["Mine", "Toolbar 1"]); let list = app.run("window.toolbar.list", json!({})).unwrap(); - let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null}); + let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null}); assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")])); } @@ -1579,7 +1920,10 @@ mod tests { assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err()); let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap(); assert_eq!(r, json!([["pen", "curvature"]])); + // Its command buttons go with it. + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); let mine = find(&app.ui, "Mine").cloned().unwrap(); + assert_eq!(mine.commands, ["object.group"]); // Another workspace has its own toolbars (none); coming back brings Mine back. app.run("window.workspace", json!({"name": "Essentials"})).unwrap(); assert!(app.ui.custom_toolbars.is_empty()); @@ -2253,6 +2597,7 @@ mod tests { .iter() .map(|id| crate::state::FloatingFlyout { tools: vec![id.to_string(), "curvature".into()], pos: [0.0, 0.0] }) .collect(), + commands: vec![], }; let long = "x".repeat(MAX_NAME + 1); let mut bars = vec![ diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 5c1fa8f6ed..9d9d38b09d 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -304,7 +304,11 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { if let Some(name) = crate::custom_toolbars::target(&app.ui, p)? { - // A toolbar made with New Toolbar goes back to blank, as it was made. + // A toolbar made with New Toolbar goes back to blank, as it was made, without its + // command buttons too. + if let Some(bar) = crate::custom_toolbars::find_mut(&mut app.ui, &name) { + bar.commands.clear(); + } return edit_custom(app, &name, |cats| { cats.clear(); Ok(()) diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 0973a752b2..5184fdbf36 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -668,7 +668,7 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { let list = app.run("window.toolbar.list", json!({})).unwrap(); assert_eq!( list, - json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "floating": true, "side": "left", "order": null}]) + json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "commands": [], "floating": true, "side": "left", "order": null}]) ); // A second tool goes after the first. let shown = open(&mut app, 19.0); @@ -891,3 +891,241 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert!(slot_of(&app, tool).is_some(), "{tool}"); } } + +/// The command buttons of the toolbar made with New Toolbar called Mine. +fn mine_commands(app: &VectorcraftApp) -> Vec { + crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone() +} + +/// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them, +/// `toolbar.removeCommand` takes them off, and a bad call changes nothing. Manage Toolbars' copy +/// keeps them, and `toolbar.reset` takes them off with the tools. +#[test] +fn command_buttons_are_added_moved_and_removed_by_their_commands() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let added = app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(added, json!(["object.group"])); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine", "at": 0})).unwrap(); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "moved, not added twice"); + for (p, why) in [ + (json!({"command": "no.such", "toolbar": "Mine"}), "an unknown command"), + (json!({"command": "tool:pen", "toolbar": "Mine"}), "a tool"), + (json!({"command": "object.group", "toolbar": "Mine", "at": 2}), "a place past the end"), + (json!({"command": "object.group", "toolbar": "Mine", "at": -1}), "a negative place"), + (json!({"command": "toolbar.addTool", "toolbar": "Mine"}), "a command that needs params"), + (json!({"command": "object.group"}), "no toolbar"), + (json!({"toolbar": "Mine"}), "no command"), + ] { + assert!(app.run("toolbar.addCommand", p.clone()).is_err(), "{why}: {p}"); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "{why} changes nothing"); + } + assert!(app.run("toolbar.removeCommand", json!({"command": "object.group"})).is_err(), "no toolbar"); + let list = app.run("window.toolbar.list", json!({})).unwrap(); + assert_eq!(list[0]["commands"], json!(["object.path.cleanUp", "object.group"])); + let copy = app.run("window.toolbar.duplicate", json!({"name": "Mine"})).unwrap(); + let copy = copy["toolbar"].as_str().unwrap().to_string(); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands, mine_commands(&app), "the copy has them"); + let left = app.run("toolbar.removeCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.path.cleanUp"])); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.reset", json!({"toolbar": "Mine"})).unwrap(); + assert!(mine_commands(&app).is_empty(), "Reset makes the toolbar blank"); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands.len(), 2, "the copy keeps its own"); +} + +/// The text painted inside the toolbar called Mine that starts with `text`: a point inside it and +/// its color. +fn on_mine(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, text: &str) -> Option<(Pos2, Color32)> { + let shown = frame(app, ctx, time, vec![]); + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.starts_with(text) && bar.contains(*p)).map(|(_, p, c)| (p, c)) +} + +/// A command button shows its command's label, without the ellipsis, and a click runs what the +/// command's menu item runs. While that item would be dimmed, the button is dimmed too and a click +/// runs nothing. A command whose item ends in … opens its dialog. +#[test] +fn a_command_button_runs_its_command_and_is_dimmed_while_it_cannot() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + for c in ["object.group", "object.path.cleanUp"] { + app.run("toolbar.addCommand", json!({"command": c, "toolbar": "Mine"})).unwrap(); + } + let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.history.undo.len()); + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "Group").expect("the button shows Group"); + assert_eq!(color, t.text_disabled, "dimmed with nothing selected"); + let before = undo(&app); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert_eq!(undo(&app), before, "a dimmed button runs nothing"); + assert!(!app.ui.status.is_empty(), "the status line says why"); + app.run("select.all", json!({})).unwrap(); + let (at, color) = on_mine(&mut app, &ctx, 2.0, "Group").expect("the button shows Group"); + assert_eq!(color, t.text, "not dimmed with objects selected"); + click(&mut app, &ctx, 3.0, at); + assert!(undo(&app) > before, "Group ran"); + let (at, _) = on_mine(&mut app, &ctx, 4.0, "Clean Up").expect("the button shows Clean Up"); + assert!(on_mine(&mut app, &ctx, 4.1, "Clean Up…").is_none(), "without the ellipsis"); + assert!(app.ui.dialog.is_none()); + click(&mut app, &ctx, 5.0, at); + assert!(app.ui.dialog.is_some(), "Clean Up… opens its dialog"); +} + +/// Command buttons are kept with the preferences, and a toolbar saved before toolbars held commands +/// loads with none. A command that is gone, such as an uninstalled plug-in's, stays: its button is +/// dimmed and shows its id, a click runs nothing and says so, and Remove Command takes it off. +#[test] +fn a_missing_command_stays_dimmed_until_it_is_removed() { + let mut app = app(); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push("plugin:x".into()); + let kept = app.ui.custom_toolbars.clone(); + let prefs: crate::state::UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap(); + assert_eq!(prefs.sanitized().custom_toolbars, kept, "kept with the preferences, the missing command too"); + let mut old = serde_json::to_value(&kept[0]).unwrap(); + old.as_object_mut().unwrap().remove("commands"); + let old: crate::state::CustomToolbar = serde_json::from_value(old).unwrap(); + assert!(old.commands.is_empty(), "an older toolbar loads without commands"); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "plug").expect("the button shows the command's id"); + assert_eq!(color, t.text_disabled); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert!(app.ui.status.contains("plugin:x"), "the status line names it: {}", app.ui.status); + let left = app.run("toolbar.removeCommand", json!({"command": "plugin:x", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.group"])); +} + +/// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one +/// off, and its Add Command submenu searches the menu commands: a click on a match adds its button +/// at the end of the toolbar. +#[test] +fn the_add_tool_menu_adds_and_removes_commands() { + let mut app = app(); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + // The + button, which moves down as command buttons are added above it. + let plus = || { + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine"))).expect("the toolbar is shown"); + crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().find(|r| bar.contains(r.center())).expect("the + button") + }; + // The menu's text named `name`, opened with a click on the + button unless it is open. + let menu_text = |app: &mut VectorcraftApp, time: f64, name: &str| { + let mut shown = frame(app, &ctx, time, vec![]); + if !shown.iter().any(|(s, ..)| s == "Select:") { + click(app, &ctx, time + 0.2, plus().center()); + frame(app, &ctx, time + 0.5, vec![]); + shown = frame(app, &ctx, time + 0.6, vec![]); + } + let menu = ctx.memory(|m| m.area_rect(crate::custom_toolbars::add_menu_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.trim() == name && menu.contains(*p)).map(|(_, p, _)| p) + }; + assert!(menu_text(&mut app, 1.0, "Remove Command:").is_some(), "a heading over the toolbar's commands"); + // The Add Command submenu opens under the pointer and searches as text is typed. + let row = menu_text(&mut app, 2.0, "Add Command").expect("the Add Command row"); + frame(&mut app, &ctx, 3.0, vec![Event::PointerMoved(row)]); + frame(&mut app, &ctx, 3.5, vec![Event::PointerMoved(row)]); + let field = crate::custom_toolbars::command_query_id("Mine").with("edit"); + ctx.memory_mut(|m| m.request_focus(field)); + frame(&mut app, &ctx, 4.0, vec![]); + frame(&mut app, &ctx, 4.1, vec![Event::Text("clean up".into())]); + frame(&mut app, &ctx, 4.2, vec![]); + let shown = frame(&mut app, &ctx, 4.3, vec![]); + let at = shown.iter().find(|(s, ..)| s.trim().ends_with("Clean Up…")).map(|(_, p, _)| *p).expect("Clean Up… is found"); + click(&mut app, &ctx, 5.0, at); + assert_eq!(mine_commands(&app), ["object.group", "object.path.cleanUp"], "added at the end"); + let pen = crate::palette::command_matches(&ctx, false, "pen", 30); + assert!(!pen.is_empty() && pen.iter().all(|(id, _)| !id.starts_with("tool:")), "tools are not listed among the commands: {pen:?}"); + let toolbar = crate::palette::command_matches(&ctx, false, "toolbar add", 30); + assert!(toolbar.iter().all(|(id, _)| id != "toolbar.addTool" && id != "toolbar.addCommand"), "commands that need params: {toolbar:?}"); + // Under Remove Command, Group is listed by its full name, and a click takes it off. + let name = crate::palette::button_text(&ctx, false, "object.group").expect("Group's result").name; + let group = menu_text(&mut app, 10.0, &name).unwrap_or_else(|| panic!("{name} under Remove Command")); + click(&mut app, &ctx, 11.0, group); + assert_eq!(mine_commands(&app), ["object.path.cleanUp"]); +} + +/// A button for a panel shows the panel, as the panel's Command Palette result does. +#[test] +fn a_panel_button_shows_its_panel() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let panel = crate::state::all_panels() + .map(|(id, _)| id) + .find(|id| !crate::panel_docking::visible(&app.ui, id) && crate::palette::is_command(&format!("panel:{id}"))) + .expect("a hidden panel"); + let id = format!("panel:{panel}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let label = crate::palette::button_text(&ctx, false, &id).expect("the panel's result").label; + let start: String = label.chars().take(3).collect(); + let (at, _) = on_mine(&mut app, &ctx, 0.1, &start).unwrap_or_else(|| panic!("the button shows {label}")); + click(&mut app, &ctx, 1.0, at); + frame(&mut app, &ctx, 1.5, vec![]); + assert!(crate::panel_docking::visible(&app.ui, panel), "{panel} is shown"); +} + +/// A button for a plug-in's command that is not installed is dimmed and shows the command's id; +/// once the plug-in is installed it shows the plug-in's name and can run, and when the plug-in is +/// removed again it is dimmed again. +#[test] +fn a_plugin_command_button_works_again_when_the_plugin_returns() { + use vectorcraft_plugins::wat as tpl; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + // A name no other test gives a plug-in. + let filter = "test.UI.toolbar_command-probe"; + let id = format!("plugin:{filter}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push(id.clone()); + app.run("select.all", json!({})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let gone = on_mine(&mut app, &ctx, 0.1, "plugin:").map(|(_, c)| c); + let manifest = format!(r#"{{"id":"{filter}","name":"Toolbar Probe","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + frame(&mut app, &ctx, 1.0, vec![]); + let back = on_mine(&mut app, &ctx, 1.1, "Toolbar").map(|(_, c)| c); + let added = app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine", "at": 0})); + vectorcraft_plugins::registry::remove(filter); + frame(&mut app, &ctx, 2.0, vec![]); + let gone_again = on_mine(&mut app, &ctx, 2.1, "plugin:").map(|(_, c)| c); + assert_eq!(gone, Some(t.text_disabled), "dimmed, with its id, while it is not installed"); + assert_eq!(back, Some(t.text), "its name, and it can run, once it is installed"); + assert!(added.is_ok(), "an installed plug-in's command can be added: {added:?}"); + assert_eq!(gone_again, Some(t.text_disabled), "dimmed again once it is removed"); +} + +/// The toolbars ask only a few command buttons in a frame whether they can run, and the others in +/// the next frames. +#[test] +fn command_buttons_ask_whether_they_can_run_a_few_at_a_time() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let ids: Vec = crate::palette::command_matches(&ctx, false, "object", 40).into_iter().map(|(id, _)| id).take(20).collect(); + assert_eq!(ids.len(), 20); + for id in &ids { + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + } + frame(&mut app, &ctx, 0.0, vec![]); + let (first, waiting) = crate::custom_toolbars::asked(&ctx); + assert!(first < ids.len() && waiting, "{first} asked in the first frame"); + for k in 1..5 { + frame(&mut app, &ctx, f64::from(k), vec![]); + } + assert_eq!(crate::custom_toolbars::asked(&ctx), (ids.len(), false), "every button was asked in the next frames"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..cd7cb481cc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -614,6 +614,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -672,7 +684,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..b103caef50 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -327,6 +327,8 @@ pub(crate) struct Catalog { list: Vec, index: search::Index, ranked: std::sync::Mutex>, + /// Where each id is in `list`. + by_id: std::collections::HashMap, } impl std::ops::Deref for Catalog { @@ -375,7 +377,69 @@ fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { // A group's row in the `search` context gives its words in `lang`; a plain row is not read. let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); - Catalog { list, index, ranked: std::sync::Mutex::new(None) } + let by_id = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + Catalog { list, index, ranked: std::sync::Mutex::new(None), by_id } +} + +/// What a command button on a toolbar made with New Toolbar shows for the result `id` +/// ([`button_text`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ButtonText { + /// The result's label in the interface language, without the menu path in front of it and + /// without a closing ellipsis. + pub label: String, + /// The result's full name in the interface language, as the palette lists it. + pub name: String, + /// The shortcut as the menus show it, or empty. + pub shortcut: String, +} + +/// The label and shortcut of the palette result `id` in the interface language, from the entries +/// built once per language, plug-in set and shortcut set (`native`: with the native menu bar); none +/// when the palette lists no result with that id now (an uninstalled plug-in's command). +pub(crate) fn button_text(ctx: &egui::Context, native: bool, id: &str) -> Option { + let entries = entries_in(ctx, crate::i18n::current(), native); + let e = entries.by_id.get(id).and_then(|&i| entries.list.get(i))?; + let label = label_of(e).trim_end(); + let label = label.strip_suffix('…').or_else(|| label.strip_suffix("...")).unwrap_or(label).trim_end(); + Some(ButtonText { label: label.to_string(), name: e.shown.clone(), shortcut: menus::shown_shortcut(&e.shortcut) }) +} + +/// The results a toolbar made with New Toolbar can hold as command buttons that the query `q` +/// matches, best first, at most `most`: the results [`is_command`] allows. Each is its id and its +/// name in the interface language (`native`: as [`button_text`]). +pub(crate) fn command_matches(ctx: &egui::Context, native: bool, q: &str, most: usize) -> Vec<(String, String)> { + let entries = entries_in(ctx, crate::i18n::current(), native); + matching(&entries, q, &[], &CommandUses::default()) + .into_iter() + .filter(|e| is_command(&e.id)) + .take(most) + .map(|e| (e.id.clone(), e.shown.clone())) + .collect() +} + +/// Can a toolbar made with New Toolbar hold the result `id` as a command button now: is it a +/// palette result other than a tool, and not a UI command that fails without params a click does +/// not give ([`crate::shortcut_editor::ui_command_needs_params`]: `toolbar.addTool` needs a +/// `tool`)? The ids are listed again when the plug-ins or the shortcuts change, not on every call. +pub(crate) fn is_command(id: &str) -> bool { + type Ids = ((u64, u64), Arc>); + static IDS: std::sync::Mutex> = std::sync::Mutex::new(None); + if id.starts_with("tool:") { + return false; + } + let key = (menus::plugin_revision(), crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed)); + let kept = IDS.lock().ok().and_then(|ids| ids.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v.clone())); + let ids = kept.unwrap_or_else(|| { + let filters: Vec = crate::shortcut_editor::filter_items().iter().map(|f| format!("plugin:{}", f.id)).collect(); + let ids = drafts().into_iter().map(|d| d.id).filter(|id| !id.starts_with("tool:") && !crate::shortcut_editor::ui_command_needs_params(id)); + let ids: Arc> = Arc::new(ids.chain(filters).collect()); + if let Ok(mut kept) = IDS.lock() { + *kept = Some((key, ids.clone())); + } + ids + }); + ids.contains(id) } /// The params text of each entry's command, which the index reads a description from @@ -531,7 +595,7 @@ pub(crate) enum Picked { /// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in /// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be /// chosen, and every other result asks about the command its pick runs. -fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { +pub(crate) fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { if id.starts_with("tool:") { return None; } @@ -585,7 +649,7 @@ impl Availability { /// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces /// that run or show their progress. A click asks again for what it leaves out (a panel shown, a /// tool chosen) without changing it ([`show`]); typing in the search field does not. -fn availability_key(app: &VectorcraftApp) -> u64 { +pub(crate) fn availability_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); crate::native_menu::state_hash(app, None).hash(&mut h); @@ -4016,6 +4080,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }; // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen // Tool: the row names that toolbar. @@ -5301,6 +5366,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index ed49600660..adad0d4e4e 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1004,7 +1004,7 @@ mod tests { /// `entries` with their index, the params text of each in `params`. fn described(entries: Vec, params: &[&str]) -> Catalog { let index = Index::build(&entries, &[], params, |_| None); - Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } + Catalog { list: entries, index, ranked: std::sync::Mutex::new(None), by_id: Default::default() } } /// Where `id` is among the results of `query`. @@ -1464,7 +1464,7 @@ mod tests { #[test] fn without_an_index_only_the_substring_rule_matches() { let entries = vec![entry("Remove Background…", "a.one"), entry("Zz Group", "b.two")]; - let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None) }; + let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None), by_id: Default::default() }; assert!(ranked(&c, "mov.nd").is_empty(), "{:?}", ranked(&c, "mov.nd")); assert_eq!(ranked(&c, "background mov"), ["a.one"]); } @@ -1519,7 +1519,12 @@ mod tests { fn a_catalog_row_adds_words_to_a_group() { let entries = || vec![entry("Zz Delete", "a.one")]; let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); - let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + let with = Catalog { + list: entries(), + index: Index::build(&entries(), &[], &[], row), + ranked: std::sync::Mutex::new(None), + by_id: Default::default(), + }; assert_eq!(ranked(&with, "entfernen"), ["a.one"]); assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..c4bfb9f835 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -991,6 +991,16 @@ fn a_menu_bar_item_runs(id: &str, params: &str) -> bool { || menu_target(id).is_some_and(|(target, _)| target != id || !names_a_required_field(params)) } +/// Is `id` a UI command that fails when it runs with no params: its params doc names a field a call +/// must give, no item of the menu bar runs it ([`a_menu_bar_item_runs`]), and a key press does not +/// run it on its own ([`ui_listed_on_its_own`])? `toolbar.addTool` needs a `tool`. +pub(crate) fn ui_command_needs_params(id: &str) -> bool { + crate::menus::UI_COMMANDS + .iter() + .find(|c| c.0 == id) + .is_some_and(|c| names_a_required_field(c.3) && !a_menu_bar_item_runs(c.0, c.3) && !ui_listed_on_its_own(c.0, c.2, c.3)) +} + /// Is engine command `c` listed in Edit › Keyboard Shortcuts whether or not an item of the menu bar /// runs it? A command with a menu path of its own is. One without (a panel menu item) is when a key /// alone can run it: it has a default key, or it is an undoable command, not an alias, whose params diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..a2284e3b6f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1087,6 +1087,11 @@ pub struct CustomToolbar { /// The groups torn off it, each floating as its own strip; they show while it does. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub floating: Vec, + /// Its command buttons, after its tools: Command Palette result ids (a command's id, or + /// `plugin:`, `effect:` or `panel:` and an id). A command that is gone, such as an uninstalled + /// plug-in's, is kept and shows as unavailable until it comes back. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub commands: Vec, } /// A category of an edited toolbar: its name (one of the Basic toolbar's; none in the Advanced diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..6d2998e113 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -479,8 +479,17 @@ toolbars Tab hid are turned off. A toolbar's ••• button button (Add Tool…) opens a menu of every tool under the drawer's headings: a click on a tool runs `toolbar.addTool {tool, toolbar}`, which puts it at the end, and the tools under its Remove Tool heading run `toolbar.removeTool {tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section -there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with -it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, +there. The same menu's Add Command submenu searches the Command Palette's results other than tools, and a pick runs +`toolbar.addCommand {command, toolbar}`, which puts a command button at the end of the toolbar, after its tools; +`toolbar.addCommand {command, toolbar, at}` moves one to place `at` among the command buttons (Move Up and Move Down +in the button's context menu), and `toolbar.removeCommand {command, toolbar}` takes one off (Remove Command in the +menu, Remove from Toolbar in the context menu). `command` is a palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. A click on the button runs what the command's menu item runs, and the +button is dimmed while that item is. An unknown command, a tool, a command that needs params a click does not give +(`toolbar.addTool`), a place past the end or a missing `toolbar` is an error and changes nothing. A command that is +no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still takes it off. +`window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. +`window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, commands, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). `window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and `window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..bcdbcab44c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3678,6 +3678,26 @@ own layout rules. {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} ``` +## Command buttons on toolbars made with New Toolbar + +A toolbar made with New Toolbar holds command buttons after its tools. `toolbar.addCommand {command, toolbar, at?}` +(Add Command in the toolbar's Add Tool… menu, remote mode, `invoke_menu`) puts a button for `command` on the toolbar +named `toolbar`, or moves the button when the toolbar has it already: at place `at` among its command buttons, 0 for +the first, or at the end without `at`. `command` is a Command Palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. `toolbar.removeCommand {command, toolbar}` takes a button off. Both +answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. An unknown +command, a tool, a command that needs params a click does not give (`toolbar.addTool`), an `at` past the end or a +missing `toolbar` is an error and changes nothing. A click on a button runs what the command's menu item runs, so a +command whose item ends in … opens its dialog, and the button is dimmed while that item is. A command that is no +longer installed, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it is +installed again or removed. `toolbar.reset {toolbar}` takes the buttons off with the tools. The buttons are kept with +the workspace, and toolbars saved before command buttons existed load without any. Command buttons are VectorCraft's +own. + +```json +{"name":"invoke_menu","arguments":{"command":"toolbar.addCommand","params":{"command":"object.group","toolbar":"Toolbar 1"}}} +``` + ## Help search Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7c0e29b42d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,6 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). + - A toolbar made with New Toolbar also holds command buttons, after its tools. The Add Command submenu at the end of its Add Tool… menu searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels), and a pick adds a button at the end; Remove Command in the same menu lists the buttons and takes one off. A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in … opens its dialog. While that item is dimmed the button is dimmed and runs nothing. The button's context menu has Move Up, Move Down and Remove from Toolbar. The buttons are kept with the toolbar in the workspace, Manage Toolbars' copy keeps them, and a toolbar saved without them loads unchanged. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons (a button shows its label). Command buttons are VectorCraft's own (`toolbar.addCommand`, `toolbar.removeCommand`; `command_buttons_are_added_moved_and_removed_by_their_commands`, `a_command_button_runs_its_command_and_is_dimmed_while_it_cannot`, `a_missing_command_stays_dimmed_until_it_is_removed`, `a_plugin_command_button_works_again_when_the_plugin_returns`, `a_panel_button_shows_its_panel`, `command_buttons_ask_whether_they_can_run_a_few_at_a_time`, `the_add_tool_menu_adds_and_removes_commands`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - In the All Tools drawer a tool the toolbar holds is drawn throughout — name, shortcut and icon — in the dim text colour, one step dimmer than a tool not in it, so it still reads as in the toolbar while its name stays readable against the panel; the disabled colour it was drawn in before was about 2.6:1 on the panel, unreadable at the drawer's 12.5 px (#8294; `tools_in_the_toolbar_are_dimmed_in_the_drawer` in `crates/ui-egui/src/edit_toolbar/tests.rs`, which asserts the painted colour's contrast). The dimming is VectorCraft's own (#1018). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). From cc83f5ab6344acc2a6e0a2f88dafc86a08695953 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:58:50 -0800 Subject: [PATCH 016/106] Plug-ins: live effects set opacity, blending and effects on their pieces A painted live effect whose manifest has "api": 3 and "appearanceOutput": true may give each piece, and each fill and stroke it returns, an opacity from 0 to 1, a blending mode by its exact name and up to 16 built-in effect records (4,096 in one result). Rows take raster effects only, and the rows an effect on a fill or stroke returns take no effects. 3D effects and plug-in effects, this one included, are refused, so a returned effect never runs a plug-in. The host checks each record as effect.apply checks its parameters: known keys, the type of each default, documented ranges and the per-effect value checks. A bad value refuses the whole result, naming the field, and that step draws its input unchanged. A piece's geometry effects reshape it before the object's later effects, which run on it once, and count against the geometry effects' budget. The effect stays live and runs again when its source changes. Docs: docs/plugins.md, docs/mcp.md (plugin.list), docs/target-app-parity.md. --- crates/effects/src/catalog.rs | 27 +++ crates/effects/src/geometry.rs | 1 + crates/effects/src/lib.rs | 4 +- crates/effects/src/params.rs | 148 +++++++++++++ crates/effects/src/reshape.rs | 115 +++++++--- crates/effects/src/tests/painted.rs | 211 ++++++++++++++++++ crates/engine/src/cmd/plugin.rs | 5 +- crates/plugins/src/effect.rs | 3 +- crates/plugins/src/manifest.rs | 49 ++++- crates/plugins/src/objects.rs | 2 +- crates/plugins/src/painted.rs | 288 ++++++++++++++++++++++--- crates/plugins/src/painted/tests.rs | 155 ++++++++++++- crates/plugins/src/permissions.rs | 8 +- crates/render/src/tests.rs | 1 + crates/render/src/tests/paintedlook.rs | 111 ++++++++++ crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 9 + crates/ui-egui/src/i18n/cs.tsv | 9 + crates/ui-egui/src/i18n/da.tsv | 9 + crates/ui-egui/src/i18n/de.tsv | 9 + crates/ui-egui/src/i18n/el.tsv | 9 + crates/ui-egui/src/i18n/es.tsv | 9 + crates/ui-egui/src/i18n/fi.tsv | 9 + crates/ui-egui/src/i18n/fr.tsv | 9 + crates/ui-egui/src/i18n/hi.tsv | 9 + crates/ui-egui/src/i18n/hu.tsv | 9 + crates/ui-egui/src/i18n/id.tsv | 9 + crates/ui-egui/src/i18n/it.tsv | 9 + crates/ui-egui/src/i18n/ja.tsv | 9 + crates/ui-egui/src/i18n/ka.tsv | 9 + crates/ui-egui/src/i18n/ko.tsv | 9 + crates/ui-egui/src/i18n/nl.tsv | 9 + crates/ui-egui/src/i18n/pl.tsv | 9 + crates/ui-egui/src/i18n/pt-br.tsv | 9 + crates/ui-egui/src/i18n/ru.tsv | 9 + crates/ui-egui/src/i18n/sv.tsv | 9 + crates/ui-egui/src/i18n/tr.tsv | 9 + crates/ui-egui/src/i18n/uk.tsv | 9 + crates/ui-egui/src/i18n/vi.tsv | 9 + crates/ui-egui/src/i18n/zh-hans.tsv | 9 + crates/ui-egui/src/i18n/zh-hant.tsv | 9 + docs/mcp.md | 5 +- docs/plugins.md | 60 +++++- docs/target-app-parity.md | 1 + 44 files changed, 1350 insertions(+), 70 deletions(-) create mode 100644 crates/render/src/tests/paintedlook.rs diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..69222c9ada 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -58,6 +58,33 @@ pub fn raster_px_range(id: &str, key: &str) -> Option Option> { + let doc = catalog_index().get(id)?.params; + let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + let rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?; + for word in rest.split_whitespace() { + let opens = word.starts_with('('); + if let Some((lo, hi)) = word.trim_start_matches('(').split_once("..") { + let (lo, hi) = (lo.parse::().ok()?, hi.trim_end_matches([',', ';', ')', '}']).parse::().ok()?); + return (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi); + } + if opens { + return None; + } + if word.ends_with([',', '}']) { + return None; + } + } + None + }) +} + /// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 6a7405648c..6d5d67eec0 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -456,6 +456,7 @@ fn builds_within(id: &str) -> bool { fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData { use util::{join, num}; if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage }; return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone()); } diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 46fd9344e2..010e661774 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -132,6 +132,6 @@ pub use geometry::{ #[cfg(test)] pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within}; pub use params::{ - any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params, - new_effect, plugin_revision, scale_effect, upgrade_params, + any_plugin_paints_output, check_returned_effect, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, + is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params, }; diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index ab588838a6..232924508c 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -117,6 +117,154 @@ pub fn new_effect(id: &str, params: &Value) -> Option { Some(Effect { id: id.to_string(), params, visible: true }) } +/// Checks an effect record that a painted live-effect plug-in returns on a piece, or on one of its +/// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other +/// than a 3D effect, a raster effect only on a fill or stroke, and parameters that effect takes. A +/// parameter is one its defaults or its parameter documentation name, of the type its default has, +/// within the range its documentation gives ([`crate::catalog::any_documented_range`]); a texture is one as `effect.list` +/// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself +/// included, is refused, so the effects a plug-in returns never run a plug-in. +pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { + if e.id.starts_with(vectorcraft_plugins::effect::PREFIX) { + return Err("plug-in effects are not allowed in returned effects".into()); + } + let Some(info) = catalog_index().get(e.id.as_str()) else { + return Err(format!("unknown effect {:?}", e.id)); + }; + if is_three_d(&e.id) { + return Err("3D effects are not allowed in returned effects".into()); + } + if row && !is_raster(&e.id) { + return Err(format!("{:?} is not a raster effect; a fill or stroke takes raster effects only", e.id)); + } + let given = match &e.params { + Value::Null => return Ok(()), + Value::Object(m) => m, + _ => return Err("`params` must be an object".into()), + }; + let defaults = info.defaults.as_object(); + for (key, v) in given { + let default = defaults.and_then(|d| d.get(key)); + if default.is_none() && !documents_key(info.params, key) { + return Err(format!("`{key}` is not a parameter of {:?}", e.id)); + } + let kind = |v: &Value| std::mem::discriminant(v); + if let Some(d) = default + && !d.is_null() + && kind(d) != kind(v) + { + return Err(format!("`{key}` must be of the type its default {d} has")); + } + let range = crate::catalog::any_documented_range(&e.id, key); + if let (Some(r), Some(x)) = (range, v.as_f64()) + && !r.contains(&x) + { + return Err(format!("`{key}` must be from {} to {}", r.start(), r.end())); + } + } + if let Some(t) = given.get(crate::pixel::TEXTURE_IMAGE) + && t.as_str().is_none_or(|t| crate::pixel::texture(t).is_none()) + { + return Err("`textureImage` must be a texture as effect.list gives it".into()); + } + check_returned_values(&e.id, given) +} + +/// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in +/// returned, that `effect.apply` also checks: an SVG filter's XML, `scale`, `origin`, `axes` and +/// `name`; a Warp's `version`; a `color` the effect can draw; a Levels or Curves `channel`; a Radial +/// Blur's center; Pathfinder Options; and the type of each parameter without a default. +fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { + let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number()); + let switch = |key: &str| given.get(key).is_some_and(|v| !v.is_boolean()); + if id == crate::SVG_FILTER { + if let Some(xml) = given.get("xml") { + crate::svg_filter::check(xml.as_str().ok_or("`xml` must be a string")?)?; + } + if given.get("scale").is_some_and(|s| !s.as_f64().is_some_and(|k| (0.001..=1000.0).contains(&k))) { + return Err("`scale` must be a number from 0.001 to 1000".into()); + } + if given + .get("origin") + .is_some_and(|o| !o.as_array().is_some_and(|o| o.len() == 2 && o.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)))) + { + return Err("`origin` must be [x, y] in points".into()); + } + if given.get("axes").is_some_and(|a| crate::svg_filter::valid_axes(a).is_none()) { + return Err("`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0".into()); + } + if given.contains_key("name") && !given.contains_key("xml") { + return Err("an SVG filter is named by its id: give `xml` with `name`".into()); + } + } + if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) { + return Err(format!("`version` must be 0 or {}", crate::WARP_NET)); + } + let takes_color = catalog_index().get(id).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string)); + if takes_color && given.get("color").is_some_and(|v| !is_color(v)) { + return Err("`color` must be a #rrggbb color".into()); + } + if matches!(id, "adjust.levels" | "adjust.curves") && given.get("channel").is_some_and(|v| !v.as_str().is_some_and(crate::is_channel)) { + return Err(format!("`channel` must be one of {}", crate::CHANNELS.join(", "))); + } + if id == "blur.radial" { + for key in ["centerX", "centerY"] { + if given.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) { + return Err(format!("`{key}` must be a number from 0 to 1")); + } + } + } + if crate::takes_pathfinder_options(id) { + if given.get("precision").is_some_and(|v| !v.as_f64().is_some_and(|p| crate::PATHFINDER_EFFECT_PRECISION.contains(&p))) { + return Err("precision must be from 0.001 to 10 pt".into()); + } + if let Some(key) = ["removeRedundantPoints", "removeUnpainted"].into_iter().find(|k| switch(k)) { + return Err(format!("`{key}` must be true or false")); + } + } + let numbers: &[&str] = match id { + "stylize.scribble" => &["variation"], + "path.outlineStroke" => &["width"], + _ => &[], + }; + if let Some(key) = numbers.iter().find(|k| number(k)) { + return Err(format!("`{key}` must be a number")); + } + if id == "blur.gaussian" && switch("linear") { + return Err("`linear` must be true or false".into()); + } + Ok(()) +} + +/// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]` +/// with three numbers first, or a color object? +/// +/// [`Color::from_hex`]: vectorcraft_doc::color::Color::from_hex +fn is_color(v: &Value) -> bool { + use vectorcraft_doc::color::Color; + match v { + Value::String(s) => Color::from_hex(s).is_some(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number), + Value::Object(_) => serde_json::from_value::(v.clone()).is_ok(), + _ => false, + } +} + +/// Does parameter documentation `doc` (`{edgeWidth: pt 1..14 (2), …}`) name parameter `key`? +fn documents_key(doc: &str, key: &str) -> bool { + doc.match_indices(key).any(|(at, _)| { + let before = doc.get(..at).and_then(|s| s.chars().last()); + let after = doc.get(at + key.len()..).unwrap_or_default(); + matches!(before, Some('{' | ' ' | ',' | '|')) && (after.starts_with(':') || after.starts_with('?')) + }) +} + +/// Makes [`check_returned_effect`] how this process checks the effect records painted live-effect +/// plug-ins return ([`vectorcraft_plugins::painted::set_effect_check`]). +pub(crate) fn check_returned_effects() { + vectorcraft_plugins::painted::set_effect_check(check_returned_effect); +} + /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see /// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which /// keep their share of the object so. A distance left at its default is written out scaled; one diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c7ab85e7a8..02b3e5b026 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -2517,7 +2517,8 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling /// path or compound path, as one of its object's effects with reference box `bounds`: `leaf` /// becomes a group with its id and name of one object for each piece returned, in order, each with /// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of -/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces +/// its own ([`vectorcraft_plugins::painted::appearance`]), and the piece's opacity, blending mode +/// and effects ([`dress_piece`]). The swatches and patterns the pieces /// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost /// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are /// refused, or they would pass `budget`. A deferred run is listed by `at`. @@ -2531,28 +2532,74 @@ fn paint_leaf( at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; - let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); + let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { return None; } - let children = pieces - .iter() - .map(|p| { - let mut one = leaf.clone(); - one.name = None; - one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into(); - set_geometry(&mut one, p.path.clone(), p.rule); - Arc::new(one) - }) - .collect(); + let mut children = Vec::with_capacity(pieces.len()); + for p in pieces.iter() { + let mut one = leaf.clone(); + one.name = None; + one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into(); + set_geometry(&mut one, p.path.clone(), p.rule); + made = made.plus(dress_piece(&mut one, &p.look, doc)); + // The pieces' own geometry effects keep to the budget too. + if !budget.fits(made) { + return None; + } + children.push(Arc::new(one)); + } let mut g = Node::group(leaf.id, children); g.name = leaf.name.clone(); *leaf = g; Some(made) } +/// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the +/// object's, its blending mode, and its effects after the object's own. The visible geometry effects +/// among them, and only those, reshape the piece at once ([`reshape_leaves`], with `doc`), so they run +/// before the source's later effects and the effects of its fills and strokes stay for their own +/// stage; the object becomes a group with its id around the reshaped piece, carrying its +/// transparency and effects. The piece's raster effects stay on it and draw on it. When the object +/// has a blending mode other than Normal and the piece gives one, the same one included, the object +/// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs +/// past its own path. +pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, doc: Option<&Document>) -> Budget { + use vectorcraft_doc::color::BlendMode; + let none = Budget { anchors: 0, lines: 0 }; + if look.is_empty() { + return none; + } + let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend); + if let Some(o) = look.opacity { + one.opacity *= o; + } + if let Some(b) = look.blend { + one.blend = b; + } + let (shape, rest): (Vec, Vec) = look.effects.iter().cloned().partition(|e| e.visible && is_geometry(&e.id)); + one.appearance.effects.extend(rest); + let mut extra = none; + if !shape.is_empty() { + let before = art_cost(one); + let mut art = one_piece(one); + reshape_leaves(&mut art, &shape.iter().collect::>(), &shape, doc); + let mut art = dressed(art, one); + art.appearance.effects = one.appearance.effects.clone(); + extra = art_cost(&art).minus(before); + *one = art; + } + if let Some(blend) = outer { + let mut g = Node::group(one.id, vec![Arc::new(one.clone())]); + g.blend = blend; + *one = g; + } + extra +} + /// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the /// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most /// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths. @@ -2572,7 +2619,8 @@ fn piece_share() -> Budget { /// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index` /// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of /// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills -/// and strokes; one that gives none keeps the leaf's. Returns +/// and strokes; one that gives none keeps the leaf's. Each path takes its piece's opacity, blending +/// mode and effects ([`dress_piece`]). Returns /// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, /// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass /// `budget`. A deferred run is listed by `at`. @@ -2588,9 +2636,10 @@ fn paint_piece( at: Option, ) -> Option { let (path, rule) = leaf_geometry(leaf)?; + crate::params::check_returned_effects(); let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at }; let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?; - let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); + let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); if !budget.fits(made) { return None; } @@ -2613,6 +2662,10 @@ fn paint_piece( let mut one = leaf.clone(); one.appearance.items = items; set_geometry(&mut one, p.path.clone(), p.rule); + made = made.plus(dress_piece(&mut one, &p.look, doc)); + if !budget.fits(made) { + return None; + } children.push(Arc::new(one)); } *leaf = Node::group(leaf.id, children); @@ -2766,18 +2819,32 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt let it = one.items.pop().unwrap_or(it); let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) }; let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) }; + crate::params::check_returned_effects(); let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc) - .map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::>()) + .map(|pieces| { + pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::>() + }) .filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus))); - // A failed run draws the fill or stroke on the geometry it was given. - let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]); - let mut group: Vec> = vec![]; - for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) { - *used = used.plus(piece_cost(&path)); - let mut p = piece(items); - set_geometry(&mut p, path, rule); - group.push(Arc::new(p)); - } + // The paths the pieces become, with their own geometry effects applied, and what they cost. + let build = |returned: Vec<(PathData, FillRule, Vec, vectorcraft_plugins::painted::Look)>| { + let mut group: Vec> = vec![]; + let mut made = Budget { anchors: 0, lines: 0 }; + for (path, rule, items, look) in returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()) { + made = made.plus(piece_cost(&path)); + let mut p = piece(items); + set_geometry(&mut p, path, rule); + made = made.plus(dress_piece(&mut p, &look, doc)); + group.push(Arc::new(p)); + } + (group, made) + }; + // A failed run, or pieces whose own geometry effects would pass the budget, draws the + // fill or stroke on the geometry it was given. + let (group, made) = painted + .map(&build) + .filter(|(_, made)| room.fits(*made)) + .unwrap_or_else(|| build(vec![(g.clone(), rule, vec![it], Default::default())])); + *used = used.plus(made); let mut p = Node::group(leaf.id, group); transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc); pieces.push(Arc::new(p)); diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 31dadc865e..8f395de870 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -268,3 +268,214 @@ fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() { let height = |b: Option| b.map_or(0.0, |b| b.height()); assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds()); } + +/// The host takes a built-in effect with parameters it has, of their type and in range, on a piece, +/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, an unknown +/// effect or parameter, a value of another type or out of range, and a geometry effect on a fill +/// or stroke. +#[test] +fn returned_effects_are_built_in_effects_with_their_own_parameters() { + let e = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true }; + let check = crate::check_returned_effect; + assert_eq!(check(&e("path.offsetPath", json!({"offset": 4.0})), false), Ok(())); + assert_eq!(check(&e("path.offsetPath", serde_json::Value::Null), false), Ok(())); + assert_eq!(check(&e("stylize.dropShadow", json!({"x": 2.0})), true), Ok(())); + assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(())); + assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(())); + // Every effect's own defaults pass the check, so each documented range holds its default. + for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id)) { + assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id); + } + for (effect, row) in [ + (e("distort.transform", json!({"copies": 1001})), false), + (e("path.offsetPath", json!({"offset": null})), false), + (e("plugin.test.effects.self", json!({})), false), + (e("threeD.extrude", json!({})), false), + (e("stylize.nope", json!({})), false), + (e("path.offsetPath", json!({"inset": 4.0})), false), + (e("path.offsetPath", json!({"offset": "4"})), false), + (e("brushStrokes.accentedEdges", json!({"edgeWidth": 15.0})), false), + (e("path.offsetPath", json!([4.0])), false), + (e("path.offsetPath", json!({"offset": 4.0})), true), + ] { + assert!(check(&effect, row).is_err(), "{effect:?} on a fill or stroke: {row}"); + } + // The values `effect.apply` checks for one effect are refused with the parameter named. + for (id, params, key) in [ + (crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"), + (crate::SVG_FILTER, json!({"scale": 0.0}), "scale"), + (crate::SVG_FILTER, json!({"origin": [1.0]}), "origin"), + (crate::SVG_FILTER, json!({"name": "f"}), "name"), + ("warp.arc", json!({"version": 99}), "version"), + ("stylize.dropShadow", json!({"color": "#zz0000"}), "color"), + ("adjust.levels", json!({"channel": "cyan"}), "channel"), + ("blur.radial", json!({"centerX": 1.5}), "centerX"), + ("pathfinder.add", json!({"precision": 20.0}), "precision"), + ("pathfinder.add", json!({"removeUnpainted": 1}), "removeUnpainted"), + ("blur.gaussian", json!({"linear": 1}), "linear"), + ("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"), + ("distort.twist", json!({"angle": 4000.0}), "angle"), + ] { + let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}")); + assert!(why.contains(key), "{id} {params}: {why}"); + } +} + +/// A painted effect on a fill whose piece fits the budget, but whose piece's own Transform copy +/// would not fit beside the source: the fill is drawn on the source's path, and nothing is drawn +/// where the piece would be. +#[test] +fn a_piece_s_own_geometry_effects_keep_to_the_budget() { + let id = "test.effects.look.budget"; + let source = drawn_share(0.45, 0.0); + let piece = json!({"path": drawn_share(0.3, 2_000.0), "effects": [{"id": "distort.transform", "params": {"copies": 1, "moveH": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = Node::path(NodeId(9), source.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut bounds = vec![]; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + bounds.push(b); + } + }); + assert!(!bounds.is_empty() && bounds.iter().all(|b| b.x1 < 2_000.0), "{bounds:?}"); + vectorcraft_plugins::registry::remove(id); +} + +/// A piece's own geometry effect reshapes it before the source's later effects run, and those run +/// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the +/// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes. +#[test] +fn later_source_effects_run_after_generated_effects_once() { + let id = "test.effects.look.offset"; + let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, "blend": "Multiply", + "effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.appearance.effects.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + n.appearance.effects.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let (mut paths, mut looks) = (vec![], vec![]); + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + paths.push(p.bounds()); + } + if c.opacity != 1.0 || c.blend != vectorcraft_doc::color::BlendMode::Normal { + looks.push((c.opacity, c.blend)); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + // Once, on the piece and what holds it. + assert_eq!(looks, [(0.5, vectorcraft_doc::color::BlendMode::Multiply)]); + let b = paths[0].unwrap(); + assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}"); + vectorcraft_plugins::registry::remove(id); +} + +/// A piece's look reshapes it by its own geometry effects alone: the Transform effect of the fill +/// it carries stays on the fill for its own stage and does not move the piece now. +#[test] +fn a_piece_s_look_runs_only_its_own_geometry_effects() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + n.appearance.items[fill].effects_mut().push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let look = vectorcraft_plugins::painted::Look { + effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, None); + let mut paths = vec![]; + n.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + paths.push((b, c.appearance.items.iter().map(|i| i.effects().len()).sum::())); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + let (b, kept) = paths[0]; + assert!((b.x0 + 10.0).abs() < 0.5 && (b.x1 - 30.0).abs() < 0.5, "{b:?}"); + assert_eq!(kept, 1, "the fill keeps its Transform effect"); +} + +/// A piece's blending mode on an object that blends in the same mode keeps both: the object +/// becomes a group in its mode around the piece in the piece's. +#[test] +fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() { + use vectorcraft_doc::color::BlendMode; + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.blend = BlendMode::Multiply; + let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() }; + crate::reshape::dress_piece(&mut n, &look, None); + let mut blends = vec![]; + n.walk(&mut |c| blends.push(c.blend)); + assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]); +} + +/// A piece with an opacity, a blending mode and a geometry effect draws them once: the group the +/// reshaped piece becomes carries them, and the path inside it draws at full opacity in Normal. +#[test] +fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() { + use vectorcraft_doc::color::BlendMode; + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let look = vectorcraft_plugins::painted::Look { + opacity: Some(0.5), + blend: Some(BlendMode::Screen), + effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], + }; + crate::reshape::dress_piece(&mut n, &look, None); + let (mut opacity, mut blends) = (1.0f32, vec![]); + n.walk(&mut |c| { + opacity *= c.opacity; + if c.blend != BlendMode::Normal { + blends.push(c.blend); + } + }); + assert!((opacity - 0.5).abs() < 1e-6, "{opacity}"); + assert_eq!(blends, [BlendMode::Screen]); +} + +/// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's +/// Offset Path runs on it alone, so the plug-in runs once and the square moves once. +#[test] +fn a_fill_s_later_effects_run_after_its_piece_s_effects_once() { + let id = "test.effects.look.rowoffset"; + let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, + "effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]}); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + let fx = n.appearance.items[fill].effects_mut(); + fx.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }); + fx.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true }); + let art = reshape(None, &n, None).unwrap(); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) + && c.appearance.items.iter().any(|i| i.is_fill() && crate::paints(i)) + { + paths.push(b); + } + }); + assert_eq!(paths.len(), 1, "{paths:?}"); + let b = paths[0]; + assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}"); + vectorcraft_plugins::registry::remove(id); +} diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..b4ba1566c0 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -104,6 +104,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if m.appearance_output { + v["appearanceOutput"] = json!(true); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -1270,7 +1273,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index 02b212cb23..57b5136251 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -503,7 +503,8 @@ fn run( tests::RUNS_STARTED.with(|n| n.set(n.get() + 1)); let output = plugin.run_limited(&input, ¶ms, &limits)?; if plugin.manifest().paint_output { - return Ok(Out::Pieces(Arc::new(painted::decode(&output, scope, rule)?))); + let looks = plugin.manifest().appearance_output.then(painted::effect_check); + return Ok(Out::Pieces(Arc::new(painted::decode_with(&output, scope, rule, looks)?))); } Ok(Out::Path(output_geometry(decode(&output)?))) } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..da07bea01f 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, APPEARANCE_API, INPUTS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -340,6 +340,11 @@ pub struct Manifest { /// manifest has `"paintOutput": true`, the only value the key may hold. #[serde(default, rename = "paintOutput", skip_serializing_if = "std::ops::Not::not")] pub paint_output: bool, + /// A live effect at `api` 3 that declares `paintOutput` and whose pieces, and their fills and + /// strokes, may also carry opacity, a blending mode and effects ([`crate::painted`]): `true` + /// when the manifest has `"appearanceOutput": true`, the only value the key may hold. + #[serde(default, rename = "appearanceOutput", skip_serializing_if = "std::ops::Not::not")] + pub appearance_output: bool, /// The menu commands it adds, in menu order (a filter or a live effect only). #[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")] pub commands: Vec, @@ -357,9 +362,14 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; - if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { + let value = serde_json::from_str::(text).ok(); + let not_true = |key: &str| value.as_ref().is_some_and(|v| v.get(key).is_some_and(|p| *p != Value::Bool(true))); + if not_true("paintOutput") { return Err(Error::Manifest("`paintOutput` may only be true".into())); } + if not_true("appearanceOutput") { + return Err(Error::Manifest("`appearanceOutput` may only be true".into())); + } let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; man.validate()?; Ok(man) @@ -381,6 +391,7 @@ impl Manifest { extensions: Vec::new(), budget: Budget::Light, paint_output: false, + appearance_output: false, commands: Vec::new(), command_allowlist: Vec::new(), } @@ -425,6 +436,9 @@ impl Manifest { if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } + if self.appearance_output && (!self.paint_output || self.api < APPEARANCE_API) { + return Err(Error::Manifest("`appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3".into())); + } self.validate_extensions()?; match (self.budget, self.kind) { (Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {} @@ -1119,7 +1133,7 @@ mod tests { (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"), (r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"), - (r#"{"id":"a","name":"x","kind":"filter","api":3}"#, "`api` is 3"), + (r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4"), (r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"), (r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"), ] { @@ -1208,6 +1222,35 @@ mod tests { } } + /// A live effect at `api` 3 that declares `paintOutput` may also declare + /// `"appearanceOutput": true`, and only that value, with no permission beyond `doc.read` and `effect.render`; + /// without `paintOutput`, below `api` 3, on another kind, or with `false`, `null` or another + /// type, it is refused naming the key. Without the key, at `api` 3, the effect paints as at 2. + #[test] + fn manifest_accepts_api3_appearance_output_only_for_painted_effects() { + let m = Manifest::parse( + br#"{"id":"org.example.tone","name":"Tone","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"permissions":["doc.read","effect.render"]}"#, + ) + .unwrap(); + assert!(m.paint_output && m.appearance_output); + assert_eq!(serde_json::to_value(&m).unwrap()["appearanceOutput"], json!(true)); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true}"#).unwrap(); + assert!(plain.paint_output && !plain.appearance_output); + assert!(serde_json::to_value(&plain).unwrap().get("appearanceOutput").is_none()); + for bad in [ + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":false}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":null}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":1}"#, + r#"{"id":"a","name":"x","kind":"effect","api":3,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"filter","api":3,"appearanceOutput":true}"#, + r#"{"id":"a","name":"x","kind":"exporter","api":3,"extensions":["plt"],"appearanceOutput":true}"#, + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("appearanceOutput"), "{bad}: {e}"); + } + } + #[test] fn commands_and_paint_output_may_both_be_declared_on_a_live_effect() { let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","api":2,"paintOutput":true,"commands":[{"id":"c","label":"C"}]}"#).unwrap(); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 19a90500ce..34cb201cdf 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -769,7 +769,7 @@ fn decode_stroke(v: &Value, at: &str) -> Result { /// An effect record from plug-in output: `{id, params?, visible?}`, in form only (the host says /// whether the effect exists and takes the parameters). `params` stays as given, so a record /// handed back unchanged equals the object's own. -fn decode_effect(v: &Value, at: &str) -> Result { +pub(crate) fn decode_effect(v: &Value, at: &str) -> Result { let e = v.as_object().ok_or_else(|| out_err(at, "an effect must be {\"id\", \"params\"?, \"visible\"?}"))?; let id = e.get("id").and_then(Value::as_str).filter(|id| (1..=MAX_EFFECT_ID).contains(&id.len()) && !id.chars().any(char::is_control)); let id = id.ok_or_else(|| out_err(at, format!("`id` must be an effect id of 1-{MAX_EFFECT_ID} bytes")))?; diff --git a/crates/plugins/src/painted.rs b/crates/plugins/src/painted.rs index 484e761677..bb4911cb9b 100644 --- a/crates/plugins/src/painted.rs +++ b/crates/plugins/src/painted.rs @@ -6,14 +6,21 @@ //! A piece without `fills` (or `strokes`) keeps the ones it was given; an empty list paints none. //! An effect on a fill may return only `fills`, one on a stroke only `strokes`. //! +//! An effect that also declares `"appearanceOutput": true` (at `api` 3) may give a piece, and each +//! fill or stroke it returns, an `opacity` (0–1), a `blend` (a [`BlendMode`] by its identifier) and +//! `effects` ([`Look`]): built-in effects only, which the host checks ([`CheckEffect`]), at most +//! [`MAX_LOOK_EFFECTS`] in one list and [`MAX_RESULT_EFFECTS`] in one result. A fill that carries +//! them is `{"paint", "opacity"?, "blend"?, "effects"?}`. The fills and strokes an effect on a fill +//! or a stroke returns take no `effects`. +//! //! The result is checked whole before any of it is used ([`decode`]): every number finite and in //! range (nothing is clamped), every key known, a gradient stop's `plates` only on a stop linked to //! a spot swatch, and every swatch and pattern a paint names in the document ([`check_references`]). //! One fault refuses the whole result, naming the field. -use serde_json::Value; -use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, LineCap, LineJoin}; +use serde_json::{Map, Value}; +use vectorcraft_color::{BlendMode, Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, LineCap, LineJoin}; use vectorcraft_geom::{FillRule, PathData}; use crate::objects::{MAX_COORD, MAX_ITEMS, MAX_OBJECTS, MAX_STROKE_WIDTH, MITER_LIMIT, OutStroke, check_point, out_err}; @@ -24,15 +31,88 @@ use crate::{Error, Result}; const PIECE_KEYS: [&str; 6] = ["type", "path", "fillRule", "bounds", "fills", "strokes"]; /// The keys a stroke of a piece may have. const STROKE_KEYS: [&str; 5] = ["paint", "width", "join", "cap", "miterLimit"]; +/// The keys a piece, a stroke or a fill also may have when the effect declares `appearanceOutput`. +const LOOK_KEYS: [&str; 3] = ["opacity", "blend", "effects"]; +/// The look keys a fill or stroke has that an effect on a fill or a stroke returns. +const ROW_LOOK_KEYS: [&str; 2] = ["opacity", "blend"]; +/// The keys an effect record has. +const EFFECT_KEYS: [&str; 3] = ["id", "params", "visible"]; + +/// Most effect records one piece, fill or stroke may carry. +pub const MAX_LOOK_EFFECTS: usize = 16; +/// Most effect records one result may carry, over all its pieces, fills and strokes. +pub const MAX_RESULT_EFFECTS: usize = 4_096; + +/// How the host checks an effect record a piece (`false`) or one of its fills or strokes (`true`) +/// carries: `Err` with the reason when the record names no built-in effect that may be there or has +/// parameters that effect does not take. The plug-in crate checks the record's form; which effects +/// exist and what they take is the host's to say. +pub type CheckEffect = fn(&Effect, bool) -> std::result::Result<(), String>; + +/// The [`CheckEffect`] of a host that lets no effect record in. +pub fn no_effects(_: &Effect, _: bool) -> std::result::Result<(), String> { + Err("this host takes no effects here".into()) +} + +/// The host's [`CheckEffect`], set once ([`set_effect_check`]). +static CHECK: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Makes `check` how the effect records of painted results are checked in this process, unless +/// one was set before. Until one is set, every effect record is refused ([`no_effects`]). +pub fn set_effect_check(check: CheckEffect) { + let _ = CHECK.set(check); +} + +/// How the effect records of painted results are checked ([`set_effect_check`]). +pub(crate) fn effect_check() -> CheckEffect { + CHECK.get().copied().unwrap_or(no_effects) +} + +/// The opacity, blending mode and effects a piece, or one of its fills or strokes, is given: each +/// `None` (or empty) keeps what it would have without. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Look { + pub opacity: Option, + pub blend: Option, + /// Drawn after the effects it already has. + pub effects: Vec, +} + +impl Look { + /// Does it keep everything as it is? + pub fn is_empty(&self) -> bool { + self.opacity.is_none() && self.blend.is_none() && self.effects.is_empty() + } + + /// Gives fill or stroke `item` this opacity and blending mode where given, and these effects + /// after its own. + fn dress(&self, item: &mut AppearanceItem) { + let (opacity, blend, effects) = match item { + AppearanceItem::Fill(f) => (&mut f.opacity, &mut f.blend, &mut f.effects), + AppearanceItem::Stroke(s) => (&mut s.opacity, &mut s.blend, &mut s.effects), + }; + if let Some(o) = self.opacity { + *opacity = o; + } + if let Some(b) = self.blend { + *blend = b; + } + effects.extend(self.effects.iter().cloned()); + } +} /// One piece a live effect returned: its geometry and fill rule, and its fills and strokes in paint -/// order (`None`: the ones it was given). +/// order (`None`: the ones it was given), with the look of the piece and of each fill and stroke it +/// gives (`fill_looks[k]` for `fills[k]`; a missing one keeps everything). #[derive(Clone, Debug, PartialEq)] pub struct Piece { pub path: PathData, pub rule: FillRule, pub fills: Option>, pub strokes: Option>, + pub look: Look, + pub fill_looks: Vec, + pub stroke_looks: Vec, } /// Where in an appearance the effect sits, which says what its pieces may paint. @@ -51,6 +131,13 @@ pub enum Scope { /// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of /// range or a paint of the wrong form refuses the whole result, naming the field. pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> { + decode_with(bytes, scope, rule, None) +} + +/// [`decode`] for an effect that declares `appearanceOutput` when `looks` is `Some`: its pieces, +/// fills and strokes may then carry opacity, a blending mode and effects, each effect record +/// checked by it. +pub fn decode_with(bytes: &[u8], scope: Scope, rule: FillRule, looks: Option) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?; if let Some(e) = crate::objects::declined(&v) { return Err(e); @@ -63,13 +150,38 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> if objects.len() > MAX_OBJECTS { return Err(out_err("objects", format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); } - let mut anchors = 0; - objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut anchors)).collect() + let mut counts = Counts { anchors: 0, effects: 0, looks, row_effects: scope == Scope::Object }; + objects.iter().enumerate().map(|(i, o)| piece(o, &format!("objects[{i}]"), scope, rule, &mut counts)).collect() } -fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) -> Result { +/// What a result holds so far, which its limits count: anchors and effect records, and how its +/// effect records are checked (`None`: the result carries no look), and whether its fills and +/// strokes may carry `effects` (only those of an object's effect: one on a fill or a stroke sits +/// among that fill's or stroke's own effects). +struct Counts { + anchors: usize, + effects: usize, + looks: Option, + row_effects: bool, +} + +impl Counts { + /// The look keys a fill or stroke may have. + fn row_look_keys(&self) -> &'static [&'static str] { + if self.row_effects { &LOOK_KEYS } else { &ROW_LOOK_KEYS } + } +} + +fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, counts: &mut Counts) -> Result { let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?; - if let Some(k) = o.keys().find(|k| !PIECE_KEYS.contains(&k.as_str())) { + let known = |k: &str| PIECE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k)); + if let Some(k) = o.keys().find(|k| !known(k)) { + if counts.looks.is_some() { + return Err(out_err( + &format!("{at}.{k}"), + "a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects`", + )); + } return Err(out_err(&format!("{at}.{k}"), "a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes`")); } if let Some(t) = o.get("type") @@ -79,7 +191,7 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) } let path = o.get("path").ok_or_else(|| out_err(&format!("{at}.path"), "each piece needs a `path`"))?; // At most MAX_ANCHORS over all pieces. - let path = crate::objects::decode_path(path, &format!("{at}.path"), anchors)?; + let path = crate::objects::decode_path(path, &format!("{at}.path"), &mut counts.anchors)?; let rule = match o.get("fillRule") { None => rule, Some(r) => match r.as_str() { @@ -101,17 +213,112 @@ fn piece(v: &Value, at: &str, scope: Scope, rule: FillRule, anchors: &mut usize) Scope::Stroke if fills.is_some() => return Err(out_err(&format!("{at}.fills"), "an effect on a stroke returns only `strokes`")), _ => {} } - let fills = fills.map(|f| f.iter().enumerate().map(|(i, p)| paint(p, &format!("{at}.fills[{i}]"))).collect::>>()).transpose()?; - let strokes = - strokes.map(|s| s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"))).collect::>>()).transpose()?; - Ok(Piece { path, rule, fills, strokes }) + let look = look(o, at, false, counts)?; + let mut fill_looks = vec![]; + let fills = match fills { + None => None, + Some(f) => { + let rows = f.iter().enumerate().map(|(i, p)| fill_row(p, &format!("{at}.fills[{i}]"), counts)).collect::>>()?; + let (paints, looks): (Vec, Vec) = rows.into_iter().unzip(); + fill_looks = looks; + Some(paints) + } + }; + let mut stroke_looks = vec![]; + let strokes = match strokes { + None => None, + Some(s) => { + let rows = s.iter().enumerate().map(|(i, s)| stroke(s, &format!("{at}.strokes[{i}]"), counts)).collect::>>()?; + let (strokes, looks): (Vec, Vec) = rows.into_iter().unzip(); + stroke_looks = looks; + Some(strokes) + } + }; + // A look that keeps everything is left out, so a result without any compares as one. + for looks in [&mut fill_looks, &mut stroke_looks] { + if looks.iter().all(Look::is_empty) { + looks.clear(); + } + } + Ok(Piece { path, rule, fills, strokes, look, fill_looks, stroke_looks }) +} + +/// A fill of a piece: a paint, or with `appearanceOutput` also `{"paint", "opacity"?, "blend"?, +/// "effects"?}` (an object with `paint` and no `type`), with its look. +fn fill_row(v: &Value, at: &str, counts: &mut Counts) -> Result<(Paint, Look)> { + match v.as_object() { + Some(o) if counts.looks.is_some() && o.contains_key("paint") && !o.contains_key("type") => { + let keys: Vec<&str> = std::iter::once("paint").chain(counts.row_look_keys().iter().copied()).collect(); + only_keys(v, at, &keys)?; + let look = look(o, at, true, counts)?; + Ok((paint(o.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?, look)) + } + _ => Ok((paint(v, at)?, Look::default())), + } +} + +/// The identifiers `blend` takes, in Transparency-panel order. +fn blend_names() -> String { + BlendMode::ALL.iter().map(|m| format!("{m:?}")).collect::>().join(", ") +} + +/// The opacity, blending mode and effects object `o` of a piece (`row` off) or of one of its fills +/// or strokes gives, checked: an `opacity` from 0 to 1, a `blend` that is one of [`BlendMode`]'s +/// identifiers exactly, and at most [`MAX_LOOK_EFFECTS`] effect records, each `{id, params?, +/// visible?}` that the host's [`CheckEffect`] lets in, within [`MAX_RESULT_EFFECTS`] for the whole +/// result. Without `appearanceOutput` the keys are refused before this is reached. +fn look(o: &Map, at: &str, row: bool, counts: &mut Counts) -> Result { + let Some(check) = counts.looks else { return Ok(Look::default()) }; + let opacity = match o.get("opacity") { + None => None, + Some(v) => match v.as_f64().filter(|x| within(*x, 0.0, 1.0)) { + Some(x) => Some(x as f32), + None => return Err(out_err(&format!("{at}.opacity"), "`opacity` must be a number from 0 to 1")), + }, + }; + let blend = match o.get("blend") { + None => None, + Some(v) => match v.as_str().and_then(|s| BlendMode::ALL.into_iter().find(|m| format!("{m:?}") == s)) { + Some(b) => Some(b), + None => return Err(out_err(&format!("{at}.blend"), format!("unknown blending mode; `blend` is one of {}", blend_names()))), + }, + }; + let records = match o.get("effects") { + None => &[][..], + Some(Value::Array(a)) if a.len() <= MAX_LOOK_EFFECTS => a.as_slice(), + Some(_) => return Err(out_err(&format!("{at}.effects"), format!("`effects` must be an array of at most {MAX_LOOK_EFFECTS} records"))), + }; + let mut effects = Vec::with_capacity(records.len()); + for (j, r) in records.iter().enumerate() { + let at = format!("{at}.effects[{j}]"); + counts.effects += 1; + if counts.effects > MAX_RESULT_EFFECTS { + return Err(out_err(&at, format!("a result carries at most {MAX_RESULT_EFFECTS} effect records"))); + } + only_keys(r, &at, &EFFECT_KEYS)?; + let e = crate::objects::decode_effect(r, &at)?; + check(&e, row).map_err(|why| out_err(&at, why))?; + effects.push(e); + } + Ok(Look { opacity, blend, effects }) } /// A stroke `{paint, width?, join?, cap?, miterLimit?}`: a width of 0–[`MAX_STROKE_WIDTH`] and a -/// miter limit in [`MITER_LIMIT`]. -fn stroke(v: &Value, at: &str) -> Result { +/// miter limit in [`MITER_LIMIT`]; with `appearanceOutput` also its look. +fn stroke(v: &Value, at: &str, counts: &mut Counts) -> Result<(OutStroke, Look)> { let s = v.as_object().ok_or_else(|| out_err(at, "a stroke must be {\"paint\", \"width\"?, \"join\"?, \"cap\"?, \"miterLimit\"?}"))?; - if let Some(k) = s.keys().find(|k| !STROKE_KEYS.contains(&k.as_str())) { + if counts.looks.is_some() && !counts.row_effects { + let keys: Vec<&str> = STROKE_KEYS.iter().chain(&ROW_LOOK_KEYS).copied().collect(); + only_keys(v, at, &keys)?; + } + let known = |k: &str| STROKE_KEYS.contains(&k) || (counts.looks.is_some() && LOOK_KEYS.contains(&k)); + if let Some(k) = s.keys().find(|k| !known(k)) { + if counts.looks.is_some() { + return Err(out_err( + &format!("{at}.{k}"), + "a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects`", + )); + } return Err(out_err(&format!("{at}.{k}"), "a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit`")); } let number = |key: &str, range: std::ops::RangeInclusive| -> Result> { @@ -136,7 +343,8 @@ fn stroke(v: &Value, at: &str) -> Result { Some(_) => return Err(out_err(&format!("{at}.cap"), "`cap` must be \"butt\", \"round\" or \"square\"")), }; let paint = paint(s.get("paint").unwrap_or(&Value::Null), &format!("{at}.paint"))?; - Ok(OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? }) + let out = OutStroke { paint, width: number("width", 0.0..=MAX_STROKE_WIDTH)?, join, cap, miter_limit: number("miterLimit", MITER_LIMIT)? }; + Ok((out, look(s, at, true, counts)?)) } /// Is `x` finite and in `lo..=hi`? @@ -407,48 +615,78 @@ pub(crate) fn with_swatch_colors(mut pieces: std::sync::Arc>, doc: &D pieces } -/// How many paints, gradient stops and freeform points `pieces` hold: what a cache counts them as -/// besides their anchors. +/// How many paints, gradient stops and freeform points `pieces` hold, and one for each effect +/// record they carry and for each 50 bytes of its parameters: what a cache counts them as besides +/// their anchors. pub(crate) fn paint_count(pieces: &[Piece]) -> usize { let one = |p: &Paint| match p { Paint::Gradient(g) => 1 + g.gradient.stops.len() + g.freeform.as_ref().map_or(0, |f| f.points.len()), _ => 1, }; - pieces.iter().map(|p| p.fills.iter().flatten().map(one).sum::() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::()).sum() + let effects = |l: &Look| l.effects.iter().map(|e| 1 + e.params.to_string().len() / 50).sum::(); + let looks = |p: &Piece| effects(&p.look) + p.fill_looks.iter().chain(&p.stroke_looks).map(effects).sum::(); + pieces + .iter() + .map(|p| p.fills.iter().flatten().map(one).sum::() + p.strokes.iter().flatten().map(|s| one(&s.paint)).sum::() + looks(p)) + .sum() } /// The appearance piece `p` of an object-level effect is drawn with: `base` (the object's) with /// its fills, then its strokes, replaced by the piece's where it has them, as a filter's output /// sets them (an existing item keeps everything but what the piece gives; new ones take the -/// defaults). +/// defaults), each given its look ([`Look`]). The piece's own look is not part of it: the art the +/// piece becomes carries it. pub fn appearance(base: &Appearance, p: &Piece) -> Appearance { let mut ap = base.clone(); if let Some(fills) = &p.fills { crate::objects::set_items(&mut ap, true, fills.iter().cloned().map(OutStroke::paint).collect()); + dress_items(&mut ap, true, &p.fill_looks); } if let Some(strokes) = &p.strokes { crate::objects::set_items(&mut ap, false, strokes.clone()); + dress_items(&mut ap, false, &p.stroke_looks); } ap } +/// Gives the fills (`fill`) or strokes of `ap`, in paint order, the looks in `looks`. +fn dress_items(ap: &mut Appearance, fill: bool, looks: &[Look]) { + for (item, look) in ap.items.iter_mut().filter(|i| i.is_fill() == fill).zip(looks) { + look.dress(item); + } +} + /// The items piece `p` of an effect on `item` (a fill or a stroke) is drawn with, in paint order: /// `item` itself when the piece keeps it, else one copy of it for each paint or stroke the piece -/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given). +/// gives, with that paint (and that stroke's weight, join, cap and miter limit where given) and +/// that fill's or stroke's look. pub fn items(item: &AppearanceItem, p: &Piece) -> Vec { + let dressed = |mut it: AppearanceItem, look: Option<&Look>| { + if let Some(look) = look { + look.dress(&mut it); + } + it + }; match item { AppearanceItem::Fill(f) => match &p.fills { None => vec![item.clone()], - Some(fills) => fills.iter().map(|paint| AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() })).collect(), + Some(fills) => fills + .iter() + .enumerate() + .map(|(k, paint)| { + dressed(AppearanceItem::Fill(vectorcraft_doc::FillLayer { paint: paint.clone(), ..f.clone() }), p.fill_looks.get(k)) + }) + .collect(), }, AppearanceItem::Stroke(s) => match &p.strokes { None => vec![item.clone()], Some(strokes) => strokes .iter() - .map(|o| { + .enumerate() + .map(|(k, o)| { let mut s = s.clone(); crate::objects::style(&mut s, o.clone()); - AppearanceItem::Stroke(s) + dressed(AppearanceItem::Stroke(s), p.stroke_looks.get(k)) }) .collect(), }, diff --git a/crates/plugins/src/painted/tests.rs b/crates/plugins/src/painted/tests.rs index 59acf18521..485531935e 100644 --- a/crates/plugins/src/painted/tests.rs +++ b/crates/plugins/src/painted/tests.rs @@ -84,8 +84,15 @@ fn a_piece_s_appearance_inherits_or_replaces() { ..Appearance::default() }; let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); - let piece = - |fills: Option>, strokes: Option>| Piece { path: PathData::default(), rule: FillRule::NonZero, fills, strokes }; + let piece = |fills: Option>, strokes: Option>| Piece { + path: PathData::default(), + rule: FillRule::NonZero, + fills, + strokes, + look: Look::default(), + fill_looks: vec![], + stroke_looks: vec![], + }; assert_eq!(appearance(&base, &piece(None, None)), base, "inherited"); let ap = appearance(&base, &piece(Some(vec![red.clone()]), Some(vec![]))); assert_eq!(ap.items.len(), 1); @@ -333,3 +340,147 @@ fn linked_spot_stop_plates_are_kept() { assert_eq!(plates(&pieces[0].fills.as_ref().unwrap()[0]), [Some([0.0; 4]), Some([0.1, 0.2, 0.3, 0.4])]); assert_eq!(plates(&pieces[0].strokes.as_ref().unwrap()[0].paint), [None, Some([0.1, 0.2, 0.3, 0.4])]); } + +/// A host check for these tests: Drop Shadow anywhere, Roughen on a piece only, nothing else. +fn shadows_only(e: &Effect, row: bool) -> std::result::Result<(), String> { + match e.id.as_str() { + "stylize.dropShadow" => Ok(()), + "distort.roughen" if !row => Ok(()), + id => Err(format!("not taken: {id}")), + } +} + +fn with_looks(pieces: Value) -> Result> { + decode_with(&out(pieces), Scope::Object, FillRule::NonZero, Some(shadows_only)) +} + +/// Without `appearanceOutput`, a piece, a fill and a stroke still have no opacity, blending mode +/// or effects: each refuses the result, naming the field. +#[test] +fn api2_and_undeclared_effects_still_refuse_piece_appearance() { + for (piece, at) in [ + (json!({"path": square(), "opacity": 0.5}), "objects[0].opacity"), + (json!({"path": square(), "blend": "Multiply"}), "objects[0].blend"), + (json!({"path": square(), "effects": []}), "objects[0].effects"), + (json!({"path": square(), "fills": [{"paint": red(), "opacity": 0.5}]}), "objects[0].fills[0]"), + (json!({"path": square(), "strokes": [{"paint": red(), "blend": "Screen"}]}), "objects[0].strokes[0].blend"), + ] { + let e = decode(&out(json!([piece])), Scope::Object, FillRule::NonZero).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } +} + +/// With `appearanceOutput`, a piece and each fill and stroke it returns take an opacity, a blending +/// mode by its identifier and effect records the host lets in; a fill carrying them is +/// `{"paint", …}`. The fills and strokes are dressed with them, with the effects after their own; +/// a piece without any compares as one from an effect that declares nothing. +#[test] +fn piece_and_row_opacity_blend_and_effects_decode_in_order() { + let shadow = json!({"id": "stylize.dropShadow", "params": {"x": 2}}); + let pieces = with_looks(json!([ + {"path": square(), "opacity": 0.5, "blend": "Multiply", "effects": [{"id": "distort.roughen"}, shadow], + "fills": [red(), {"paint": red(), "opacity": 0.25, "blend": "ColorBurn", "effects": [shadow]}], + "strokes": [{"paint": red(), "width": 2, "opacity": 0, "effects": [{"id": "stylize.dropShadow", "visible": false}]}]}, + {"path": square(), "fills": [red()]}, + ])) + .unwrap(); + let look = &pieces[0].look; + assert_eq!((look.opacity, look.blend), (Some(0.5), Some(BlendMode::Multiply))); + assert_eq!(look.effects.iter().map(|e| e.id.as_str()).collect::>(), ["distort.roughen", "stylize.dropShadow"]); + assert_eq!(look.effects[1].params, json!({"x": 2})); + assert_eq!(pieces[0].fill_looks.len(), 2); + assert!(pieces[0].fill_looks[0].is_empty()); + assert_eq!((pieces[0].fill_looks[1].opacity, pieces[0].fill_looks[1].blend), (Some(0.25), Some(BlendMode::ColorBurn))); + assert_eq!(pieces[0].stroke_looks[0].opacity, Some(0.0)); + assert!(!pieces[0].stroke_looks[0].effects[0].visible); + let plain = decode(&out(json!([{"path": square(), "fills": [red()]}])), Scope::Object, FillRule::NonZero).unwrap(); + assert_eq!(pieces[1], plain[0], "no look"); + // Dressed: the second fill and the stroke take their looks, the stroke's effect after its own. + let mut own = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0); + own.effects.push(Effect { id: "stylize.outerGlow".into(), params: Value::Null, visible: true }); + let base = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::WHITE))), AppearanceItem::Stroke(own)], + ..Default::default() + }; + let ap = appearance(&base, &pieces[0]); + let fills: Vec<&FillLayer> = ap.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + assert_eq!((fills[0].opacity, fills[0].blend), (1.0, BlendMode::Normal)); + assert_eq!((fills[1].opacity, fills[1].blend, fills[1].effects.len()), (0.25, BlendMode::ColorBurn, 1)); + let Some(AppearanceItem::Stroke(s)) = ap.items.iter().find(|i| !i.is_fill()) else { panic!("a stroke") }; + assert_eq!(s.opacity, 0.0); + assert_eq!(s.effects.iter().map(|e| e.id.as_str()).collect::>(), ["stylize.outerGlow", "stylize.dropShadow"]); + // On one fill: each copy takes its own fill's look. + let copies = items(&base.items[0], &pieces[0]); + let opacity: Vec = copies.iter().map(|i| if let AppearanceItem::Fill(f) = i { f.opacity } else { -1.0 }).collect(); + assert_eq!(opacity, [1.0, 0.25]); +} + +/// Every bad look refuses the whole result, naming the field: an opacity that is not a number from +/// 0 to 1, a blending mode that is not an identifier exactly, an `effects` that is not a list, a +/// record with another key or an id the host refuses (a plug-in effect, a geometry effect on a +/// fill), and the limits of 16 records in a list and 4,096 in a result. +#[test] +fn invalid_appearance_field_refuses_every_piece_and_names_field() { + let ok = json!({"path": square(), "opacity": 0.5}); + let shadow = json!({"id": "stylize.dropShadow"}); + for (piece, at) in [ + (json!({"path": square(), "opacity": 1.5}), "objects[1].opacity"), + (json!({"path": square(), "opacity": -0.01}), "objects[1].opacity"), + (json!({"path": square(), "opacity": "0.5"}), "objects[1].opacity"), + (json!({"path": square(), "opacity": null}), "objects[1].opacity"), + (json!({"path": square(), "blend": "multiply"}), "objects[1].blend"), + (json!({"path": square(), "blend": "Color Burn"}), "objects[1].blend"), + (json!({"path": square(), "blend": 2}), "objects[1].blend"), + (json!({"path": square(), "effects": shadow}), "objects[1].effects"), + (json!({"path": square(), "effects": [{"id": "stylize.dropShadow", "order": 1}]}), "objects[1].effects[0].order"), + (json!({"path": square(), "effects": [{"id": ""}]}), "objects[1].effects[0]"), + (json!({"path": square(), "effects": [{"id": "plugin.test.self"}]}), "objects[1].effects[0]"), + (json!({"path": square(), "effects": [shadow, {"id": "stylize.nope"}]}), "objects[1].effects[1]"), + (json!({"path": square(), "fills": [{"paint": red(), "effects": [{"id": "distort.roughen"}]}]}), "objects[1].fills[0].effects[0]"), + (json!({"path": square(), "fills": [{"paint": red(), "tint": 1}]}), "objects[1].fills[0].tint"), + (json!({"path": square(), "strokes": [{"paint": red(), "opacity": 2}]}), "objects[1].strokes[0].opacity"), + (json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS + 1]}), "objects[1].effects"), + ] { + let e = with_looks(json!([ok, piece])).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } + let e = with_looks(json!([{"path": square(), "effects": [{"id": "plugin.test.self"}]}])).unwrap_err().to_string(); + assert!(e.contains("not taken: plugin.test.self"), "{e}"); + // 256 pieces of 16 records each fit; one more record does not. + let full = json!({"path": square(), "effects": vec![shadow.clone(); MAX_LOOK_EFFECTS]}); + let mut many = vec![full.clone(); MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS]; + assert_eq!(with_looks(Value::from(many.clone())).unwrap().len(), MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS); + many.push(json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]})); + let e = with_looks(Value::from(many)).unwrap_err().to_string(); + assert!( + e.contains(&format!("objects[{}].fills[0].effects[0]: a result carries at most {MAX_RESULT_EFFECTS}", MAX_RESULT_EFFECTS / MAX_LOOK_EFFECTS)), + "{e}" + ); + // A host that has set no check lets no record in. + let e = decode_with(&out(json!([{"path": square(), "effects": [shadow]}])), Scope::Object, FillRule::NonZero, Some(no_effects)).unwrap_err(); + assert!(e.to_string().contains("objects[0].effects[0]:"), "{e}"); +} + +/// An effect on a fill or a stroke sits among that fill's or stroke's own effects, so the fills +/// and strokes it returns take an opacity and a blending mode but no `effects`, even an empty +/// list; its pieces still take effects of their own. +#[test] +fn rows_of_an_effect_on_a_fill_or_stroke_take_no_effects() { + let shadow = json!({"id": "stylize.dropShadow"}); + for (scope, piece, at) in [ + (Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]}), "objects[0].fills[0].effects"), + (Scope::Fill, json!({"path": square(), "fills": [{"paint": red(), "effects": []}]}), "objects[0].fills[0].effects"), + (Scope::Stroke, json!({"path": square(), "strokes": [{"paint": red(), "effects": [shadow]}]}), "objects[0].strokes[0].effects"), + ] { + let e = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only)).unwrap_err().to_string(); + assert!(e.contains(&format!("{at}:")), "{at}: {e}"); + } + for (scope, piece) in [ + (Scope::Fill, json!({"path": square(), "effects": [shadow], "fills": [{"paint": red(), "opacity": 0.5, "blend": "Screen"}]})), + (Scope::Stroke, json!({"path": square(), "effects": [shadow], "strokes": [{"paint": red(), "width": 1, "opacity": 0.5}]})), + (Scope::Object, json!({"path": square(), "fills": [{"paint": red(), "effects": [shadow]}]})), + ] { + let pieces = decode_with(&out(json!([piece])), scope, FillRule::NonZero, Some(shadows_only)); + assert!(pieces.is_ok(), "{scope:?}: {pieces:?}"); + } +} diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..0f257cf178 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,8 +15,12 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` -/// ([`crate::painted`]). -pub const API_LEVEL: u32 = 2; +/// ([`crate::painted`]); level 3 adds its `appearanceOutput` ([`APPEARANCE_API`]). +pub const API_LEVEL: u32 = 3; + +/// The API level that adds a painted live effect's `appearanceOutput`: opacity, a blending mode +/// and effects on the pieces it returns and on their fills and strokes ([`crate::painted`]). +pub const APPEARANCE_API: u32 = 3; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, /// `settings`, `cache` and `commands` permissions they need. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 06cada26f4..eddc139ebb 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -30,6 +30,7 @@ mod meshwarp; mod movedstroke; mod objectfx; mod paintedbrush; +mod paintedlook; mod placed_document; mod rasterize; mod setup; diff --git a/crates/render/src/tests/paintedlook.rs b/crates/render/src/tests/paintedlook.rs new file mode 100644 index 0000000000..06064a8849 --- /dev/null +++ b/crates/render/src/tests/paintedlook.rs @@ -0,0 +1,111 @@ +//! A live-effect plug-in that declares `appearanceOutput` gives each piece it returns an opacity, a +//! blending mode and effects, and the canvas draws the piece with them. A refused look (an unknown +//! blending mode, a plug-in effect) leaves the source as it is. + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node}; +use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, shapes}; + +use crate::{RenderOptions, Renderer}; + +/// A 20 × 20 square at `x`, 40. +fn square_at(x: f64) -> PathData { + PathData::single(SubPath::polyline(&[Point::new(x, 40.0), Point::new(x + 20.0, 40.0), Point::new(x + 20.0, 60.0), Point::new(x, 60.0)], true)) +} + +/// Installs live-effect plug-in `id`, which declares `appearanceOutput` and returns one piece: the +/// square at 120, 40 filled red, with `look`'s keys added to it. +fn install(id: &str, look: serde_json::Value) { + use vectorcraft_plugins::wat as tpl; + let red = serde_json::to_value(Paint::solid(Color::rgb(1.0, 0.0, 0.0))).unwrap(); + let mut piece = json!({"path": square_at(120.0), "fills": [red]}); + if let (Some(p), Some(l)) = (piece.as_object_mut(), look.as_object()) { + p.extend(l.clone()); + } + let output = json!({ "objects": [piece] }).to_string(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &output)).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); +} + +/// A document with a blue rectangle over all of it and, above it, the square at `x`, 40 filled +/// green with live-effect plug-in `plugin` as its own effect. +fn document(plugin: &str, x: f64) -> Document { + let mut d = Document::new(300.0, 100.0); + let l = d.layers[0].id; + let blue = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 100.0)), + Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0), + ); + d.insert(Some(l), 0, blue).unwrap(); + let mut ap = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + ap.effects = vec![Effect { id: format!("plugin.{plugin}"), params: json!({}), visible: true }]; + let n = Node::path(d.alloc_id(), square_at(x), ap); + d.insert(Some(l), usize::MAX, n).unwrap(); + d +} + +/// The color a new renderer draws `d` with at (`x`, `y`). +fn pixel(d: &Document, x: f64, y: f64) -> [u8; 4] { + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + Renderer::new().render(d, 1, 1, Affine::translate((-x, -y)), &opts).pixel(0, 0) +} + +fn near(got: [u8; 4], want: [u8; 3]) -> bool { + got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8) +} + +/// A piece at 50% opacity with Multiply draws red multiplied with the blue under it (black) at +/// half strength: half blue. Moved, the source runs the plug-in again, and the new piece draws the +/// same way. Without the look the piece is plain red. +#[test] +fn a_piece_s_opacity_and_blending_mode_draw_and_survive_a_rerun() { + const ID: &str = "test.render.paintedlook.multiply"; + install(ID, json!({"opacity": 0.5, "blend": "Multiply"})); + for x in [0.0, 2.0] { + let d = document(ID, x); + let p = pixel(&d, 130.0, 50.0); + assert!(near(p, [0, 0, 128]), "source at {x}: {p:?}"); + assert!(near(pixel(&d, 10.0, 50.0), [0, 0, 255]), "the source is not drawn"); + } + assert_eq!(vectorcraft_plugins::effect::last_error(ID), None); + install(ID, json!({})); + assert!(near(pixel(&document(ID, 4.0), 130.0, 50.0), [255, 0, 0])); + vectorcraft_plugins::registry::remove(ID); +} + +/// A piece's geometry effect reshapes it: Offset Path by 10 pt draws red 5 pt left of the square. +#[test] +fn a_piece_s_geometry_effect_draws_on_it() { + const ID: &str = "test.render.paintedlook.offset"; + install(ID, json!({"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]})); + let d = document(ID, 0.0); + assert!(near(pixel(&d, 115.0, 50.0), [255, 0, 0]), "{:?}", pixel(&d, 115.0, 50.0)); + assert!(near(pixel(&d, 130.0, 50.0), [255, 0, 0])); + vectorcraft_plugins::registry::remove(ID); +} + +/// An unknown blending mode, a plug-in effect (this one itself) and too many effects refuse the +/// whole result: the source draws as it is, green at its own place, with no piece, and the plug-in +/// reports the field. +#[test] +fn a_refused_look_leaves_the_source_unchanged() { + for (name, look, field) in [ + ("blend", json!({"blend": "multiply"}), "objects[0].blend"), + ("self", json!({"effects": [{"id": "plugin.test.render.paintedlook.self"}]}), "objects[0].effects[0]"), + ("many", json!({"effects": vec![json!({"id": "stylize.dropShadow"}); 17]}), "objects[0].effects"), + ] { + let id = format!("test.render.paintedlook.{name}"); + install(&id, look); + let d = document(&id, 0.0); + assert!(near(pixel(&d, 10.0, 50.0), [0, 255, 0]), "{name}: the source draws"); + assert!(near(pixel(&d, 130.0, 50.0), [0, 0, 255]), "{name}: no piece"); + let e = vectorcraft_plugins::effect::last_error(&id).unwrap_or_default(); + assert!(e.contains(field), "{name}: {e}"); + vectorcraft_plugins::registry::remove(&id); + } +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..428d6c3cf7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -718,6 +718,7 @@ impl PluginIntField { extensions: Vec::new(), budget: Default::default(), paint_output: false, + appearance_output: false, commands: Vec::new(), command_allowlist: Vec::new(), }; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..1fa9d8ee41 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7767,6 +7767,15 @@ variable-list-end {0}, {1} {0} i {1} @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given s’ha omès un objecte de només lectura: retorneu-lo com a {{"id": …}} sol o tal com s’ha rebut @msg a string una cadena @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un traç només té `paint`, `width`, `join`, `cap` i `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` una peça d’un efecte dinàmic de pintura només té `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` i `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un traç només té `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` i `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` només pot ser true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` només és per a un efecte dinàmic que declara `paintOutput`, amb `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` ha de ser un nombre de 0 a 1 +@msg unknown blending mode; `blend` is one of {_1} mode de fusió desconegut; `blend` és un de {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` ha de ser una llista d’un màxim de {MAX_LOOK_EFFECTS} registres +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un resultat porta com a màxim {MAX_RESULT_EFFECTS} registres d’efecte +@msg this host takes no effects here aquest amfitrió no accepta efectes aquí @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un traç ha de ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} un efecte ha de ser {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` un efecte en un farciment només retorna `fills` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..df826e9959 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7377,6 +7377,15 @@ axis Y Axis osa Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objekt jen pro čtení byl vynechán: vraťte ho jako samotné {{"id": …}} nebo tak, jak byl předán @msg a string řetězec @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` tah má jen `paint`, `width`, `join`, `cap` a `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` část malujícího živého efektu má jen `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` a `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` tah má jen `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` a `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` může být jen true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` je jen pro živý efekt, který deklaruje `paintOutput`, s `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` musí být číslo od 0 do 1 +@msg unknown blending mode; `blend` is one of {_1} neznámý režim míchání; `blend` je jedno z {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` musí být pole nejvýše {MAX_LOOK_EFFECTS} záznamů +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records výsledek nese nejvýše {MAX_RESULT_EFFECTS} záznamů efektů +@msg this host takes no effects here tento hostitel zde nepřijímá žádné efekty @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} tah musí být {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} efekt musí být {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` efekt na výplni vrací jen `fills` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f9eebb781d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -608,6 +608,15 @@ liquify-list-end {0}, {1} {0} og {1} @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given et skrivebeskyttet objekt blev udeladt: returnér det, som {{"id": …}} alene eller som det blev givet @msg a string en streng @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en streg har kun `paint`, `width`, `join`, `cap` og `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` et stykke fra en malet live-effekt har kun `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` og `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` en streg har kun `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` og `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` må kun være true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` er kun til en live-effekt, der angiver `paintOutput`, ved `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` skal være et tal fra 0 til 1 +@msg unknown blending mode; `blend` is one of {_1} ukendt blandingstilstand; `blend` er en af {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` skal være en liste med højst {MAX_LOOK_EFFECTS} poster +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records et resultat bærer højst {MAX_RESULT_EFFECTS} effektposter +@msg this host takes no effects here denne vært tager ikke imod effekter her @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en streg skal være {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} en effekt skal være {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` en effekt på en udfyldning returnerer kun `fills` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..b34442ec03 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6960,6 +6960,15 @@ axis Y Axis Y-Achse @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ein schreibgeschütztes Objekt wurde weggelassen: Geben Sie es zurück, als {{"id": …}} allein oder so, wie es übergeben wurde @msg a string eine Zeichenkette @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` eine Kontur hat nur `paint`, `width`, `join`, `cap` und `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ein Teil eines malenden Live-Effekts hat nur `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` und `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` eine Kontur hat nur `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` und `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` darf nur true sein +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` gilt nur für einen Live-Effekt, der `paintOutput` angibt, mit `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` muss eine Zahl von 0 bis 1 sein +@msg unknown blending mode; `blend` is one of {_1} unbekannter Mischmodus; `blend` ist einer von {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` muss eine Liste von höchstens {MAX_LOOK_EFFECTS} Einträgen sein +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ein Ergebnis enthält höchstens {MAX_RESULT_EFFECTS} Effekteinträge +@msg this host takes no effects here dieser Host nimmt hier keine Effekte an @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} eine Kontur muss {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} sein @msg an effect must be {{"id", "params"?, "visible"?}} ein Effekt muss {{"id", "params"?, "visible"?}} sein @msg an effect on a fill returns only `fills` ein Effekt auf einer Fläche gibt nur `fills` zurück diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..68f5721e88 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7367,6 +7367,15 @@ axis Y Axis Άξονας Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given παραλείφθηκε ένα αντικείμενο μόνο για ανάγνωση: επιστρέψτε το ως {{"id": …}} μόνο ή όπως δόθηκε @msg a string συμβολοσειρά @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` ένα περίγραμμα έχει μόνο `paint`, `width`, `join`, `cap` και `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ένα κομμάτι ζωντανού εφέ βαφής έχει μόνο `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` και `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` ένα περίγραμμα έχει μόνο `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` και `effects` +@msg `appearanceOutput` may only be true Το `appearanceOutput` μπορεί να είναι μόνο true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 το `appearanceOutput` ισχύει μόνο για ζωντανό εφέ που δηλώνει `paintOutput`, με `api` 3 +@msg `opacity` must be a number from 0 to 1 το `opacity` πρέπει να είναι αριθμός από 0 έως 1 +@msg unknown blending mode; `blend` is one of {_1} άγνωστη λειτουργία ανάμειξης· το `blend` είναι ένα από τα {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records το `effects` πρέπει να είναι πίνακας με το πολύ {MAX_LOOK_EFFECTS} εγγραφές +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ένα αποτέλεσμα φέρει το πολύ {MAX_RESULT_EFFECTS} εγγραφές εφέ +@msg this host takes no effects here αυτό το κεντρικό σύστημα δεν δέχεται εφέ εδώ @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} ένα περίγραμμα πρέπει να είναι {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} ένα εφέ πρέπει να είναι {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` ένα εφέ σε γέμισμα επιστρέφει μόνο `fills` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..0d447e8fb0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7353,6 +7353,15 @@ axis Y Axis Eje Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given se omitió un objeto de solo lectura: devuélvalo como {{"id": …}} solo o tal como se recibió @msg a string una cadena @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un trazo solo tiene `paint`, `width`, `join`, `cap` y `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` una pieza de un efecto dinámico de pintura solo tiene `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` y `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un trazo solo tiene `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` y `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` solo puede ser true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` solo es para un efecto dinámico que declara `paintOutput`, con `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` debe ser un número de 0 a 1 +@msg unknown blending mode; `blend` is one of {_1} modo de fusión desconocido; `blend` es uno de {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` debe ser una lista de {MAX_LOOK_EFFECTS} registros como máximo +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un resultado lleva como máximo {MAX_RESULT_EFFECTS} registros de efecto +@msg this host takes no effects here este host no admite efectos aquí @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un trazo debe ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} un efecto debe ser {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` un efecto en un relleno solo devuelve `fills` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..e73ade4bb9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7444,6 +7444,15 @@ axis Y Axis Y-akseli @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given vain luku -objekti jätettiin pois: palauta se pelkkänä {{"id": …}}-muotona tai sellaisena kuin se annettiin @msg a string merkkijono @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` viivalla on vain `paint`, `width`, `join`, `cap` ja `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` maalaavan live-tehosteen osalla on vain `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` ja `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` viivalla on vain `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` ja `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` voi olla vain true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` on vain reaaliaikaiselle tehosteelle, joka ilmoittaa `paintOutput`-avaimen, tasolla `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` on oltava luku 0:sta 1:een +@msg unknown blending mode; `blend` is one of {_1} tuntematon sekoitustila; `blend` on yksi seuraavista: {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` on oltava enintään {MAX_LOOK_EFFECTS} tietueen taulukko +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records tuloksessa on enintään {MAX_RESULT_EFFECTS} tehostetietuetta +@msg this host takes no effects here tämä isäntä ei ota tässä vastaan tehosteita @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} viivan on oltava muotoa {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} tehosteen on oltava muotoa {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` täytön tehoste palauttaa vain kentän `fills` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..8ce1a6fb36 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7373,6 +7373,15 @@ axis Y Axis Axe Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given un objet en lecture seule a été omis : renvoyez-le, sous la forme {{"id": …}} seul ou tel qu’il a été fourni @msg a string une chaîne @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` un contour a seulement `paint`, `width`, `join`, `cap` et `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` une pièce d’un effet dynamique de peinture a seulement `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` et `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` un contour a seulement `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` et `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` ne peut valoir que true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` est réservé à un effet dynamique qui déclare `paintOutput`, avec `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` doit être un nombre de 0 à 1 +@msg unknown blending mode; `blend` is one of {_1} mode de fusion inconnu, `blend` vaut l’un de {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` doit être une liste d’au plus {MAX_LOOK_EFFECTS} enregistrements +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un résultat porte au plus {MAX_RESULT_EFFECTS} enregistrements d’effet +@msg this host takes no effects here cet hôte n’accepte aucun effet ici @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} un contour doit être {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} un effet doit être {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` un effet sur un fond renvoie seulement `fills` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..66badc0047 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6561,6 +6561,15 @@ arrowhead Feather पंख @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given एक केवल-पढ़ने योग्य ऑब्जेक्ट छोड़ दिया गया: इसे केवल {{"id": …}} के रूप में या जैसा दिया गया था वैसा लौटाएँ @msg a string एक स्ट्रिंग @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` स्ट्रोक में केवल `paint`, `width`, `join`, `cap` और `miterLimit` होते हैं +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` पेंट करने वाले लाइव इफ़ेक्ट के हिस्से में केवल `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` और `effects` होते हैं +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` स्ट्रोक में केवल `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` और `effects` होते हैं +@msg `appearanceOutput` may only be true `appearanceOutput` केवल true हो सकता है +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` केवल `api` 3 पर ऐसे लाइव इफ़ेक्ट के लिए है जो `paintOutput` घोषित करता है +@msg `opacity` must be a number from 0 to 1 `opacity` 0 से 1 तक की संख्या होनी चाहिए +@msg unknown blending mode; `blend` is one of {_1} अज्ञात ब्लेंडिंग मोड; `blend` इनमें से एक है: {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` अधिकतम {MAX_LOOK_EFFECTS} रिकॉर्ड की सूची होनी चाहिए +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records एक परिणाम में अधिकतम {MAX_RESULT_EFFECTS} इफ़ेक्ट रिकॉर्ड होते हैं +@msg this host takes no effects here यह होस्ट यहाँ कोई इफ़ेक्ट नहीं लेता @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} स्ट्रोक {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} होना चाहिए @msg an effect must be {{"id", "params"?, "visible"?}} इफ़ेक्ट {{"id", "params"?, "visible"?}} होना चाहिए @msg an effect on a fill returns only `fills` फ़िल पर इफ़ेक्ट केवल `fills` लौटाता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..3468f2b7c6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7362,6 +7362,15 @@ axis Y Axis Y tengely @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given kimaradt egy írásvédett objektum: adja vissza önmagában {{"id": …}} formában vagy úgy, ahogy megkapta @msg a string karakterlánc @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` a körvonalnak csak `paint`, `width`, `join`, `cap` és `miterLimit` kulcsa van +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` a festő élő effektus darabjának csak `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` és `effects` kulcsa van +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` a körvonalnak csak `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` és `effects` kulcsa van +@msg `appearanceOutput` may only be true Az `appearanceOutput` értéke csak true lehet +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 az `appearanceOutput` csak `paintOutput` kulcsot megadó élő effektushoz használható, `api` 3 mellett +@msg `opacity` must be a number from 0 to 1 az `opacity` értéke 0 és 1 közötti szám kell legyen +@msg unknown blending mode; `blend` is one of {_1} ismeretlen keverési mód; a `blend` értéke ezek egyike: {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records az `effects` legfeljebb {MAX_LOOK_EFFECTS} bejegyzésből álló tömb lehet +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records egy eredmény legfeljebb {MAX_RESULT_EFFECTS} effektusbejegyzést tartalmazhat +@msg this host takes no effects here ez a gazdagép itt nem fogad effektusokat @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} a körvonal formája {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} legyen @msg an effect must be {{"id", "params"?, "visible"?}} az effektus formája {{"id", "params"?, "visible"?}} legyen @msg an effect on a fill returns only `fills` a kitöltésen lévő effektus csak `fills` értéket ad vissza diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..484fcc98a2 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -490,6 +490,15 @@ @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given objek baca-saja dihilangkan: kembalikan objek itu, sebagai {{"id": …}} saja atau seperti yang diberikan @msg a string string @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` goresan hanya memiliki `paint`, `width`, `join`, `cap` dan `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` potongan efek langsung yang dicat hanya memiliki `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` dan `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` goresan hanya memiliki `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` dan `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` hanya boleh true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` hanya untuk efek langsung yang menyatakan `paintOutput`, pada `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` harus berupa angka dari 0 sampai 1 +@msg unknown blending mode; `blend` is one of {_1} mode campuran tidak dikenal; `blend` adalah salah satu dari {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` harus berupa larik berisi paling banyak {MAX_LOOK_EFFECTS} catatan +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records satu hasil membawa paling banyak {MAX_RESULT_EFFECTS} catatan efek +@msg this host takes no effects here host ini tidak menerima efek di sini @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} goresan harus berupa {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} efek harus berupa {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` efek pada isian hanya mengembalikan `fills` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..57073c02cb 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6999,6 +6999,15 @@ axis Y Axis Asse Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given è stato omesso un oggetto di sola lettura: restituiscilo come {{"id": …}} da solo o così come è stato fornito @msg a string una stringa @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` una traccia ha solo `paint`, `width`, `join`, `cap` e `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` un pezzo di un effetto dinamico di pittura ha solo `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` e `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` una traccia ha solo `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` e `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` può essere solo true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` vale solo per un effetto dinamico che dichiara `paintOutput`, con `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` deve essere un numero da 0 a 1 +@msg unknown blending mode; `blend` is one of {_1} metodo di fusione sconosciuto; `blend` è uno di {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` deve essere un elenco di al massimo {MAX_LOOK_EFFECTS} record +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records un risultato porta al massimo {MAX_RESULT_EFFECTS} record di effetto +@msg this host takes no effects here questo host qui non accetta effetti @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} una traccia deve essere {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} un effetto deve essere {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` un effetto su un riempimento restituisce solo `fills` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..7bf0fb1300 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7074,6 +7074,15 @@ axis Y Axis Y 軸 @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 読み取り専用のオブジェクトが省かれています: {{"id": …}} だけの形か、渡されたとおりの形で返してください @msg a string 文字列 @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 線に使えるのは `paint`、`width`、`join`、`cap`、`miterLimit` だけです +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` ペイント型のライブ効果のピースに使えるのは `path`、`fillRule`、`fills`、`strokes`、`opacity`、`blend`、`effects` だけです +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 線に使えるのは `paint`、`width`、`join`、`cap`、`miterLimit`、`opacity`、`blend`、`effects` だけです +@msg `appearanceOutput` may only be true `appearanceOutput` には true のみ指定できます +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` は `paintOutput` を宣言した `api` 3 のライブ効果専用です +@msg `opacity` must be a number from 0 to 1 `opacity` は 0 から 1 の数値にしてください +@msg unknown blending mode; `blend` is one of {_1} 不明な描画モードです。`blend` は {_1} のいずれかです +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` は最大 {MAX_LOOK_EFFECTS} 件のレコードの配列にしてください +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 1 つの結果に含められる効果レコードは最大 {MAX_RESULT_EFFECTS} 件です +@msg this host takes no effects here このホストではここに効果を指定できません @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 線は {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} の形にしてください @msg an effect must be {{"id", "params"?, "visible"?}} 効果は {{"id", "params"?, "visible"?}} の形にしてください @msg an effect on a fill returns only `fills` 塗りの効果が返すのは `fills` だけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..074932d7d8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9480,6 +9480,15 @@ axis Y Axis Y ღერძი @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given გამოტოვებულია მხოლოდ წასაკითხი ობიექტი: დააბრუნეთ ის მხოლოდ {{"id": …}}-ის სახით ან ისე, როგორც მიიღეთ @msg a string სტრიქონი @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` კონტურს აქვს მხოლოდ `paint`, `width`, `join`, `cap` და `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` მხატვრული ცოცხალი ეფექტის ნაწილს აქვს მხოლოდ `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` და `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` კონტურს აქვს მხოლოდ `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` და `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` შეიძლება იყოს მხოლოდ true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` მხოლოდ ცოცხალი ეფექტისთვისაა, რომელიც აცხადებს `paintOutput`-ს, `api` 3-ზე +@msg `opacity` must be a number from 0 to 1 `opacity` უნდა იყოს რიცხვი 0-დან 1-მდე +@msg unknown blending mode; `blend` is one of {_1} შერევის უცნობი რეჟიმი; `blend` არის ერთ-ერთი: {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` უნდა იყოს მასივი არაუმეტეს {MAX_LOOK_EFFECTS} ჩანაწერით +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records შედეგი შეიცავს არაუმეტეს {MAX_RESULT_EFFECTS} ეფექტის ჩანაწერს +@msg this host takes no effects here ეს ჰოსტი აქ ეფექტებს არ იღებს @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} კონტური უნდა იყოს {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} ეფექტი უნდა იყოს {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` შევსების ეფექტი აბრუნებს მხოლოდ `fills`-ს diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..cad77acdcc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6971,6 +6971,15 @@ axis Y Axis Y축 @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 읽기 전용 개체가 빠졌습니다: {{"id": …}}만 있는 형태나 받은 그대로 반환하십시오 @msg a string 문자열 @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 선에는 `paint`, `width`, `join`, `cap`, `miterLimit`만 있습니다 +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` 페인트형 라이브 효과의 조각에는 `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend`, `effects`만 있습니다 +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 선에는 `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend`, `effects`만 있습니다 +@msg `appearanceOutput` may only be true `appearanceOutput`에는 true만 지정할 수 있습니다 +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput`은 `paintOutput`을 선언한 `api` 3의 라이브 효과에만 쓸 수 있습니다 +@msg `opacity` must be a number from 0 to 1 `opacity`는 0에서 1 사이의 숫자여야 합니다 +@msg unknown blending mode; `blend` is one of {_1} 알 수 없는 혼합 모드입니다. `blend`는 {_1} 중 하나입니다 +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects`는 최대 {MAX_LOOK_EFFECTS}개 레코드의 배열이어야 합니다 +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 결과 하나에는 효과 레코드가 최대 {MAX_RESULT_EFFECTS}개까지 들어갑니다 +@msg this host takes no effects here 이 호스트는 여기서 효과를 받지 않습니다 @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 선은 {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 형태여야 합니다 @msg an effect must be {{"id", "params"?, "visible"?}} 효과는 {{"id", "params"?, "visible"?}} 형태여야 합니다 @msg an effect on a fill returns only `fills` 칠에 적용된 효과는 `fills`만 반환합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..e590d203ff 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -454,6 +454,15 @@ liquify-list-end {0}, {1} {0} en {1} @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given een alleen-lezen object is weggelaten: geef het terug, als alleen {{"id": …}} of zoals het is gegeven @msg a string een string @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` een contour heeft alleen `paint`, `width`, `join`, `cap` en `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` een stuk van een geschilderd live-effect heeft alleen `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` en `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` een contour heeft alleen `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` en `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` mag alleen true zijn +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` is alleen voor een live-effect dat `paintOutput` opgeeft, bij `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` moet een getal van 0 tot 1 zijn +@msg unknown blending mode; `blend` is one of {_1} onbekende overvloeimodus; `blend` is een van {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` moet een lijst van hoogstens {MAX_LOOK_EFFECTS} records zijn +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records een resultaat draagt hoogstens {MAX_RESULT_EFFECTS} effectrecords +@msg this host takes no effects here deze host neemt hier geen effecten aan @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} een contour moet {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} zijn @msg an effect must be {{"id", "params"?, "visible"?}} een effect moet {{"id", "params"?, "visible"?}} zijn @msg an effect on a fill returns only `fills` een effect op een vulling geeft alleen `fills` terug diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..6871a687cd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7232,6 +7232,15 @@ axis Y Axis Oś Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given pominięto obiekt tylko do odczytu: zwróć go jako samo {{"id": …}} lub w postaci, w jakiej został przekazany @msg a string ciągiem znaków @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` obrys ma tylko `paint`, `width`, `join`, `cap` i `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` element malującego efektu dynamicznego ma tylko `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` i `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` obrys ma tylko `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` i `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` może mieć tylko wartość true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` dotyczy tylko efektu na żywo, który deklaruje `paintOutput`, z `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` musi być liczbą od 0 do 1 +@msg unknown blending mode; `blend` is one of {_1} nieznany tryb mieszania; `blend` to jeden z {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` musi być tablicą najwyżej {MAX_LOOK_EFFECTS} rekordów +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records wynik zawiera najwyżej {MAX_RESULT_EFFECTS} rekordów efektów +@msg this host takes no effects here ten host nie przyjmuje tu efektów @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} obrys musi mieć postać {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} efekt musi mieć postać {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` efekt wypełnienia zwraca tylko `fills` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..44d07cae1a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7276,6 +7276,15 @@ axis Y Axis Eixo Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given um objeto somente leitura foi omitido: retorne-o como {{"id": …}} sozinho ou como foi recebido @msg a string uma string @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` um traçado tem apenas `paint`, `width`, `join`, `cap` e `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` uma peça de um efeito dinâmico de pintura tem apenas `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` e `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` um traçado tem apenas `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` e `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` só pode ser true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` é só para um efeito dinâmico que declara `paintOutput`, com `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` deve ser um número de 0 a 1 +@msg unknown blending mode; `blend` is one of {_1} modo de mesclagem desconhecido; `blend` é um de {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` deve ser uma lista de no máximo {MAX_LOOK_EFFECTS} registros +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records um resultado leva no máximo {MAX_RESULT_EFFECTS} registros de efeito +@msg this host takes no effects here este host não aceita efeitos aqui @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} um traçado deve ser {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} um efeito deve ser {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` um efeito em um preenchimento retorna apenas `fills` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..df085528b3 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6999,6 +6999,15 @@ axis Y Axis Ось Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given пропущен объект только для чтения: верните его как один {{"id": …}} или в том виде, в каком он был передан @msg a string строка @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` у обводки есть только `paint`, `width`, `join`, `cap` и `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` у части рисующего динамического эффекта есть только `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` и `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` у обводки есть только `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` и `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` может быть только true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` допустим только для динамического эффекта, который объявляет `paintOutput`, с `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` должно быть числом от 0 до 1 +@msg unknown blending mode; `blend` is one of {_1} неизвестный режим наложения; `blend` принимает одно из значений {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` должен быть массивом не более чем из {MAX_LOOK_EFFECTS} записей +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records результат содержит не более {MAX_RESULT_EFFECTS} записей эффектов +@msg this host takes no effects here этот хост здесь не принимает эффекты @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} обводка должна иметь вид {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} эффект должен иметь вид {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` эффект на заливке возвращает только `fills` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..1bed48187d 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7389,6 +7389,15 @@ axis Y Axis Y-axel @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given ett skrivskyddat objekt utelämnades: returnera det som enbart {{"id": …}} eller som det gavs @msg a string en sträng @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en kontur har bara `paint`, `width`, `join`, `cap` och `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` en del av en målande live-effekt har bara `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` och `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` en kontur har bara `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` och `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` får bara vara true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` gäller bara en liveeffekt som anger `paintOutput`, med `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` måste vara ett tal från 0 till 1 +@msg unknown blending mode; `blend` is one of {_1} okänt blandningsläge; `blend` är ett av {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` måste vara en lista med högst {MAX_LOOK_EFFECTS} poster +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records ett resultat har högst {MAX_RESULT_EFFECTS} effektposter +@msg this host takes no effects here den här värden tar inte emot effekter här @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en kontur måste vara {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} en effekt måste vara {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` en effekt på en fyllning returnerar bara `fills` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..253448b384 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7449,6 +7449,15 @@ axis Y Axis Y ekseni @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given salt okunur bir nesne atlandı: onu yalnızca {{"id": …}} olarak veya verildiği gibi döndürün @msg a string bir dize @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` bir konturda yalnızca `paint`, `width`, `join`, `cap` ve `miterLimit` bulunur +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` boyama türü canlı efektin bir parçasında yalnızca `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` ve `effects` bulunur +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` bir konturda yalnızca `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` ve `effects` bulunur +@msg `appearanceOutput` may only be true `appearanceOutput` yalnızca true olabilir +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` yalnızca `paintOutput` bildiren, `api` 3 düzeyindeki canlı efekt içindir +@msg `opacity` must be a number from 0 to 1 `opacity` 0 ile 1 arasında bir sayı olmalıdır +@msg unknown blending mode; `blend` is one of {_1} bilinmeyen karışım modu; `blend` şunlardan biridir: {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` en fazla {MAX_LOOK_EFFECTS} kayıtlık bir dizi olmalıdır +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records bir sonuç en fazla {MAX_RESULT_EFFECTS} efekt kaydı taşır +@msg this host takes no effects here bu ana bilgisayar burada efekt kabul etmez @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} bir kontur {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} biçiminde olmalıdır @msg an effect must be {{"id", "params"?, "visible"?}} bir efekt {{"id", "params"?, "visible"?}} biçiminde olmalıdır @msg an effect on a fill returns only `fills` dolgudaki bir efekt yalnızca `fills` döndürür diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..f1f909c810 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6981,6 +6981,15 @@ axis Y Axis Вісь Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given пропущено об’єкт лише для читання: поверніть його як один {{"id": …}} або в тому вигляді, у якому його передано @msg a string рядок @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` обведення має лише `paint`, `width`, `join`, `cap` і `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` частина малювального динамічного ефекту має лише `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` і `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` обведення має лише `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` і `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` може бути лише true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` дозволено лише для динамічного ефекту, що оголошує `paintOutput`, з `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` має бути числом від 0 до 1 +@msg unknown blending mode; `blend` is one of {_1} невідомий режим накладання; `blend` має одне зі значень {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` має бути масивом щонайбільше з {MAX_LOOK_EFFECTS} записів +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records результат містить щонайбільше {MAX_RESULT_EFFECTS} записів ефектів +@msg this host takes no effects here цей хост тут не приймає ефектів @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} обведення має мати вигляд {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} ефект має мати вигляд {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` ефект на заливці повертає лише `fills` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..7bd343130b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7028,6 +7028,15 @@ axis Y Axis Trục Y @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given một đối tượng chỉ đọc đã bị bỏ sót: hãy trả lại nó dưới dạng chỉ {{"id": …}} hoặc như khi được nhận @msg a string một chuỗi @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` nét chỉ có `paint`, `width`, `join`, `cap` và `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` một phần của hiệu ứng động kiểu tô chỉ có `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` và `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` nét chỉ có `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` và `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` chỉ có thể là true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` chỉ dành cho hiệu ứng trực tiếp có khai báo `paintOutput`, ở `api` 3 +@msg `opacity` must be a number from 0 to 1 `opacity` phải là một số từ 0 đến 1 +@msg unknown blending mode; `blend` is one of {_1} chế độ hòa trộn không xác định; `blend` là một trong {_1} +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` phải là một mảng tối đa {MAX_LOOK_EFFECTS} bản ghi +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records một kết quả mang tối đa {MAX_RESULT_EFFECTS} bản ghi hiệu ứng +@msg this host takes no effects here máy chủ này không nhận hiệu ứng ở đây @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} nét phải có dạng {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} @msg an effect must be {{"id", "params"?, "visible"?}} hiệu ứng phải có dạng {{"id", "params"?, "visible"?}} @msg an effect on a fill returns only `fills` hiệu ứng trên phần tô chỉ trả về `fills` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..eb59ef4452 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7209,6 +7209,15 @@ axis Y Axis Y 轴 @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 漏掉了一个只读对象:请以单独的 {{"id": …}} 或原样返回它 @msg a string 字符串 @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 描边只有 `paint`、`width`、`join`、`cap` 和 `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` 绘制型实时效果的片段只有 `path`、`fillRule`、`fills`、`strokes`、`opacity`、`blend` 和 `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 描边只有 `paint`、`width`、`join`、`cap`、`miterLimit`、`opacity`、`blend` 和 `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` 只能为 true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` 仅适用于声明了 `paintOutput` 的 `api` 3 实时效果 +@msg `opacity` must be a number from 0 to 1 `opacity` 必须是 0 到 1 之间的数字 +@msg unknown blending mode; `blend` is one of {_1} 未知的混合模式;`blend` 是 {_1} 之一 +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` 必须是最多 {MAX_LOOK_EFFECTS} 条记录的数组 +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 一个结果最多带 {MAX_RESULT_EFFECTS} 条效果记录 +@msg this host takes no effects here 此宿主不在此处接受效果 @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 描边必须是 {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 形式 @msg an effect must be {{"id", "params"?, "visible"?}} 效果必须是 {{"id", "params"?, "visible"?}} 形式 @msg an effect on a fill returns only `fills` 填色上的效果只返回 `fills` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..af88c1bf43 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7030,6 +7030,15 @@ axis Y Axis Y 軸 @msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given 漏掉了一個唯讀物件:請以單獨的 {{"id": …}} 或原樣傳回它 @msg a string 字串 @msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` 筆畫只有 `paint`、`width`、`join`、`cap` 和 `miterLimit` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills`, `strokes`, `opacity`, `blend` and `effects` 繪製型即時效果的片段只有 `path`、`fillRule`、`fills`、`strokes`、`opacity`、`blend` 和 `effects` +@msg a stroke has only `paint`, `width`, `join`, `cap`, `miterLimit`, `opacity`, `blend` and `effects` 筆畫只有 `paint`、`width`、`join`、`cap`、`miterLimit`、`opacity`、`blend` 和 `effects` +@msg `appearanceOutput` may only be true `appearanceOutput` 只能為 true +@msg `appearanceOutput` is only for a live effect that declares `paintOutput`, at `api` 3 `appearanceOutput` 僅適用於宣告了 `paintOutput` 的 `api` 3 即時效果 +@msg `opacity` must be a number from 0 to 1 `opacity` 必須是 0 到 1 之間的數字 +@msg unknown blending mode; `blend` is one of {_1} 未知的混合模式;`blend` 是 {_1} 之一 +@msg `effects` must be an array of at most {MAX_LOOK_EFFECTS} records `effects` 必須是最多 {MAX_LOOK_EFFECTS} 筆記錄的陣列 +@msg a result carries at most {MAX_RESULT_EFFECTS} effect records 一個結果最多帶 {MAX_RESULT_EFFECTS} 筆效果記錄 +@msg this host takes no effects here 此主機不在此處接受效果 @msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 筆畫必須是 {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} 形式 @msg an effect must be {{"id", "params"?, "visible"?}} 效果必須是 {{"id", "params"?, "visible"?}} 形式 @msg an effect on a fill returns only `fills` 填色上的效果只傳回 `fills` diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..7c0950a8e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13267,7 +13267,10 @@ id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearanc `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them as ordinary paths with those paints; a result it refuses is drawn as if the effect weren't there, and `plugin.info`'s -`lastError` names the plug-in and the refused field. While the app draws a document on screen, the live-effect plug-ins +`lastError` names the plug-in and the refused field. One that also declares `appearanceOutput` (at plug-in API level 3; +`plugin.list` gives `appearanceOutput: true`) may give each piece, fill and stroke an `opacity` from 0 to 1, a `blend` +and built-in `effects` (16 at most in one list, 4,096 in one result, no plug-in effect), drawn and expanded with the +piece; see `docs/plugins.md`. While the app draws a document on screen, the live-effect plug-ins of its first view share a 2,000 ms budget (VectorCraft's own value), and each run also keeps to its own 5,000 ms limit: once the budget is spent no run starts, and a result that comes back after it is not used. A stage left out for want of time, or one that times out, fails or has no plug-in, draws its input art unchanged and is deferred; the status bar diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..d69f1d80bc 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -27,7 +27,7 @@ in `crates/engine/src/cmd/plugin.rs`). | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, appearanceOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects), and `appearanceOutput: true` one whose pieces carry [opacity, blending and effects](#opacity-blending-and-effects-on-pieces); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. | | `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | @@ -324,10 +324,10 @@ capability model proposed for PhotoCraft plug-ins - The host enforces the grant on a filter run and a command run: without `doc.read` the filter is given no objects; without `state` its `documentData` is `null` and an output that sets it is refused; without `doc.write` an output that changes the document is refused. A refused output leaves the document as it was. -- `api` is the plug-in API level the manifest is written for: `1` (the default) or `2`, which adds the [host +- `api` is the plug-in API level the manifest is written for: `1` (the default), `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and - symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects). A higher one - is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for + symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects), or `3`, which + adds a painted live effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces). A higher one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. A level 2 effect that declares `paintOutput` needs no other permission than `doc.read` and `effect.render`. @@ -560,7 +560,12 @@ the module's start function, in a run that isn't a filter's run on a document, o instead of geometry alone. `true` is the only value the key takes; `false`, `null`, another type, another kind or `api` 1 is refused when the module is installed, and the error names `paintOutput`. Without the key the effect returns geometry, at any level. Hosts at `api` 1 refuse the manifest for its `api`, so such an effect never draws unpainted - there. + there. A painted effect may say `"api": 3` without other changes. +- `appearanceOutput` (painted live effects at `api` 3 only): `true` lets the pieces, and the fills and strokes they + return, carry [opacity, a blending mode and effects](#opacity-blending-and-effects-on-pieces). `true` is the only value + the key takes; `false`, `null`, another type, an effect without `paintOutput`, another kind or an `api` below 3 is + refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond + `doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its `api`, so such an effect never draws without its looks. - `extensions` (exporters and importers only, and required): 1–8 file extensions, lower-case letters and digits without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and @@ -811,7 +816,7 @@ is a piece drawn by itself, in the order returned, with paints of its own: - `path` is required; `fillRule` defaults to the object's. `type` and `bounds` may be handed back as given and are ignored. Any other key (`opacity`, `effects`, `guide`, `locked`, `name`, a top-level `documentData`…) refuses the - result, as does a key that a paint, its color, a gradient stop, a gradient's placement or a freeform point does not + result (an effect that declares `appearanceOutput` also takes `opacity`, `blend` and `effects`, [below](#opacity-blending-and-effects-on-pieces)), as does a key that a paint, its color, a gradient stop, a gradient's placement or a freeform point does not have, such as `opacity` on a solid paint. - `fills` and `strokes` take the forms a filter returns ([Input](#input)). A piece without `fills` (or `strokes`) is painted with the ones the effect was given; an empty list paints none. Given ones replace the object's in order, as @@ -847,6 +852,46 @@ is a piece drawn by itself, in the order returned, with paints of its own: ordinary path or compound path with its fills and strokes, as one undo step. Object › Expand of gradient and pattern fills expands the fills of each piece, and leaves a piece with other paints as it is drawn. +#### Opacity, blending and effects on pieces + +A painted live effect whose manifest also has `"api": 3` and `"appearanceOutput": true` may give each piece, and each +fill and stroke the piece returns, three more keys: + +```json +{"objects": [ + {"path": {…}, "opacity": 0.5, "blend": "Multiply", "effects": [{"id": "path.offsetPath", "params": {"offset": 4}}], + "fills": [{"type": "solid", …}, {"paint": {"type": "solid", …}, "opacity": 0.25, "blend": "Screen"}], + "strokes": [{"paint": {…}, "width": 2, "effects": [{"id": "stylize.dropShadow"}]}]} +]} +``` + +- `opacity` is a number from 0 to 1 (nothing is clamped). `blend` is one of `Normal`, `Darken`, `Multiply`, + `ColorBurn`, `Lighten`, `Screen`, `ColorDodge`, `Overlay`, `SoftLight`, `HardLight`, `Difference`, `Exclusion`, `Hue`, + `Saturation`, `Color` and `Luminosity`, spelled exactly so. `effects` is a list of at most 16 effect records + `{"id", "params"?, "visible"?}`, and one result carries at most 4,096 of them over all its pieces, fills and strokes. +- A fill that carries any of them is written `{"paint": , "opacity"?, "blend"?, "effects"?}`; a fill without + them may stay a bare paint. A stroke takes them beside its `paint`, `width`, `join`, `cap` and `miterLimit`. +- An effect record names a built-in effect that `effect.list` lists, other than a 3D effect, with parameters that + effect takes, each of the type of its default and within the range `effect.list` gives for it, where it gives one. + The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, + `axes` and `name`, a Warp's `version`, a `color`, a Levels or Curves `channel`, a Radial Blur's center and the + Pathfinder Options. Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are + taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke + returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a piece carries never + run a plug-in. +- Left out, a piece's opacity is the object's, its blending mode Normal and its effects none; a fill or stroke keeps + the opacity, blending and effects it would have without the keys. Given, a piece's opacity multiplies the object's, + and its effects and a fill's or stroke's come after the ones it already has. The object's own opacity, blending mode + and later effects still apply once to all the pieces together. +- A piece's geometry effects reshape it before the effects after this one in the object's stack, which then run on + the reshaped piece once. Its raster effects draw on the piece. What the geometry effects make counts against the + budget of the object's geometry effects, with the pieces. +- A bad value refuses the whole result as any other fault does, naming the field: for example + `objects[1].blend: unknown blending mode; …` or `objects[0].fills[1].effects[2]: plug-in effects are not allowed in + returned effects`. Without `appearanceOutput`, the three keys are refused as before. +- The effect stays live: the document holds only the effect record, and the looks are drawn, exported and expanded + (Object › Expand Appearance) as the pieces are. + An **exporter** returns `{"dataBase64": "…", "warnings"?: ["…"]}`: the file, in base64, which the host writes as it is, and what the export left out or changed, for the user (at most 100 warnings of at most 500 characters each, shown with the export's own). A decline (`{"error": …}`), a missing `dataBase64` or data that isn't base64 writes nothing. @@ -888,7 +933,6 @@ per change of their input, parameters or paints (results are cached), not per fr - Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, and importers that place files (File › Place reads only the built-in formats) or make type, images, layers or artboards. -- Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces - it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see +- Filters that change type, images or symbol instances (a filter at `api` 2 reads them, see [`inputs`](#reading-type-images-and-symbols)). - Apply Last Effect and Last Effect work for plug-in effects; there is no "last filter" for object filters yet. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..470719a586 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2681,6 +2681,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, a light filter with `progress` and no `commandAllowlist` runs in the background with the same progress window when it runs at once or OK runs it with Preview off, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Painted effects refuse gradient stop plates without a spot link (G17):** a gradient stop with process `plates` in a painted live effect's fill or stroke must link to a spot swatch of the document itself; a stop with no link, a `null` link or only the gradient's own `swatch` refuses the whole result, and so does a link to a process swatch or Registration, also when a cached result's swatch stops being a spot swatch. `lastError` names the stop's `plates`. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/effect.rs` (`cached_painted_plates_refuse_after_spot_becomes_process`). Scores and hours unchanged. +- **Painted live effects set opacity, blending and effects on their pieces (G17):** a painted live effect whose manifest has `"api": 3` and `"appearanceOutput": true` may give each piece, and each fill and stroke it returns, an `opacity` from 0 to 1, a `blend` by its exact name and up to 16 built-in effect records (4,096 in one result; raster effects only on a fill or stroke; no 3D or plug-in effect, this one included). A piece's geometry effects reshape it before the object's later effects, which run on it once. A bad value, an unknown blending mode or effect, or a list past its limit refuses the whole result, naming the field, and that step draws its input unchanged. The effect stays live and runs again when its source changes. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/effects/src/tests/painted.rs`, `crates/render/src/tests/paintedlook.rs`. Scores and hours unchanged. - **Later effects on every fill or stroke a painted effect returns (G17):** when a painted effect on a fill or stroke returns several fills or strokes, a later live-effect plug-in in that fill's or stroke's stack, and a later geometry effect on strokes, runs once on each of them in paint order, given its own paint and its own `_context.item` among them. Each run's pieces replace only that fill or stroke. A run that fails, is refused, is deferred or would pass the effects' budget leaves only its own fill or stroke as it was, and the others still run; a deferred stage is listed once, at the source fill's or stroke's place. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/effects/src/tests/painted.rs`. Scores and hours unchanged. - **Painted pieces with brushed strokes are culled and measured by their brush art (G17):** a piece that keeps the object's brushed stroke draws the brush along the piece's own path at the piece's stroke width. Culling leaves VectorCraft's usual room for brush art (16 × the stroke width + 8 pt) past each piece, from the piece's width rather than the object's, and so does culling of a group, layer, symbol instance, blend, envelope or repeat that holds the object. A group or layer also leaves that room for each brushed path among its members, painted or not. Object › Rasterize takes the brush art drawn along each piece and leaves out the object's own brush art, which is not drawn. Pieces without a brush are culled as before. Regressions: `crates/render/src/tests/paintedbrush.rs`. Scores and hours unchanged. - **Brushed paths just off the page are exported and printed:** PDF and EPS export keep a path or compound path whose brush art reaches the page while the path lies just off it, alone or in a group, by leaving the canvas's room for brush art (16 × the widest stroke + 8 pt, VectorCraft's own value) past its box. Skip Blank Artboards keeps an artboard such brush art reaches, and Print with Ignore Artboards frames the page with that room around brushed paths and around instances whose art holds brushed strokes. A clip group leaves room only for its clipping path. Art without brushed strokes is written as before. Regressions: `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/print.rs`, `crates/eps/src/tests.rs`. Scores and hours unchanged. From 10150cb77b23252813db75cafef8d17ffb474089 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:01:37 -0800 Subject: [PATCH 017/106] Plug-ins: a piece's own effects keep to what the pieces before it leave of the budget Each painted piece's own geometry effects now run within what the pieces and the pieces before it leave of the budget of the object's geometry effects, and stop at the first effect that would go past it or that would make fewer Transform copies than it asks for. The pieces after it are not built, and the object, or the fill or stroke the effect is on, draws the geometry it was given. Before, each piece was reshaped with the whole budget and checked afterwards, and on a fill every piece was reshaped before any check. Adds tests for SVG and PDF export and Expand Appearance of a piece's opacity, blending mode and effects, and fuzz cases for hostile piece looks. --- crates/effects/src/reshape.rs | 99 +++++++++++++++++++---------- crates/effects/src/tests/painted.rs | 84 ++++++++++++++++++++++-- crates/engine/src/tests/plugins.rs | 45 +++++++++++++ crates/engine/tests/plugin_fuzz.rs | 82 ++++++++++++++++++++++++ docs/plugins.md | 27 ++++---- 5 files changed, 290 insertions(+), 47 deletions(-) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 02b3e5b026..1107685578 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1625,12 +1625,27 @@ fn hoist_copies(art: &mut Node) { /// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked /// masks keeps its shape under that effect. fn reshape_leaves_apart( + art: &mut Node, + fx: &[&Effect], + owner: &[Effect], + budget: Budget, + flags: (bool, bool), + doc: Option<&Document>, +) -> crate::Carry { + reshape_leaves_checked(art, fx, owner, budget, flags, doc, None) +} + +/// [`reshape_leaves_apart`] that, given `complete`, stops at the first effect that leaves a path in +/// the art with its shape or makes fewer copies than it asks for, past `budget` ([`Ran::kept`], +/// [`Ran::short`]), and sets `complete` to `false`; the art is then partly reshaped. +fn reshape_leaves_checked( art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, (apart, rows): (bool, bool), doc: Option<&Document>, + mut complete: Option<&mut bool>, ) -> crate::Carry { let mut whole = crate::Carry::default(); if fx.is_empty() { @@ -1668,11 +1683,18 @@ fn reshape_leaves_apart( let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); - let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held }; + let strict = complete.is_some(); + let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held, strict }; // Art with linked masks keeps its shape under an effect that a mask in it could not take // as the art it masks did, so no mask is left apart from its art. let before = masked.then(|| (art.clone(), used)); let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0); + if (ran.kept || ran.short) + && let Some(complete) = complete.as_deref_mut() + { + *complete = false; + return whole; + } if (ran.masks || ran.short) && let Some((was, cost)) = before { @@ -1704,7 +1726,8 @@ fn reshape_leaves_apart( /// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of /// each linked mask before the first effect, by the id of the object it masks, and whether one of /// the object's effects holds the raster effects in its art back from its Transform effects -/// ([`follow_art`]). +/// ([`follow_art`]), and whether a Transform effect that makes fewer copies of anything in the art +/// than it asks for is reported ([`Ran::short`]) wherever it is (`strict`). struct Step<'a> { e: &'a Effect, params: &'a serde_json::Value, @@ -1716,6 +1739,7 @@ struct Step<'a> { doc: Option<&'a Document>, wholes: &'a HashMap, held: bool, + strict: bool, } /// What [`Step::run`] did to a piece of art. @@ -1728,7 +1752,8 @@ struct Ran { /// took the effect, or could have ([`Step::reshape_masks`]). masks: bool, /// A Transform effect made fewer copies of a path, image or symbol instance than it asks for - /// (past the budget or out of reach), where a linked mask could take a different number. + /// (past the budget or out of reach), where a linked mask could take a different number, or + /// anywhere in the art for a [`Step`] with `strict`. short: bool, /// How what paints the art as a whole follows the effect, when it does. whole: Option, @@ -1840,7 +1865,8 @@ impl Step<'_> { { if !own { *used = copy_art(art, m, copies, copy_scaling(options), max); - return Ran { kept: false, took: true, masks: false, short: false, whole: None }; + let short = self.strict && art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies); + return Ran { kept: false, took: true, masks: false, short, whole: None }; } // A mask's art: its copies keep to what the rest of the art leaves of `max`, and the // linked mask of the art itself takes them too. That mask's art stays in `used`, as @@ -1861,7 +1887,7 @@ impl Step<'_> { if watch && !own { masked_ids(art, false, &mut covered); } - let counts = |id: NodeId| watch && (own || covered.contains(&id)); + let counts = |id: NodeId| self.strict || (watch && (own || covered.contains(&id))); let mut short = false; let mut took = false; for_each_leaf(art, &mut |leaf| { @@ -2545,11 +2571,8 @@ fn paint_leaf( one.name = None; one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into(); set_geometry(&mut one, p.path.clone(), p.rule); - made = made.plus(dress_piece(&mut one, &p.look, doc)); - // The pieces' own geometry effects keep to the budget too. - if !budget.fits(made) { - return None; - } + // The pieces' own geometry effects keep to what the pieces before them leave of the budget. + made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?); children.push(Arc::new(one)); } let mut g = Node::group(leaf.id, children); @@ -2560,18 +2583,19 @@ fn paint_leaf( /// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the /// object's, its blending mode, and its effects after the object's own. The visible geometry effects -/// among them, and only those, reshape the piece at once ([`reshape_leaves`], with `doc`), so they run +/// among them, and only those, reshape the piece at once ([`reshape_leaves_checked`], with `doc`), so they run /// before the source's later effects and the effects of its fills and strokes stay for their own /// stage; the object becomes a group with its id around the reshaped piece, carrying its /// transparency and effects. The piece's raster effects stay on it and draw on it. When the object /// has a blending mode other than Normal and the piece gives one, the same one included, the object /// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs -/// past its own path. -pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, doc: Option<&Document>) -> Budget { +/// past its own path; `None` when its geometry effects would cost more than `room` past it: they stop at the first +/// effect that does not fit, and `one` is then incomplete. +pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, room: Budget, doc: Option<&Document>) -> Option { use vectorcraft_doc::color::BlendMode; let none = Budget { anchors: 0, lines: 0 }; if look.is_empty() { - return none; + return Some(none); } let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend); if let Some(o) = look.opacity { @@ -2586,10 +2610,16 @@ pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::L if !shape.is_empty() { let before = art_cost(one); let mut art = one_piece(one); - reshape_leaves(&mut art, &shape.iter().collect::>(), &shape, doc); + let mut complete = true; + reshape_leaves_checked(&mut art, &shape.iter().collect::>(), &shape, room.plus(before), (false, false), doc, Some(&mut complete)); + #[cfg(test)] + DRESSED.with(|d| d.set(d.get().plus(art_cost(&art)))); + extra = art_cost(&art).minus(before); + if !complete || !room.fits(extra) { + return None; + } let mut art = dressed(art, one); art.appearance.effects = one.appearance.effects.clone(); - extra = art_cost(&art).minus(before); *one = art; } if let Some(blend) = outer { @@ -2597,7 +2627,13 @@ pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::L g.blend = blend; *one = g; } - extra + Some(extra) +} + +#[cfg(test)] +thread_local! { + /// What the art [`dress_piece`] has reshaped on this thread has cost, all together. + pub(crate) static DRESSED: std::cell::Cell = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) }; } /// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the @@ -2662,10 +2698,7 @@ fn paint_piece( let mut one = leaf.clone(); one.appearance.items = items; set_geometry(&mut one, p.path.clone(), p.rule); - made = made.plus(dress_piece(&mut one, &p.look, doc)); - if !budget.fits(made) { - return None; - } + made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?); children.push(Arc::new(one)); } *leaf = Node::group(leaf.id, children); @@ -2825,25 +2858,27 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::>() }) .filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus))); - // The paths the pieces become, with their own geometry effects applied, and what they cost. + // The paths the pieces become, with their own geometry effects applied, and what they + // cost; `None` as soon as a piece's own geometry effects would pass `room`. let build = |returned: Vec<(PathData, FillRule, Vec, vectorcraft_plugins::painted::Look)>| { + let returned: Vec<_> = returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()).collect(); + let mut made = returned.iter().map(|(path, ..)| piece_cost(path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus); let mut group: Vec> = vec![]; - let mut made = Budget { anchors: 0, lines: 0 }; - for (path, rule, items, look) in returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()) { - made = made.plus(piece_cost(&path)); + for (path, rule, items, look) in returned { let mut p = piece(items); set_geometry(&mut p, path, rule); - made = made.plus(dress_piece(&mut p, &look, doc)); + made = made.plus(dress_piece(&mut p, &look, room.minus(made), doc)?); group.push(Arc::new(p)); } - (group, made) + Some((group, made)) }; // A failed run, or pieces whose own geometry effects would pass the budget, draws the - // fill or stroke on the geometry it was given. - let (group, made) = painted - .map(&build) - .filter(|(_, made)| room.fits(*made)) - .unwrap_or_else(|| build(vec![(g.clone(), rule, vec![it], Default::default())])); + // fill or stroke on the geometry it was given, at that geometry's own cost. + let (group, made) = painted.and_then(build).unwrap_or_else(|| { + let mut p = piece(vec![it]); + set_geometry(&mut p, g.clone(), rule); + (vec![Arc::new(p)], piece_cost(&g)) + }); *used = used.plus(made); let mut p = Node::group(leaf.id, group); transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc); diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 8f395de870..775205408c 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -8,7 +8,7 @@ use vectorcraft_plugins::wat as tpl; use crate::geometry::Budget; use crate::reshape; -use crate::reshape::{HELD_PEAK, PLUGIN_RUNS}; +use crate::reshape::{DRESSED, HELD_PEAK, PLUGIN_RUNS}; /// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id: /// its effect returns `output` whatever it is given. @@ -348,6 +348,82 @@ fn a_piece_s_own_geometry_effects_keep_to_the_budget() { vectorcraft_plugins::registry::remove(id); } +/// Where [`many_heavy_pieces`] puts its effect. +#[derive(Clone, Copy, Debug)] +enum HeavyOn { + /// The object's own effects. + Object, + /// The square's fill, as its only effect. + Fill, + /// The square's fill, after a painted effect that returns the square. + LaterOnFill, +} + +/// Ten painted pieces, each drawn with 4% of the effects' budget, each with a Transform effect that +/// makes 14 copies of it (60% of the budget per piece), from an effect on a square `on`: they would +/// pass the budget together, so the square is drawn as it was. The pieces' own geometry effects keep +/// to what the pieces before them left: the art reshaped for them costs less than the budget +/// together, and so does the art drawn. +fn many_heavy_pieces(on: HeavyOn) { + let id = format!("test.effects.look.heavy{on:?}").to_lowercase(); + let pieces: Vec<_> = (0..10) + .map(|k| json!({"path": drawn_share(0.04, 1_000.0 * f64::from(k)), "effects": [{"id": "distort.transform", "params": {"copies": 14, "moveH": 10.0}}]})) + .collect(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": pieces }).to_string())).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)); + let first = format!("{id}.first"); + install_painting(&first, &json!({"objects": [{"path": square}]})); + let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let heavy = Effect { id: format!("plugin.{id}"), params: json!({}), visible: true }; + let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap(); + match on { + HeavyOn::Object => n.appearance.effects.push(heavy), + HeavyOn::Fill => n.appearance.items[fill].effects_mut().push(heavy), + HeavyOn::LaterOnFill => { + n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{first}"), params: json!({}), visible: true }); + n.appearance.items[fill].effects_mut().push(heavy); + } + } + DRESSED.with(|d| d.set(Budget { anchors: 0, lines: 0 })); + let art = reshape(None, &n, None).unwrap(); + let dressed = DRESSED.with(std::cell::Cell::get); + assert!(Budget::EFFECTS.fits(dressed), "{on:?}: the pieces' own effects made {dressed:?}"); + let (mut bounds, mut drawn) = (vec![], Budget { anchors: 0, lines: 0 }); + art.walk(&mut |c| { + if let Some(p) = c.path_data() { + bounds.push(p.bounds()); + drawn = drawn.plus(Budget::of(p)); + } + }); + // On a fill, the fill and the stroke are paths of their own. + assert!(!bounds.is_empty() && bounds.iter().all(|b| *b == square.bounds()), "{on:?}: {bounds:?}"); + assert!(Budget::EFFECTS.fits(drawn), "{on:?}: the art costs {drawn:?}"); + vectorcraft_plugins::registry::remove(&id); + vectorcraft_plugins::registry::remove(&first); +} + +/// [`many_heavy_pieces`] from the object's own effect. +#[test] +fn heavy_pieces_of_an_object_s_effect_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::Object); +} + +/// [`many_heavy_pieces`] from an effect on a fill. +#[test] +fn heavy_pieces_of_a_fill_s_effect_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::Fill); +} + +/// [`many_heavy_pieces`] from a later effect on a fill. +#[test] +fn heavy_pieces_of_a_later_effect_on_a_fill_stop_within_the_budget() { + many_heavy_pieces(HeavyOn::LaterOnFill); +} + /// A piece's own geometry effect reshapes it before the source's later effects run, and those run /// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the /// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes. @@ -395,7 +471,7 @@ fn a_piece_s_look_runs_only_its_own_geometry_effects() { effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], ..Default::default() }; - crate::reshape::dress_piece(&mut n, &look, None); + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); let mut paths = vec![]; n.walk(&mut |c| { if let Some(b) = c.path_data().and_then(PathData::bounds) { @@ -417,7 +493,7 @@ fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() { Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); n.blend = BlendMode::Multiply; let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() }; - crate::reshape::dress_piece(&mut n, &look, None); + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); let mut blends = vec![]; n.walk(&mut |c| blends.push(c.blend)); assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]); @@ -435,7 +511,7 @@ fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() { blend: Some(BlendMode::Screen), effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }], }; - crate::reshape::dress_piece(&mut n, &look, None); + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); let (mut opacity, mut blends) = (1.0f32, vec![]); n.walk(&mut |c| { opacity *= c.opacity; diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..12c87bb696 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -439,6 +439,51 @@ fn a_painted_live_effect_draws_its_pieces_with_their_own_paints() { assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.paints"); } +/// A piece that an effect declaring `appearanceOutput` returns with 50% opacity, Multiply and +/// Offset Path keeps that look in SVG and PDF export, which leave the document alone, and Expand +/// Appearance writes it as an ordinary path that draws the same, with the opacity and blending +/// mode applied once, in one undo step. +#[test] +fn a_painted_piece_s_look_is_exported_and_expanded() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let piece = json!({"path": square_at(40.0), "fills": [solid("#00ff00")], "opacity": 0.5, "blend": "Multiply", + "effects": [{"id": "path.offsetPath", "params": {"offset": 5}}]}); + let manifest = + r#"{"id":"test.engine.looks","name":"Looks","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#; + install_wat(&mut s, &tpl::returning(manifest, &json!({ "objects": [piece] }).to_string())); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.looks"})); + assert_eq!(run(&mut s, "plugin.info", json!({"id": "test.engine.looks"}))["lastError"], Value::Null); + let near = |got: [u8; 4], want: [u8; 3]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 8); + let img = drawn(&s); + let (inside, grown, outside) = (img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50)); + assert!(near(inside, [128, 255, 128]) && near(grown, [128, 255, 128]), "half green, grown by the offset: {inside:?} {grown:?}"); + assert_eq!((outside, img.pixel(15, 15)), (WHITE, WHITE)); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap(); + assert!(svg.contains("#00ff00") && svg.contains("multiply") && svg.contains("0.5"), "{svg}"); + let pdf = s.execute("document.export", &json!({"format": "pdf"})).unwrap(); + let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); + assert!(pdf.windows(9).any(|w| w == b"/Multiply"), "the PDF sets the blending mode"); + assert_eq!(s.doc().unwrap().doc, before, "export doesn't change the document"); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "effect.expandAppearance", json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let (mut opacity, mut multiplies) = (1.0_f32, 0); + s.doc().unwrap().doc.walk(|n| { + assert!(n.appearance.effects.iter().all(|e| !e.id.starts_with("plugin.")), "no plug-in effect left"); + opacity *= n.opacity; + multiplies += usize::from(n.blend == vectorcraft_color::BlendMode::Multiply); + }); + assert_eq!((opacity, multiplies), (0.5, 1), "the look applies once"); + let img = drawn(&s); + assert_eq!((img.pixel(50, 50), img.pixel(37, 50), img.pixel(32, 50)), (inside, grown, outside), "expanded, it draws the same"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(node(&s, id).appearance.effects[0].id, "plugin.test.engine.looks"); +} + /// On a fill, a painted effect returns only fills: they replace that fill on each piece. A result /// that breaks a rule (strokes from an effect on a fill, a swatch the document doesn't have) is /// refused whole: the object is drawn as if the effect weren't there, and `plugin.info` names the diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 35f29a2a25..5cce1b8beb 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -481,6 +481,44 @@ fn arb_object() -> impl Strategy, Value)> { }) } +/// The keys a piece or a fill or stroke of an effect that declares `appearanceOutput` may carry: +/// opacity, a blending mode (known, wrongly spelled or junk) and effect records (built-in ones +/// with random parameters, plug-in effects including the effect itself, junk), up to past the cap. +fn arb_look() -> impl Strategy> { + let id = prop_oneof![ + Just(json!("path.offsetPath")), + Just(json!("stylize.dropShadow")), + Just(json!("distort.twist")), + Just(json!("blur.gaussianBlur")), + Just(json!("threeD.extrude")), + Just(json!("plugin.fuzz.looks")), + arb_junk(), + ]; + let params = prop_oneof![Just(Value::Null), arb_num().prop_map(|n| json!({"offset": n, "angle": n, "radius": n, "opacity": n})), arb_junk()]; + let record = (id, params, prop::option::of(prop_oneof![any::().prop_map(Value::from), arb_junk()])).prop_map(|(id, params, visible)| { + let mut r = Map::new(); + r.insert("id".into(), id); + if !params.is_null() { + r.insert("params".into(), params); + } + if let Some(v) = visible { + r.insert("visible".into(), v); + } + Value::Object(r) + }); + let blend = prop_oneof![Just(json!("Multiply")), Just(json!("Screen")), Just(json!("multiply")), arb_junk()]; + let effects = prop_oneof![prop::collection::vec(record, 0..20).prop_map(Value::from), arb_junk()]; + (prop::option::of(arb_num()), prop::option::of(blend), prop::option::of(effects)).prop_map(|(opacity, blend, effects)| { + let mut m = Map::new(); + for (k, v) in [("opacity", opacity), ("blend", blend), ("effects", effects)] { + if let Some(v) = v { + m.insert(k.into(), v); + } + } + m + }) +} + /// The output document: objects (ids resolved against `inputs`; out-of-range indices become /// unknown ids), or junk. fn output(objects: &[(Option, Value)], inputs: &[u64], junk: Option) -> String { @@ -559,6 +597,50 @@ proptest! { renders(&s, &out)?; } + /// A live effect that declares `appearanceOutput` returning pieces whose own looks, and their + /// first fill's, are hostile, on objects or on a fill: drawing, export and Expand Appearance + /// never crash. + #[test] + fn hostile_piece_looks_never_crash( + objects in prop::collection::vec((arb_object(), arb_look(), prop::option::of(arb_look())), 0..4), + on_fill in any::(), + ) { + let mut s = rich_session(); + s.execute("select.all", &json!({})).unwrap(); + let pieces: Vec<(Option, Value)> = objects + .into_iter() + .map(|((_, mut o), look, fill_look)| { + if let Some(m) = o.as_object_mut() { + m.remove("name"); + m.extend(look); + if let (Some(fl), Some(Value::Array(fills))) = (fill_look, m.get_mut("fills")) + && let Some(first) = fills.first_mut() + { + let mut row = Map::new(); + row.insert("paint".into(), first.take()); + row.extend(fl); + *first = Value::Object(row); + } + } + (None, o) + }) + .collect(); + let out = output(&pieces, &[], None); + let manifest = r#"{"id":"fuzz.looks","name":"Fuzz","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{}}"#; + install(&mut s, &wat::parse_str(tpl::returning(manifest, &out)).unwrap()).unwrap(); + let item = if on_fill { json!(0) } else { Value::Null }; + let r = catch_quiet(|| s.execute("effect.apply", &json!({"effect": "plugin.fuzz.looks", "item": item})).map(|_| ())); + if let Err(msg) = r { + return Err(TestCaseError::fail(format!("panicked on {out}: {msg}"))); + } + renders(&s, &out)?; + let r = catch_quiet(|| s.execute("effect.expandAppearance", &json!({})).map(|_| ())); + if let Err(msg) = r { + return Err(TestCaseError::fail(format!("expanding panicked on {out}: {msg}"))); + } + renders(&s, &out)?; + } + /// An importer's hostile output (`document.open`) either opens a document that renders and /// exports, or is an error that opens nothing. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index d69f1d80bc..8df435bac4 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -327,8 +327,8 @@ capability model proposed for PhotoCraft plug-ins - `api` is the plug-in API level the manifest is written for: `1` (the default), `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects), or `3`, which - adds a painted live effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces). A higher one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for - are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the + adds a painted live effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces). A higher one is refused. + `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. A level 2 effect that declares `paintOutput` needs no other permission than `doc.read` and `effect.render`. - Parameter declarations are unchanged by permissions (`params`, below). @@ -562,10 +562,11 @@ the module's start function, in a run that isn't a filter's run on a document, o geometry, at any level. Hosts at `api` 1 refuse the manifest for its `api`, so such an effect never draws unpainted there. A painted effect may say `"api": 3` without other changes. - `appearanceOutput` (painted live effects at `api` 3 only): `true` lets the pieces, and the fills and strokes they - return, carry [opacity, a blending mode and effects](#opacity-blending-and-effects-on-pieces). `true` is the only value - the key takes; `false`, `null`, another type, an effect without `paintOutput`, another kind or an `api` below 3 is - refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond - `doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its `api`, so such an effect never draws without its looks. + return, carry [opacity, a blending mode and effects](#opacity-blending-and-effects-on-pieces). `true` is the only + value the key takes; `false`, `null`, another type, an effect without `paintOutput`, another kind or an `api` below 3 + is refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond + `doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its + `api`, so such an effect never draws without its looks. - `extensions` (exporters and importers only, and required): 1–8 file extensions, lower-case letters and digits without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and @@ -816,8 +817,9 @@ is a piece drawn by itself, in the order returned, with paints of its own: - `path` is required; `fillRule` defaults to the object's. `type` and `bounds` may be handed back as given and are ignored. Any other key (`opacity`, `effects`, `guide`, `locked`, `name`, a top-level `documentData`…) refuses the - result (an effect that declares `appearanceOutput` also takes `opacity`, `blend` and `effects`, [below](#opacity-blending-and-effects-on-pieces)), as does a key that a paint, its color, a gradient stop, a gradient's placement or a freeform point does not - have, such as `opacity` on a solid paint. + result (an effect that declares `appearanceOutput` also takes `opacity`, `blend` and `effects`, + [below](#opacity-blending-and-effects-on-pieces)), as does a key that a paint, its color, a gradient stop, a gradient's + placement or a freeform point does not have, such as `opacity` on a solid paint. - `fills` and `strokes` take the forms a filter returns ([Input](#input)). A piece without `fills` (or `strokes`) is painted with the ones the effect was given; an empty list paints none. Given ones replace the object's in order, as a filter's output sets them: an existing fill or stroke keeps its own effects, opacity and blending, and a new stroke @@ -877,15 +879,18 @@ fill and stroke the piece returns, three more keys: `axes` and `name`, a Warp's `version`, a `color`, a Levels or Curves `channel`, a Radial Blur's center and the Pathfinder Options. Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke - returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a piece carries never - run a plug-in. + returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), + this effect's own included, is refused, so the effects a piece carries never run a plug-in. - Left out, a piece's opacity is the object's, its blending mode Normal and its effects none; a fill or stroke keeps the opacity, blending and effects it would have without the keys. Given, a piece's opacity multiplies the object's, and its effects and a fill's or stroke's come after the ones it already has. The object's own opacity, blending mode and later effects still apply once to all the pieces together. - A piece's geometry effects reshape it before the effects after this one in the object's stack, which then run on the reshaped piece once. Its raster effects draw on the piece. What the geometry effects make counts against the - budget of the object's geometry effects, with the pieces. + budget of the object's geometry effects, with the pieces: each piece's effects run within what the pieces and the + pieces before it leave of it. When a piece's effects would go past that, or a Transform effect would make fewer + copies than it asks for, the pieces after it are not built, none of the effect's pieces are drawn, and the object, or + the fill or stroke the effect is on, draws the geometry it was given. - A bad value refuses the whole result as any other fault does, naming the field: for example `objects[1].blend: unknown blending mode; …` or `objects[0].fills[1].effects[2]: plug-in effects are not allowed in returned effects`. Without `appearanceOutput`, the three keys are refused as before. From e90e860f80ab8b8866c9a1c75d77258f46101235 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:24:56 -0800 Subject: [PATCH 018/106] Plug-ins: a piece's raster effects follow its Transform effect, and pieces take no Pathfinder effect A raster effect that a painted live-effect plug-in lists on a piece before a Transform effect now follows that Transform, as an object's raster effects do once its geometry effects are applied: a Drop Shadow before a scale of 200% draws at twice its offset. Before, it kept the offset and size it had before the Transform. A Pathfinder effect (pathfinder.*) in a piece's effects now refuses the result, naming the field. A piece is one path, so the effect had nothing to combine and was never drawn. Docs: docs/plugins.md. --- crates/effects/src/params.rs | 15 ++++------- crates/effects/src/reshape.rs | 6 +++-- crates/effects/src/tests/painted.rs | 40 ++++++++++++++++++++++++----- docs/plugins.md | 28 ++++++++++---------- 4 files changed, 58 insertions(+), 31 deletions(-) diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 232924508c..e7b1912bbb 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -119,7 +119,7 @@ pub fn new_effect(id: &str, params: &Value) -> Option { /// Checks an effect record that a painted live-effect plug-in returns on a piece, or on one of its /// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other -/// than a 3D effect, a raster effect only on a fill or stroke, and parameters that effect takes. A +/// than a 3D or Pathfinder effect, a raster effect only on a fill or stroke, and parameters that effect takes. A /// parameter is one its defaults or its parameter documentation name, of the type its default has, /// within the range its documentation gives ([`crate::catalog::any_documented_range`]); a texture is one as `effect.list` /// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself @@ -134,6 +134,9 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { if is_three_d(&e.id) { return Err("3D effects are not allowed in returned effects".into()); } + if is_pathfinder(&e.id) { + return Err("Pathfinder effects are not allowed in returned effects; a piece is one path, with nothing to combine".into()); + } if row && !is_raster(&e.id) { return Err(format!("{:?} is not a raster effect; a fill or stroke takes raster effects only", e.id)); } @@ -173,7 +176,7 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { /// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in /// returned, that `effect.apply` also checks: an SVG filter's XML, `scale`, `origin`, `axes` and /// `name`; a Warp's `version`; a `color` the effect can draw; a Levels or Curves `channel`; a Radial -/// Blur's center; Pathfinder Options; and the type of each parameter without a default. +/// Blur's center; and the type of each parameter without a default. fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number()); let switch = |key: &str| given.get(key).is_some_and(|v| !v.is_boolean()); @@ -214,14 +217,6 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str } } } - if crate::takes_pathfinder_options(id) { - if given.get("precision").is_some_and(|v| !v.as_f64().is_some_and(|p| crate::PATHFINDER_EFFECT_PRECISION.contains(&p))) { - return Err("precision must be from 0.001 to 10 pt".into()); - } - if let Some(key) = ["removeRedundantPoints", "removeUnpainted"].into_iter().find(|k| switch(k)) { - return Err(format!("`{key}` must be true or false")); - } - } let numbers: &[&str] = match id { "stylize.scribble" => &["variation"], "path.outlineStroke" => &["width"], diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 1107685578..94c1d359a8 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -2604,8 +2604,10 @@ pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::L if let Some(b) = look.blend { one.blend = b; } - let (shape, rest): (Vec, Vec) = look.effects.iter().cloned().partition(|e| e.visible && is_geometry(&e.id)); - one.appearance.effects.extend(rest); + let shape: Vec = look.effects.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect(); + // The raster effects before a Transform effect follow it, as an object's do once its geometry + // effects are applied ([`crate::raster::without_geometry`]); hidden records stay as they are. + one.appearance.effects.extend(crate::raster::followed(&look.effects).iter().filter(|e| !(e.visible && is_geometry(&e.id))).cloned()); let mut extra = none; if !shape.is_empty() { let before = art_cost(one); diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 775205408c..663c1ea199 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -270,9 +270,9 @@ fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() { } /// The host takes a built-in effect with parameters it has, of their type and in range, on a piece, -/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, an unknown -/// effect or parameter, a value of another type or out of range, and a geometry effect on a fill -/// or stroke. +/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, a Pathfinder +/// effect (a piece is one path, with nothing to combine), an unknown effect or parameter, a value +/// of another type or out of range, and a geometry effect on a fill or stroke. #[test] fn returned_effects_are_built_in_effects_with_their_own_parameters() { let e = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true }; @@ -283,7 +283,7 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(())); assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(())); // Every effect's own defaults pass the check, so each documented range holds its default. - for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id)) { + for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) { assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id); } for (effect, row) in [ @@ -291,6 +291,8 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { (e("path.offsetPath", json!({"offset": null})), false), (e("plugin.test.effects.self", json!({})), false), (e("threeD.extrude", json!({})), false), + (e("pathfinder.add", serde_json::Value::Null), false), + (e("pathfinder.divide", json!({"precision": 1.0})), false), (e("stylize.nope", json!({})), false), (e("path.offsetPath", json!({"inset": 4.0})), false), (e("path.offsetPath", json!({"offset": "4"})), false), @@ -300,6 +302,8 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ] { assert!(check(&effect, row).is_err(), "{effect:?} on a fill or stroke: {row}"); } + let why = check(&e("pathfinder.add", serde_json::Value::Null), false).unwrap_err(); + assert!(why.contains("Pathfinder effects are not allowed"), "{why}"); // The values `effect.apply` checks for one effect are refused with the parameter named. for (id, params, key) in [ (crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"), @@ -310,8 +314,6 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.dropShadow", json!({"color": "#zz0000"}), "color"), ("adjust.levels", json!({"channel": "cyan"}), "channel"), ("blur.radial", json!({"centerX": 1.5}), "centerX"), - ("pathfinder.add", json!({"precision": 20.0}), "precision"), - ("pathfinder.add", json!({"removeUnpainted": 1}), "removeUnpainted"), ("blur.gaussian", json!({"linear": 1}), "linear"), ("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"), ("distort.twist", json!({"angle": 4000.0}), "angle"), @@ -523,6 +525,32 @@ fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() { assert_eq!(blends, [BlendMode::Screen]); } +/// A piece's raster effect listed before its Transform effect follows the Transform, as an +/// object's does: a Drop Shadow before a scale of 200% keeps twice its offset. A hidden record +/// stays as it is. +#[test] +fn a_piece_s_raster_effects_follow_its_transform_effect() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let hidden = Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: false }; + let look = vectorcraft_plugins::painted::Look { + effects: vec![ + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true }, + hidden.clone(), + Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true }, + ], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap(); + let mut kept = vec![]; + n.walk(&mut |c| kept.extend(c.appearance.effects.iter().cloned())); + let shadow = kept.iter().find(|e| e.id == "stylize.dropShadow").expect("the piece keeps its Drop Shadow"); + let at = |k: &str| shadow.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN); + assert!((at("x") - 6.0).abs() < 1e-9 && (at("y") - 8.0).abs() < 1e-9, "{shadow:?}"); + assert_eq!(kept.iter().filter(|e| **e == hidden).count(), 1, "{kept:?}"); + assert!(kept.iter().all(|e| e.id != "distort.transform"), "{kept:?}"); +} + /// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's /// Offset Path runs on it alone, so the plug-in runs once and the square moves once. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 8df435bac4..ec9a71079d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -873,24 +873,26 @@ fill and stroke the piece returns, three more keys: `{"id", "params"?, "visible"?}`, and one result carries at most 4,096 of them over all its pieces, fills and strokes. - A fill that carries any of them is written `{"paint": , "opacity"?, "blend"?, "effects"?}`; a fill without them may stay a bare paint. A stroke takes them beside its `paint`, `width`, `join`, `cap` and `miterLimit`. -- An effect record names a built-in effect that `effect.list` lists, other than a 3D effect, with parameters that - effect takes, each of the type of its default and within the range `effect.list` gives for it, where it gives one. - The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, - `axes` and `name`, a Warp's `version`, a `color`, a Levels or Curves `channel`, a Radial Blur's center and the - Pathfinder Options. Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are - taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke - returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), - this effect's own included, is refused, so the effects a piece carries never run a plug-in. +- An effect record names a built-in effect that `effect.list` lists, other than a 3D effect or a Pathfinder effect + (`pathfinder.*`, which has nothing to combine on a piece's one path), with parameters that effect takes, each of the + type of its default and within the range `effect.list` gives for it, where it gives one. The values `effect.apply` + checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a + Warp's `version`, a `color`, a Levels or Curves `channel` and a Radial Blur's center. Omitted parameters take the + effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: + the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its + pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a + piece carries never run a plug-in. - Left out, a piece's opacity is the object's, its blending mode Normal and its effects none; a fill or stroke keeps the opacity, blending and effects it would have without the keys. Given, a piece's opacity multiplies the object's, and its effects and a fill's or stroke's come after the ones it already has. The object's own opacity, blending mode and later effects still apply once to all the pieces together. - A piece's geometry effects reshape it before the effects after this one in the object's stack, which then run on - the reshaped piece once. Its raster effects draw on the piece. What the geometry effects make counts against the - budget of the object's geometry effects, with the pieces: each piece's effects run within what the pieces and the - pieces before it leave of it. When a piece's effects would go past that, or a Transform effect would make fewer - copies than it asks for, the pieces after it are not built, none of the effect's pieces are drawn, and the object, or - the fill or stroke the effect is on, draws the geometry it was given. + the reshaped piece once. Its raster effects draw on the piece, and those listed before a Transform effect follow it + as an object's do: a Drop Shadow before a scale of 200% draws at twice its offset. What the geometry effects make + counts against the budget of the object's geometry effects, with the pieces: each piece's effects run within what + the pieces and the pieces before it leave of it. When a piece's effects would go past that, or a Transform effect + would make fewer copies than it asks for, the pieces after it are not built, none of the effect's pieces are drawn, + and the object, or the fill or stroke the effect is on, draws the geometry it was given. - A bad value refuses the whole result as any other fault does, naming the field: for example `objects[1].blend: unknown blending mode; …` or `objects[0].fills[1].effects[2]: plug-in effects are not allowed in returned effects`. Without `appearanceOutput`, the three keys are refused as before. From 47495471c8f7ff945e9ec071115068195c79f5e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:54:08 -0800 Subject: [PATCH 019/106] Plug-ins: returned effects check comma-led ranges and Free Distort corners - A parameter documented right after a comma (Paint Daubs' `sharpness`) has its documented range checked, in returned effects and in distance and pixel ranges. - A returned Free Distort's `corners` must be four [x, y] pairs of finite numbers. - A piece's Transform effect with no copies and Scale Strokes & Effects on no longer counts as short of copies, so the piece is dressed and moves. - The painted-look rerun test moves the source in one document drawn by one renderer, and the plug-in returns a different piece for the moved source. --- crates/effects/src/catalog.rs | 10 +++- crates/effects/src/params.rs | 8 +++- crates/effects/src/reshape.rs | 2 +- crates/effects/src/tests/painted.rs | 24 +++++++++- crates/render/src/tests/paintedlook.rs | 63 ++++++++++++++++++-------- 5 files changed, 82 insertions(+), 25 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 69222c9ada..c79baa50e0 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -64,7 +64,7 @@ pub fn raster_px_range(id: &str, key: &str) -> Option Option> { let doc = catalog_index().get(id)?.params; - let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + let starts = |at: usize| starts_key(doc, at); doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; let rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?; @@ -88,7 +88,7 @@ pub(crate) fn any_documented_range(id: &str, key: &str) -> Option Option> { let doc = catalog_index().get(id)?.params; - let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' '); + let starts = |at: usize| starts_key(doc, at); let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| { let rest = doc.get(at + key.len()..)?; rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ') @@ -98,6 +98,12 @@ fn documented_range(id: &str, key: &str, unit: &str) -> Option bool { + doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| matches!(c, '{' | ' ' | ',')) +} + /// The distance parameters of effect `id` (none for unknown effects). fn lengths_of(id: &str) -> Lengths { let always = |always| Lengths { always, absolute: &[] }; diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index e7b1912bbb..4ac8d3dfde 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -174,8 +174,8 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { } /// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in -/// returned, that `effect.apply` also checks: an SVG filter's XML, `scale`, `origin`, `axes` and -/// `name`; a Warp's `version`; a `color` the effect can draw; a Levels or Curves `channel`; a Radial +/// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and +/// `name`; a Free Distort's four `corners`; a Warp's `version`; a `color` the effect can draw; a Levels or Curves `channel`; a Radial /// Blur's center; and the type of each parameter without a default. fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number()); @@ -200,6 +200,10 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str return Err("an SVG filter is named by its id: give `xml` with `name`".into()); } } + let pair = |p: &Value| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); + if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) { + return Err("`corners` must be four [x, y] pairs of numbers".into()); + } if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) { return Err(format!("`version` must be 0 or {}", crate::WARP_NET)); } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 94c1d359a8..1d28bec263 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1928,7 +1928,7 @@ impl Step<'_> { if options.objects { moved_ids.insert(leaf.id); } - short |= counts(leaf.id) && copied(leaf) <= copies; + short |= copies > 0 && counts(leaf.id) && copied(leaf) <= copies; } else { kept_ids.insert(leaf.id); } diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 663c1ea199..a88d751e03 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -282,6 +282,8 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { assert_eq!(check(&e("stylize.dropShadow", json!({"x": 2.0})), true), Ok(())); assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(())); assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(())); + // A parameter documented right after a comma has its range checked too. + assert_eq!(check(&e("artistic.paintDaubs", json!({"sharpness": 25})), false), Ok(())); // Every effect's own defaults pass the check, so each documented range holds its default. for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) { assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id); @@ -297,6 +299,7 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { (e("path.offsetPath", json!({"inset": 4.0})), false), (e("path.offsetPath", json!({"offset": "4"})), false), (e("brushStrokes.accentedEdges", json!({"edgeWidth": 15.0})), false), + (e("artistic.paintDaubs", json!({"sharpness": 41})), false), (e("path.offsetPath", json!([4.0])), false), (e("path.offsetPath", json!({"offset": 4.0})), true), ] { @@ -304,7 +307,7 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { } let why = check(&e("pathfinder.add", serde_json::Value::Null), false).unwrap_err(); assert!(why.contains("Pathfinder effects are not allowed"), "{why}"); - // The values `effect.apply` checks for one effect are refused with the parameter named. + // The values checked for one effect are refused with the parameter named. for (id, params, key) in [ (crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"), (crate::SVG_FILTER, json!({"scale": 0.0}), "scale"), @@ -317,6 +320,8 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("blur.gaussian", json!({"linear": 1}), "linear"), ("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"), ("distort.twist", json!({"angle": 4000.0}), "angle"), + ("distort.freeDistort", json!({"corners": []}), "corners"), + ("distort.freeDistort", json!({"corners": [[0, 0], [1, 0], [1, 1], [0]]}), "corners"), ] { let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}")); assert!(why.contains(key), "{id} {params}: {why}"); @@ -551,6 +556,23 @@ fn a_piece_s_raster_effects_follow_its_transform_effect() { assert!(kept.iter().all(|e| e.id != "distort.transform"), "{kept:?}"); } +/// A piece's Transform effect with no copies and Scale Strokes & Effects on moves the piece: no +/// copies were asked for, so none are missing. +#[test] +fn a_piece_s_transform_without_copies_scaling_strokes_moves_it() { + let mut n = + Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let look = vectorcraft_plugins::painted::Look { + effects: vec![Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 0, "strokes": true}), visible: true }], + ..Default::default() + }; + crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed"); + let mut paths = vec![]; + n.walk(&mut |c| paths.extend(c.path_data().and_then(PathData::bounds))); + assert_eq!(paths.len(), 1, "{paths:?}"); + assert!((paths[0].x0 - 30.0).abs() < 0.5 && (paths[0].x1 - 50.0).abs() < 0.5, "{paths:?}"); +} + /// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's /// Offset Path runs on it alone, so the plug-in runs once and the square moves once. #[test] diff --git a/crates/render/src/tests/paintedlook.rs b/crates/render/src/tests/paintedlook.rs index 06064a8849..d7ce8284c6 100644 --- a/crates/render/src/tests/paintedlook.rs +++ b/crates/render/src/tests/paintedlook.rs @@ -14,23 +14,37 @@ fn square_at(x: f64) -> PathData { PathData::single(SubPath::polyline(&[Point::new(x, 40.0), Point::new(x + 20.0, 40.0), Point::new(x + 20.0, 60.0), Point::new(x, 60.0)], true)) } -/// Installs live-effect plug-in `id`, which declares `appearanceOutput` and returns one piece: the -/// square at 120, 40 filled red, with `look`'s keys added to it. -fn install(id: &str, look: serde_json::Value) { - use vectorcraft_plugins::wat as tpl; +/// The output of a plug-in that returns one piece: the square at `x`, 40 filled red, with `look`'s +/// keys added to it. +fn output(x: f64, look: &serde_json::Value) -> String { let red = serde_json::to_value(Paint::solid(Color::rgb(1.0, 0.0, 0.0))).unwrap(); - let mut piece = json!({"path": square_at(120.0), "fills": [red]}); + let mut piece = json!({"path": square_at(x), "fills": [red]}); if let (Some(p), Some(l)) = (piece.as_object_mut(), look.as_object()) { p.extend(l.clone()); } - let output = json!({ "objects": [piece] }).to_string(); - let manifest = format!( - r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"# - ); - let module = wat::parse_str(tpl::returning(&manifest, &output)).unwrap(); + json!({ "objects": [piece] }).to_string() +} + +/// The manifest of live-effect plug-in `id`, which declares `appearanceOutput`. +fn manifest(id: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#) +} + +/// Installs live-effect plug-in `id`, which returns one piece: the square at 120, 40 filled red, +/// with `look`'s keys added to it. +fn install(id: &str, look: serde_json::Value) { + let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest(id), &output(120.0, &look))).unwrap(); vectorcraft_plugins::registry::install_bytes(&module).unwrap(); } +/// Installs live-effect plug-in `id` as [`install`] does, except that it returns the square at 160, +/// 40 when its input holds the text `moved`. +fn install_moving(id: &str, look: serde_json::Value, moved: &str) { + use vectorcraft_plugins::wat as tpl; + let module = tpl::when_given_else(&manifest(id), tpl::Given::Input, moved, &output(160.0, &look), &output(120.0, &look)); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(module).unwrap()).unwrap(); +} + /// A document with a blue rectangle over all of it and, above it, the square at `x`, 40 filled /// green with live-effect plug-in `plugin` as its own effect. fn document(plugin: &str, x: f64) -> Document { @@ -51,8 +65,13 @@ fn document(plugin: &str, x: f64) -> Document { /// The color a new renderer draws `d` with at (`x`, `y`). fn pixel(d: &Document, x: f64, y: f64) -> [u8; 4] { + pixel_with(&mut Renderer::new(), d, x, y) +} + +/// The color renderer `r` draws `d` with at (`x`, `y`). +fn pixel_with(r: &mut Renderer, d: &Document, x: f64, y: f64) -> [u8; 4] { let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; - Renderer::new().render(d, 1, 1, Affine::translate((-x, -y)), &opts).pixel(0, 0) + r.render(d, 1, 1, Affine::translate((-x, -y)), &opts).pixel(0, 0) } fn near(got: [u8; 4], want: [u8; 3]) -> bool { @@ -60,18 +79,24 @@ fn near(got: [u8; 4], want: [u8; 3]) -> bool { } /// A piece at 50% opacity with Multiply draws red multiplied with the blue under it (black) at -/// half strength: half blue. Moved, the source runs the plug-in again, and the new piece draws the +/// half strength: half blue. Moved in the same document and drawn by the same renderer, the source +/// runs the plug-in again, which now returns the square at 160, 40, and the new piece draws the /// same way. Without the look the piece is plain red. #[test] fn a_piece_s_opacity_and_blending_mode_draw_and_survive_a_rerun() { const ID: &str = "test.render.paintedlook.multiply"; - install(ID, json!({"opacity": 0.5, "blend": "Multiply"})); - for x in [0.0, 2.0] { - let d = document(ID, x); - let p = pixel(&d, 130.0, 50.0); - assert!(near(p, [0, 0, 128]), "source at {x}: {p:?}"); - assert!(near(pixel(&d, 10.0, 50.0), [0, 0, 255]), "the source is not drawn"); - } + install_moving(ID, json!({"opacity": 0.5, "blend": "Multiply"}), "33.25"); + let mut d = document(ID, 0.0); + let source = d.layers[0].children().and_then(|c| c.last()).map(|n| n.id).unwrap(); + let mut r = Renderer::new(); + let p = pixel_with(&mut r, &d, 130.0, 50.0); + assert!(near(p, [0, 0, 128]), "before the move: {p:?}"); + assert!(near(pixel_with(&mut r, &d, 10.0, 50.0), [0, 0, 255]), "the source is not drawn"); + d.node_mut(source).unwrap().transform(Affine::translate((33.25, 0.0)), false); + let p = pixel_with(&mut r, &d, 170.0, 50.0); + assert!(near(p, [0, 0, 128]), "after the move: {p:?}"); + assert!(near(pixel_with(&mut r, &d, 130.0, 50.0), [0, 0, 255]), "the earlier piece is not drawn"); + assert!(near(pixel_with(&mut r, &d, 43.0, 50.0), [0, 0, 255]), "the moved source is not drawn"); assert_eq!(vectorcraft_plugins::effect::last_error(ID), None); install(ID, json!({})); assert!(near(pixel(&document(ID, 4.0), 130.0, 50.0), [255, 0, 0])); From 3f6bd6a0e135598cf74011a32e8edc2d7b7ae182 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:38:37 -0800 Subject: [PATCH 020/106] Toolbars: a rerun of a frame keeps its check budget, and a command that needs a path gets no button Known::load reset the budget of 12 availability checks on every call, so a request_discard pass of the same frame asked 12 more. The budget is now reset only when ctx.cumulative_frame_nr() changes. ui_listed_on_its_own exempted every params doc starting with {path, which took in Save Summary... ({path}) and the Scripts folder command ({path: ...}). Both need a path, but ui_command_needs_params returned false for them, so Save Summary... was offered as a toolbar button and in Keyboard Shortcuts and ran with empty params. Only the optional {path? form is exempt now. --- crates/ui-egui/src/custom_toolbars.rs | 37 +++++++++++++++++++++++++-- crates/ui-egui/src/shortcut_editor.rs | 26 ++++++++++++++++--- 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 72edd613ae..bc7b6b2e58 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -846,6 +846,8 @@ struct Known { stale: std::collections::HashMap>, /// How many more commands this frame may ask. budget: usize, + /// The frame `budget` was set for; a later pass of the same frame keeps what is left of it. + frame: Option, /// Is a command still waiting to be asked in this state? pending: bool, } @@ -853,7 +855,8 @@ struct Known { impl Known { /// The answers for the state now. The state leaves out a panel shown and a tool chosen, so a /// frame with a pointer button release or a key press asks every command again, as the Command - /// Palette asks its results again on a click. + /// Palette asks its results again on a click. Every pass of one frame (a `request_discard` + /// rerun) shares that frame's [`ASKS_PER_FRAME`]. fn load(app: &VectorcraftApp, ctx: &egui::Context) -> Known { let key = crate::palette::availability_key(app); let mut known = ctx.data(|d| d.get_temp::(known_id())).unwrap_or_default(); @@ -865,7 +868,11 @@ impl Known { known.stale.extend(old); known.key = key; } - known.budget = ASKS_PER_FRAME; + let frame = ctx.cumulative_frame_nr(); + if known.frame != Some(frame) { + known.budget = ASKS_PER_FRAME; + known.frame = Some(frame); + } known.pending = false; known } @@ -3130,4 +3137,30 @@ mod tests { assert_eq!(place(&app, "Mine"), (None, false), "released outside its lane"); assert!(ctx.memory(|m| m.area_rect(area_id("Mine"))).unwrap().contains(out)); } + + /// A `request_discard` rerun of a frame asks no more commands than are left of that frame's + /// [`ASKS_PER_FRAME`]; the next frame may ask that many again. + #[test] + fn a_rerun_of_a_frame_shares_its_checks() { + let app = app(); + let ctx = egui::Context::default(); + let mut left = vec![]; + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx(); + let mut known = Known::load(&app, ctx); + for i in 0..ASKS_PER_FRAME - 2 { + let id = format!("tool:probe-{}-{i}", left.len()); + known.why(&app, &id, &id); + } + left.push(known.budget); + ctx.data_mut(|d| d.insert_temp(known_id(), known)); + if left.len() == 1 { + ctx.request_discard("a second pass"); + } + }); + out.textures_delta.clear(); + } + assert_eq!(left, [2, 0, 2], "the rerun used what was left; the next frame started anew"); + } } diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index c4bfb9f835..59da1f22f3 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1011,11 +1011,12 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { /// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts /// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc -/// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs -/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in -/// front. +/// of `{}` or `{path?…}`, where a call with no path picks a file. A params doc of `{path}` or +/// `{path: …}` (Save Summary…, a Scripts folder script) needs a path, so a key press alone can't +/// run it. Rename has no default key, and a key press names the selection: it needs no `id`. Color +/// Picker… has no default key either, and a key press opens it for the proxy in front. fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool { - !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker" + !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path?") || id == "ui.rename" || id == "ui.colorPicker" } /// Does a menu bar item run the command with no params, so that it does what its label says and opens @@ -3429,6 +3430,23 @@ mod tests { assert!(failures.is_empty(), "{failures:#?}"); } + /// A UI command whose params doc starts `{path}` or `{path: …}` needs a path, so it is neither + /// listed on its own nor offered as a button; one that starts `{path?` picks a file without one. + #[test] + fn a_ui_command_that_needs_a_path_is_not_run_without_one() { + for id in ["ui.pdfSummary.save", crate::scripts_menu::COMMAND] { + let (_, _, sc, params) = menus::UI_COMMANDS.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{id} is a UI command")); + assert!(!ui_listed_on_its_own(id, sc, params), "{id} is not listed on its own"); + assert!(ui_command_needs_params(id), "{id} needs a path"); + assert!(!crate::palette::is_command(id), "{id} is not offered as a toolbar button"); + } + for id in ["shortcuts.export", "file.open"] { + let (_, _, sc, params) = menus::UI_COMMANDS.iter().find(|c| c.0 == id).unwrap_or_else(|| panic!("{id} is a UI command")); + assert!(ui_listed_on_its_own(id, sc, params) || a_menu_bar_item_runs(id, params), "{id} runs without a path"); + assert!(!ui_command_needs_params(id), "{id} picks a file without a path"); + } + } + /// #2991: Enter Isolation Mode has no default key but runs on the selection, so it belongs in /// Edit › Keyboard Shortcuts. #[test] From c1f74eeeb18ecb73045e9b812889f4c5d6cc90b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:20:51 -0800 Subject: [PATCH 021/106] Plug-ins: returned effects check listed choices, blend modes, colors and two more ranges An effect record a painted live effect returns now has each parameter that `effect.list` documents as a list of choices checked against that list, so Roughen's `points` takes only "smooth" or "corner". A Drop Shadow's, Inner Glow's or Outer Glow's `mode` must name a blend mode. An unknown name was drawn as Normal before. A `color` is taken as [r, g, b] or a color object as well as "#rrggbb", as `effect.apply` takes it; the check of its default's type refused those forms before. Pucker & Bloat's `amount` and Temperature/Tint's `temperature` and `tint` are documented as `lo..hi` ranges, so a returned value outside -200..200 or -100..100 is refused. The effects already clamp to these ranges. --- crates/effects/src/catalog.rs | 28 +++++++++++++++++++++++++-- crates/effects/src/params.rs | 18 +++++++++++++++-- crates/effects/src/raster.rs | 7 ++++++- crates/effects/src/tests/painted.rs | 30 +++++++++++++++++++++++++++++ docs/plugins.md | 6 ++++-- 5 files changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index c79baa50e0..47599c02c4 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -85,6 +85,30 @@ pub(crate) fn any_documented_range(id: &str, key: &str) -> Option Option> { + let doc = catalog_index().get(id)?.params; + doc.match_indices(key).map(|(at, _)| at).filter(|at| starts_key(doc, *at)).find_map(|at| { + let rest = doc.get(at + key.len()..)?; + let mut rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?; + let mut choices = vec![]; + while let Some((choice, after)) = rest.strip_prefix('"').and_then(|r| r.split_once('"')) { + choices.push(choice); + let after = match after.strip_prefix(" (") { + Some(note) => note.get(note.find(')')? + 1..)?, + None => after, + }; + match after.strip_prefix('|') { + Some(next) => rest = next, + None => break, + } + } + (choices.len() >= 2).then_some(choices) + }) +} + /// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`). fn documented_range(id: &str, key: &str, unit: &str) -> Option> { let doc = catalog_index().get(id)?.params; @@ -290,7 +314,7 @@ pub fn effect_catalog() -> Vec { "{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]]; placed gradients move and scale from the object's bounds to its distorted bounds)}", json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}), ), - g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})), + g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % -200..200 (0; -200 puckers, 200 bloats)}", json!({"amount": 0.0})), g( "distort.roughen", "Roughen…", @@ -841,7 +865,7 @@ pub fn effect_catalog() -> Vec { "adjust.temperatureTint", "Temperature/Tint…", ADJUST, - "{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does", + "{temperature: -100..100 (0; -100 cooler, 100 warmer), tint: -100..100 (0; -100 greener, 100 more magenta)} recolours as Brightness/Contrast does", json!({"temperature": 0.0, "tint": 0.0}), ), ]); diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 4ac8d3dfde..93c5e2a502 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -121,7 +121,8 @@ pub fn new_effect(id: &str, params: &Value) -> Option { /// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other /// than a 3D or Pathfinder effect, a raster effect only on a fill or stroke, and parameters that effect takes. A /// parameter is one its defaults or its parameter documentation name, of the type its default has, -/// within the range its documentation gives ([`crate::catalog::any_documented_range`]); a texture is one as `effect.list` +/// within the range its documentation gives ([`crate::catalog::any_documented_range`]) and one of the +/// choices it lists ([`crate::catalog::documented_choices`]); a texture is one as `effect.list` /// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself /// included, is refused, so the effects a plug-in returns never run a plug-in. pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { @@ -152,8 +153,11 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { return Err(format!("`{key}` is not a parameter of {:?}", e.id)); } let kind = |v: &Value| std::mem::discriminant(v); + // A `color` is checked as a color, in any form the effect draws ([`is_color`]). + let color = key == "color" && default.is_some_and(Value::is_string); if let Some(d) = default && !d.is_null() + && !color && kind(d) != kind(v) { return Err(format!("`{key}` must be of the type its default {d} has")); @@ -164,6 +168,11 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { { return Err(format!("`{key}` must be from {} to {}", r.start(), r.end())); } + if let Some(choices) = crate::catalog::documented_choices(&e.id, key) + && !v.as_str().is_some_and(|v| choices.contains(&v)) + { + return Err(format!("`{key}` must be one of \"{}\"", choices.join("\", \""))); + } } if let Some(t) = given.get(crate::pixel::TEXTURE_IMAGE) && t.as_str().is_none_or(|t| crate::pixel::texture(t).is_none()) @@ -175,7 +184,8 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { /// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in /// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and -/// `name`; a Free Distort's four `corners`; a Warp's `version`; a `color` the effect can draw; a Levels or Curves `channel`; a Radial +/// `name`; a Free Distort's four `corners`; a Warp's `version`; a `color` the effect can draw; a +/// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial /// Blur's center; and the type of each parameter without a default. fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number()); @@ -211,6 +221,10 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str if takes_color && given.get("color").is_some_and(|v| !is_color(v)) { return Err("`color` must be a #rrggbb color".into()); } + let takes_blend_mode = catalog_index().get(id).is_some_and(|info| info.params.contains("mode: blend mode")); + if takes_blend_mode && given.get("mode").is_some_and(|v| v.as_str().and_then(crate::raster::named_blend_mode).is_none()) { + return Err("`mode` must be a blend mode, such as \"multiply\" or \"screen\"".into()); + } if matches!(id, "adjust.levels" | "adjust.curves") && given.get("channel").is_some_and(|v| !v.as_str().is_some_and(crate::is_channel)) { return Err(format!("`channel` must be one of {}", crate::CHANNELS.join(", "))); } diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index 6948d0f977..c72391e56d 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -365,8 +365,13 @@ impl Rasterize { /// Parse a blend mode name (`"multiply"`, `"Screen"`, `"color-burn"`…). pub fn blend_mode(s: &str) -> BlendMode { + named_blend_mode(s).unwrap_or(BlendMode::Normal) +} + +/// The blend mode `s` names as [`blend_mode`] reads it; `None` when it names none. +pub(crate) fn named_blend_mode(s: &str) -> Option { let key: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); - BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key).unwrap_or(BlendMode::Normal) + BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key) } /// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object). diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index a88d751e03..c1f0105f6b 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -284,6 +284,22 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(())); // A parameter documented right after a comma has its range checked too. assert_eq!(check(&e("artistic.paintDaubs", json!({"sharpness": 25})), false), Ok(())); + // Each documented choice and each end of a documented range passes. + for (id, params) in [ + ("distort.roughen", json!({"points": "smooth"})), + ("distort.roughen", json!({"points": "corner"})), + ("distort.zigZag", json!({"points": "corner"})), + ("distort.puckerBloat", json!({"amount": -200})), + ("distort.puckerBloat", json!({"amount": 200})), + ("adjust.temperatureTint", json!({"temperature": -100, "tint": 100})), + ("stylize.dropShadow", json!({"mode": "color-burn"})), + ("stylize.outerGlow", json!({"mode": "Normal"})), + // A `color` is also taken as [r, g, b] 0..1 or a color object, as the effects draw it. + ("stylize.dropShadow", json!({"color": [1.0, 0.0, 0.0]})), + ("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})), + ] { + assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}"); + } // Every effect's own defaults pass the check, so each documented range holds its default. for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) { assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id); @@ -315,6 +331,9 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { (crate::SVG_FILTER, json!({"name": "f"}), "name"), ("warp.arc", json!({"version": 99}), "version"), ("stylize.dropShadow", json!({"color": "#zz0000"}), "color"), + ("stylize.dropShadow", json!({"color": [1.0, "0", 0.0]}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "rgb"}}), "color"), + ("stylize.outerGlow", json!({"color": true}), "color"), ("adjust.levels", json!({"channel": "cyan"}), "channel"), ("blur.radial", json!({"centerX": 1.5}), "centerX"), ("blur.gaussian", json!({"linear": 1}), "linear"), @@ -322,6 +341,17 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("distort.twist", json!({"angle": 4000.0}), "angle"), ("distort.freeDistort", json!({"corners": []}), "corners"), ("distort.freeDistort", json!({"corners": [[0, 0], [1, 0], [1, 1], [0]]}), "corners"), + ("distort.roughen", json!({"points": "invalid"}), "points"), + ("distort.zigZag", json!({"points": "Corner"}), "points"), + ("path.offsetPath", json!({"joins": "square"}), "joins"), + (crate::RASTERIZE, json!({"colorModel": "cmyk"}), "colorModel"), + (crate::CROP_MARKS, json!({"style": 1}), "style"), + ("distort.puckerBloat", json!({"amount": -201}), "amount"), + ("distort.puckerBloat", json!({"amount": 201}), "amount"), + ("adjust.temperatureTint", json!({"temperature": 101}), "temperature"), + ("adjust.temperatureTint", json!({"tint": -101}), "tint"), + ("stylize.dropShadow", json!({"mode": "not-a-mode"}), "mode"), + ("stylize.innerGlow", json!({"mode": "???"}), "mode"), ] { let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}")); assert!(why.contains(key), "{id} {params}: {why}"); diff --git a/docs/plugins.md b/docs/plugins.md index ec9a71079d..5fb19c4cc4 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -875,9 +875,11 @@ fill and stroke the piece returns, three more keys: them may stay a bare paint. A stroke takes them beside its `paint`, `width`, `join`, `cap` and `miterLimit`. - An effect record names a built-in effect that `effect.list` lists, other than a 3D effect or a Pathfinder effect (`pathfinder.*`, which has nothing to combine on a piece's one path), with parameters that effect takes, each of the - type of its default and within the range `effect.list` gives for it, where it gives one. The values `effect.apply` + type of its default, within the range `effect.list` gives for it, where it gives one, and one of the choices it + lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a - Warp's `version`, a `color`, a Levels or Curves `channel` and a Radial Blur's center. Omitted parameters take the + Warp's `version`, a `color`, a Levels or Curves `channel` and a Radial Blur's center. A Drop Shadow's, Inner + Glow's or Outer Glow's `mode` must name a blend mode (`"multiply"`, `"color-burn"`). Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a From 1e644a8251dc56b0d94006ea832deb6ebf3f0195 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:22:24 -0800 Subject: [PATCH 022/106] Plug-ins: returned effect colors keep their components from 0 to 1 A returned effect's `color` given as [r, g, b] now needs each of the first three components from 0 to 1, and a color object needs its components from 0 to 1 (a Lab color's lightness from 0 to 100), as the effects document them. [2, -1, 0] was taken before. --- crates/effects/src/params.rs | 16 ++++++++++++---- crates/effects/src/tests/painted.rs | 9 +++++++++ docs/plugins.md | 3 ++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 93c5e2a502..5d862ebe4a 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -219,7 +219,7 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str } let takes_color = catalog_index().get(id).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string)); if takes_color && given.get("color").is_some_and(|v| !is_color(v)) { - return Err("`color` must be a #rrggbb color".into()); + return Err("`color` must be a #rrggbb color, [r, g, b] from 0 to 1 or a color object".into()); } let takes_blend_mode = catalog_index().get(id).is_some_and(|info| info.params.contains("mode: blend mode")); if takes_blend_mode && given.get("mode").is_some_and(|v| v.as_str().and_then(crate::raster::named_blend_mode).is_none()) { @@ -250,15 +250,23 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str } /// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]` -/// with three numbers first, or a color object? +/// with three numbers from 0 to 1 first, or a color object with its components from 0 to 1 (a Lab +/// color's lightness from 0 to 100, and finite a and b)? /// /// [`Color::from_hex`]: vectorcraft_doc::color::Color::from_hex fn is_color(v: &Value) -> bool { use vectorcraft_doc::color::Color; + let unit = |x: f32| (0.0..=1.0).contains(&x); match v { Value::String(s) => Color::from_hex(s).is_some(), - Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number), - Value::Object(_) => serde_json::from_value::(v.clone()).is_ok(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|c| c.as_f64().is_some_and(|c| (0.0..=1.0).contains(&c))), + Value::Object(_) => match serde_json::from_value::(v.clone()) { + Ok(Color::Rgb { r, g, b }) => [r, g, b].into_iter().all(unit), + Ok(Color::Cmyk { c, m, y, k }) => [c, m, y, k].into_iter().all(unit), + Ok(Color::Gray { k }) => unit(k), + Ok(Color::Lab { l, a, b }) => (0.0..=100.0).contains(&l) && a.is_finite() && b.is_finite(), + Err(_) => false, + }, _ => false, } } diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index c1f0105f6b..3b02deff51 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -296,7 +296,10 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.outerGlow", json!({"mode": "Normal"})), // A `color` is also taken as [r, g, b] 0..1 or a color object, as the effects draw it. ("stylize.dropShadow", json!({"color": [1.0, 0.0, 0.0]})), + ("stylize.dropShadow", json!({"color": [1, 0, 0]})), ("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})), + ("stylize.innerGlow", json!({"color": {"model": "cmyk", "c": 0, "m": 1, "y": 0, "k": 0}})), + ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})), ] { assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}"); } @@ -334,6 +337,12 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.dropShadow", json!({"color": [1.0, "0", 0.0]}), "color"), ("stylize.innerGlow", json!({"color": {"model": "rgb"}}), "color"), ("stylize.outerGlow", json!({"color": true}), "color"), + // Color components are from 0 to 1, Lab's lightness from 0 to 100. + ("stylize.dropShadow", json!({"color": [2, -1, 0]}), "color"), + ("stylize.dropShadow", json!({"color": [0.5, 0.5, 1.01]}), "color"), + ("stylize.outerGlow", json!({"color": {"model": "rgb", "r": 2.0, "g": 0.0, "b": 0.0}}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "gray", "k": -0.5}}), "color"), + ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"), ("adjust.levels", json!({"channel": "cyan"}), "channel"), ("blur.radial", json!({"centerX": 1.5}), "centerX"), ("blur.gaussian", json!({"linear": 1}), "linear"), diff --git a/docs/plugins.md b/docs/plugins.md index 5fb19c4cc4..8de1192c3c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -878,7 +878,8 @@ fill and stroke the piece returns, three more keys: type of its default, within the range `effect.list` gives for it, where it gives one, and one of the choices it lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a - Warp's `version`, a `color`, a Levels or Curves `channel` and a Radial Blur's center. A Drop Shadow's, Inner + Warp's `version`, a `color` (`"#rrggbb"`, `[r, g, b]` with each component from 0 to 1, or a color object with + components from 0 to 1 and a Lab lightness from 0 to 100), a Levels or Curves `channel` and a Radial Blur's center. A Drop Shadow's, Inner Glow's or Outer Glow's `mode` must name a blend mode (`"multiply"`, `"color-burn"`). Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its From ff68f3553cd8d12addd7f39d8135067e369d5bf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:30:07 -0800 Subject: [PATCH 023/106] Plug-ins: returned Curves points take pairs, Transform counts whole numbers A returned Curves effect's `points` is now also taken as [[x, y], ...], the form the effect draws, each entry a pair of numbers. A returned Transform effect's `copies` and `reference` must be whole numbers; 1.5 copies drew one copy before. --- crates/effects/src/params.rs | 14 +++++++++++++- crates/effects/src/tests/painted.rs | 7 +++++++ docs/plugins.md | 13 +++++++------ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 5d862ebe4a..9130d746ae 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -155,9 +155,12 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { let kind = |v: &Value| std::mem::discriminant(v); // A `color` is checked as a color, in any form the effect draws ([`is_color`]). let color = key == "color" && default.is_some_and(Value::is_string); + // Curves' `points` is also taken as [[x, y], …], as the effect draws it. + let curve = e.id == "adjust.curves" && key == "points" && v.is_array(); if let Some(d) = default && !d.is_null() && !color + && !curve && kind(d) != kind(v) { return Err(format!("`{key}` must be of the type its default {d} has")); @@ -184,7 +187,8 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { /// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in /// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and -/// `name`; a Free Distort's four `corners`; a Warp's `version`; a `color` the effect can draw; a +/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs; a Transform's whole +/// `copies` and `reference`; a Warp's `version`; a `color` the effect can draw; a /// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial /// Blur's center; and the type of each parameter without a default. fn check_returned_values(id: &str, given: &Map) -> Result<(), String> { @@ -214,6 +218,14 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) { return Err("`corners` must be four [x, y] pairs of numbers".into()); } + if id == "adjust.curves" && given.get("points").and_then(Value::as_array).is_some_and(|p| !p.iter().all(pair)) { + return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers".into()); + } + if id == "distort.transform" + && let Some(key) = ["copies", "reference"].into_iter().find(|k| given.get(*k).and_then(Value::as_f64).is_some_and(|x| x.fract() != 0.0)) + { + return Err(format!("`{key}` must be a whole number")); + } if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) { return Err(format!("`version` must be 0 or {}", crate::WARP_NET)); } diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 3b02deff51..5792f9f233 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -300,6 +300,9 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})), ("stylize.innerGlow", json!({"color": {"model": "cmyk", "c": 0, "m": 1, "y": 0, "k": 0}})), ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})), + // Curves' `points` is also taken as [[x, y], …], and a Transform's whole numbers as such. + ("adjust.curves", json!({"points": [[0, 255], [255, 0]]})), + ("distort.transform", json!({"copies": 2, "reference": 0.0})), ] { assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}"); } @@ -343,6 +346,10 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.outerGlow", json!({"color": {"model": "rgb", "r": 2.0, "g": 0.0, "b": 0.0}}), "color"), ("stylize.innerGlow", json!({"color": {"model": "gray", "k": -0.5}}), "color"), ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"), + ("adjust.curves", json!({"points": [[0, 255], [255]]}), "points"), + ("adjust.curves", json!({"points": ["0,0", "255,255"]}), "points"), + ("distort.transform", json!({"copies": 1.5}), "copies"), + ("distort.transform", json!({"reference": 4.5}), "reference"), ("adjust.levels", json!({"channel": "cyan"}), "channel"), ("blur.radial", json!({"centerX": 1.5}), "centerX"), ("blur.gaussian", json!({"linear": 1}), "linear"), diff --git a/docs/plugins.md b/docs/plugins.md index 8de1192c3c..0ac355d3c9 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -876,12 +876,13 @@ fill and stroke the piece returns, three more keys: - An effect record names a built-in effect that `effect.list` lists, other than a 3D effect or a Pathfinder effect (`pathfinder.*`, which has nothing to combine on a piece's one path), with parameters that effect takes, each of the type of its default, within the range `effect.list` gives for it, where it gives one, and one of the choices it - lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). The values `effect.apply` - checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a - Warp's `version`, a `color` (`"#rrggbb"`, `[r, g, b]` with each component from 0 to 1, or a color object with - components from 0 to 1 and a Lab lightness from 0 to 100), a Levels or Curves `channel` and a Radial Blur's center. A Drop Shadow's, Inner - Glow's or Outer Glow's `mode` must name a blend mode (`"multiply"`, `"color-burn"`). Omitted parameters take the - effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: + lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). Curves' `points` may also be + `[[x, y], …]`, each a pair of numbers, and a Transform's `copies` and `reference` are whole numbers. The values + `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and + `name`, a Warp's `version`, a `color` (`"#rrggbb"`, `[r, g, b]` with each component from 0 to 1, or a color object + with components from 0 to 1 and a Lab lightness from 0 to 100), a Levels or Curves `channel` and a Radial Blur's + center. A Drop Shadow's, Inner Glow's or Outer Glow's `mode` must name a blend mode (`"multiply"`, `"color-burn"`). + Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a piece carries never run a plug-in. From d327f6be5f5caff8bbe20187e36ce1aae8013fca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:49:13 -0800 Subject: [PATCH 024/106] Docs: state each color model's range for returned effect colors A color object's RGB, CMYK and Gray components are each from 0 to 1. A Lab color's `l` is from 0 to 100, and its `a` and `b` are any finite numbers, as the returned-effect check accepts them. --- docs/plugins.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plugins.md b/docs/plugins.md index 0ac355d3c9..ffc38b858d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -880,7 +880,8 @@ fill and stroke the piece returns, three more keys: `[[x, y], …]`, each a pair of numbers, and a Transform's `copies` and `reference` are whole numbers. The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a Warp's `version`, a `color` (`"#rrggbb"`, `[r, g, b]` with each component from 0 to 1, or a color object - with components from 0 to 1 and a Lab lightness from 0 to 100), a Levels or Curves `channel` and a Radial Blur's + whose RGB, CMYK or Gray components are each from 0 to 1, or whose Lab `l` is from 0 to 100 and `a` and `b` are any + finite numbers), a Levels or Curves `channel` and a Radial Blur's center. A Drop Shadow's, Inner Glow's or Outer Glow's `mode` must name a blend mode (`"multiply"`, `"color-burn"`). Omitted parameters take the effect's defaults. On a fill or stroke only raster effects are taken, and only from an effect in the object's stack: the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its From 14cde8fd1836235bba7304df43ca2e320f37df5b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:59:52 -0800 Subject: [PATCH 025/106] Plug-ins: returned Curves points are checked in both forms, 0 to 255 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Curves effect a painted live-effect plug-in returns is refused when its `points` string holds a token that is not an `x,y` pair of numbers, or when any point in the string or the `[[x, y], …]` array lies outside 0 to 255. Before, an unreadable string passed and the effect drew the default curve, and an out-of-range point was clamped. --- crates/effects/src/params.rs | 20 +++++++++++++++++--- crates/effects/src/tests/painted.rs | 5 +++++ docs/plugins.md | 4 ++-- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 9130d746ae..9cdc305522 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -187,7 +187,7 @@ pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> { /// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in /// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and -/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs; a Transform's whole +/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs from 0 to 255; a Transform's whole /// `copies` and `reference`; a Warp's `version`; a `color` the effect can draw; a /// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial /// Blur's center; and the type of each parameter without a default. @@ -218,8 +218,8 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) { return Err("`corners` must be four [x, y] pairs of numbers".into()); } - if id == "adjust.curves" && given.get("points").and_then(Value::as_array).is_some_and(|p| !p.iter().all(pair)) { - return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers".into()); + if id == "adjust.curves" && given.get("points").is_some_and(|p| !is_curve_points(p)) { + return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers from 0 to 255".into()); } if id == "distort.transform" && let Some(key) = ["copies", "reference"].into_iter().find(|k| given.get(*k).and_then(Value::as_f64).is_some_and(|x| x.fract() != 0.0)) @@ -261,6 +261,20 @@ fn check_returned_values(id: &str, given: &Map) -> Result<(), Str Ok(()) } +/// Can Curves read `v` as its `points`: `"x,y x,y …"` (pairs split by whitespace or `;`) or +/// `[[x, y], …]`, each number from 0 to 255? +fn is_curve_points(v: &Value) -> bool { + let level = |x: f64| (0.0..=255.0).contains(&x); + match v { + Value::String(s) => s + .split(|c: char| c.is_whitespace() || c == ';') + .filter(|p| !p.is_empty()) + .all(|p| p.split_once(',').is_some_and(|(x, y)| [x, y].into_iter().all(|n| n.trim().parse::().is_ok_and(level)))), + Value::Array(a) => a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|n| n.as_f64().is_some_and(level)))), + _ => false, + } +} + /// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]` /// with three numbers from 0 to 1 first, or a color object with its components from 0 to 1 (a Lab /// color's lightness from 0 to 100, and finite a and b)? diff --git a/crates/effects/src/tests/painted.rs b/crates/effects/src/tests/painted.rs index 5792f9f233..d1a9952354 100644 --- a/crates/effects/src/tests/painted.rs +++ b/crates/effects/src/tests/painted.rs @@ -302,6 +302,7 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})), // Curves' `points` is also taken as [[x, y], …], and a Transform's whole numbers as such. ("adjust.curves", json!({"points": [[0, 255], [255, 0]]})), + ("adjust.curves", json!({"points": "0,0; 64,32 255,255"})), ("distort.transform", json!({"copies": 2, "reference": 0.0})), ] { assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}"); @@ -348,6 +349,10 @@ fn returned_effects_are_built_in_effects_with_their_own_parameters() { ("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"), ("adjust.curves", json!({"points": [[0, 255], [255]]}), "points"), ("adjust.curves", json!({"points": ["0,0", "255,255"]}), "points"), + // Curves' points are read as "x,y" or [x, y] pairs, each number from 0 to 255. + ("adjust.curves", json!({"points": "not-points"}), "points"), + ("adjust.curves", json!({"points": "0,0 255,-1"}), "points"), + ("adjust.curves", json!({"points": [[0, 300], [255, 0]]}), "points"), ("distort.transform", json!({"copies": 1.5}), "copies"), ("distort.transform", json!({"reference": 4.5}), "reference"), ("adjust.levels", json!({"channel": "cyan"}), "channel"), diff --git a/docs/plugins.md b/docs/plugins.md index ffc38b858d..9ba350ce6a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -876,8 +876,8 @@ fill and stroke the piece returns, three more keys: - An effect record names a built-in effect that `effect.list` lists, other than a 3D effect or a Pathfinder effect (`pathfinder.*`, which has nothing to combine on a piece's one path), with parameters that effect takes, each of the type of its default, within the range `effect.list` gives for it, where it gives one, and one of the choices it - lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). Curves' `points` may also be - `[[x, y], …]`, each a pair of numbers, and a Transform's `copies` and `reference` are whole numbers. The values + lists for it, where it lists them (Roughen's `points` is `"smooth"` or `"corner"`). Curves' `points` is + `"x,y x,y …"` or `[[x, y], …]`, each number from 0 to 255, and a Transform's `copies` and `reference` are whole numbers. The values `effect.apply` checks for one effect are checked the same way: an SVG filter's `xml`, `scale`, `origin`, `axes` and `name`, a Warp's `version`, a `color` (`"#rrggbb"`, `[r, g, b]` with each component from 0 to 1, or a color object whose RGB, CMYK or Gray components are each from 0 to 1, or whose Lab `l` is from 0 to 100 and `a` and `b` are any From 43315db6b433b95b12802725f81b66a452fd25e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 09:49:22 -0800 Subject: [PATCH 026/106] Tabs: document tab titles draw in the condensed face through craft-ui's tab-title role Desktop builds call `Embed::tab_face()`, which embeds the Noto Sans Condensed SemiBold row of the checkout's `fonts/latin-manifest.txt` with the `tab` role. craft-ui draws semibold document tab titles in it, scaled to the semibold face's x-height. The document font list leaves that face out. Web builds and builds without the face draw tab titles in the semibold face. The craft-libs crates point at storytold/craft-libs#3545's head until it merges. --- Cargo.lock | 170 +++++++++++++++++--------------- Cargo.toml | 68 ++++++------- apps/vectorcraft-web/Cargo.toml | 2 +- crates/text/build.rs | 9 +- crates/text/src/craft_fonts.rs | 13 ++- docs/development.md | 5 + docs/ui-parity.md | 1 + 7 files changed, 150 insertions(+), 118 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c9393ef10..13a3db8a71 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1134,7 +1134,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-automation", "craft-behavior", @@ -1175,7 +1175,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "crc32fast", "flate2", @@ -1186,7 +1186,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "block2 0.6.2", "objc2-app-kit 0.3.2", @@ -1196,7 +1196,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "rustix 1.1.6", ] @@ -1204,7 +1204,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1229,7 +1229,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1247,7 +1247,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-docpath", @@ -1265,7 +1265,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "crc32fast", "flate2", @@ -1274,7 +1274,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "egui", ] @@ -1282,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "md-5", "rayon", @@ -1291,12 +1291,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-cms", @@ -1316,7 +1316,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "getrandom 0.3.4", "serde", @@ -1326,7 +1326,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "rayon", ] @@ -1334,7 +1334,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1359,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "serde", ] @@ -1367,7 +1367,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1386,7 +1386,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-codepage", "encoding_rs", @@ -1398,12 +1398,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1418,7 +1418,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1434,14 +1434,24 @@ dependencies = [ "skrifa 0.47.0", ] +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", @@ -1459,12 +1469,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "gif", ] @@ -1472,7 +1482,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "flate2", ] @@ -1480,7 +1490,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1493,7 +1503,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "chrono", "fixed_decimal", @@ -1521,7 +1531,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-dds", "craft-jpeg", @@ -1548,7 +1558,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1566,7 +1576,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "thiserror 2.0.21", ] @@ -1574,7 +1584,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1585,7 +1595,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-host", "craft-i18n", @@ -1600,7 +1610,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-i18n", @@ -1614,7 +1624,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -1632,7 +1642,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1644,7 +1654,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "encoding_rs", "image", @@ -1655,7 +1665,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "chrono", "craft-codepage", @@ -1665,7 +1675,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-keymap", @@ -1681,7 +1691,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1693,7 +1703,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "async-channel", "async-io", @@ -1724,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1733,7 +1743,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -1757,7 +1767,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1768,7 +1778,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-eps", "flate2", @@ -1782,7 +1792,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "encoding_rs", "flate2", @@ -1793,7 +1803,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "dispatch2", "egui", @@ -1806,7 +1816,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1825,7 +1835,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-atomic", "craft-host", @@ -1842,7 +1852,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "fax", "hayro-ccitt", @@ -1853,7 +1863,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-image-codecs", "craft-xml", @@ -1874,7 +1884,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-keymap", @@ -1886,7 +1896,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-font-manager", @@ -1911,7 +1921,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1926,7 +1936,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-atomic", "craft-behavior", @@ -1941,7 +1951,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "serde", "thiserror 2.0.21", @@ -1951,7 +1961,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "serde", "thiserror 2.0.21", @@ -1960,7 +1970,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-keymap", @@ -1975,12 +1985,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1994,7 +2004,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-i18n", @@ -2010,7 +2020,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "accesskit", "craft-behavior", @@ -2048,7 +2058,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2059,7 +2069,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -2077,7 +2087,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -2098,7 +2108,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -2119,7 +2129,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-behavior", "craft-host", @@ -2138,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "chrono", "craft-host", @@ -2167,7 +2177,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "flate2", "serde", @@ -2178,7 +2188,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2188,7 +2198,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "js-sys", "serde_json", @@ -2199,7 +2209,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "winsafe", ] @@ -2207,7 +2217,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "craft-appkit", "craft-atomic", @@ -2239,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3507,7 +3517,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "brotli", "hayro-postscript", @@ -3516,7 +3526,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3534,7 +3544,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3552,12 +3562,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "flate2", "hayro-ccitt", @@ -4488,7 +4498,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4645,7 +4655,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=6fcf61c816c399508a60c7029a59e2c7b6139e0b#6fcf61c816c399508a60c7029a59e2c7b6139e0b" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=423b0375042e5c313b25140b553d7a8227c502bf#423b0375042e5c313b25140b553d7a8227c502bf" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index e7eb351554..89df409f43 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,44 +11,44 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-cms = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-pdf = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-proof = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-vectorcraft-format = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-gzip = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-affinity = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-cdr = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-svg = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf", features = ["tree"] } +craft-mime = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-eps = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-plotter = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-dxf = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-metafile = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-xml = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-image-codecs = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-gif = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-tiff = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-ps = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-stream-codecs = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-jxl = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-codepage = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +craft-color-ui = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-theme = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +craft-fonts-build = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -191,13 +191,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" } +hayro-syntax = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +hayro-interpret = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +hayro-jbig2 = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +hayro-cmap = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +hayro-postscript = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +krilla = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } +linesweeper = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 8cca976717..a7d16e9924 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -27,7 +27,7 @@ log = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", version = "0.1.0" } +craft-web-api = { git = "https://github.com/dotCooCoo/craft-libs", rev = "423b0375042e5c313b25140b553d7a8227c502bf", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/text/build.rs b/crates/text/build.rs index 28669285e3..7863efe464 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -1,7 +1,9 @@ //! The optional craft-fonts build input (https://github.com/storytold/craft-fonts, //! `docs/integration.md`): with `CRAFT_FONTS_DIR=` set, every font in its //! `fonts/manifest.txt` is embedded as `CRAFT_FONTS` (the framework's `craft_fonts_build::Embed`); -//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts. +//! unset, `CRAFT_FONTS` is empty and the app uses its own and the installed fonts. Desktop builds +//! also embed the Noto Sans Condensed SemiBold row of the checkout's `fonts/latin-manifest.txt` +//! (`Embed::tab_face`), which document tab titles draw in; a checkout without it gives a warning. //! `CRAFT_FONTS_REQUIRED=1` turns a bad checkout into a build error (release builds). Nothing is //! fetched: the build reads only the local checkout. //! @@ -40,7 +42,10 @@ fn main() { None => embed, } }; - if let Err(e) = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1)).write("craft_fonts.rs") { + // Desktop builds also embed the checkout's condensed face for document tab titles. + let embedded = fonts().filter(move |f| !wasm || (f.family == WEB_FONT.0 && f.style == WEB_FONT.1)); + let embedded = if wasm { embedded } else { embedded.tab_face() }; + if let Err(e) = embedded.write("craft_fonts.rs") { println!("cargo::error={e}"); } let mut web = String::new(); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 7e64490b3f..28b2dc2662 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -72,6 +72,7 @@ fn japanese_document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> { /// first: the fallback for Arabic text; the other families are picked by name), then the Thai ones /// (Noto Sans Thai: the fallback for Thai text where no Thai font is installed, and on the web), /// then the Georgian ones (Noto Sans Georgian, the same for Georgian). Remaining faces follow in manifest order, so every explicitly supplied family can be selected. +/// The tab-title face (role `tab`), which only document tab titles draw in, is left out. /// Empty when built without craft-fonts. pub fn document_fonts() -> Vec<&'static EmbeddedFace> { document_fonts_from(CRAFT_FONTS) @@ -79,7 +80,9 @@ pub fn document_fonts() -> Vec<&'static EmbeddedFace> { fn document_fonts_from(fonts: &[EmbeddedFace]) -> Vec<&EmbeddedFace> { let mut v = japanese_document_fonts_from(fonts); - let rest = |f: &&EmbeddedFace, earlier: &[&str]| !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s)); + let rest = |f: &&EmbeddedFace, earlier: &[&str]| { + f.role != Some(craft_fonts_build::TAB_ROLE) && !f.has_script("Jpan") && !earlier.iter().any(|s| f.has_script(s)) + }; v.extend(fonts.iter().filter(|f| f.has_script("Arab") && rest(f, &[]))); v.extend(fonts.iter().filter(|f| f.has_script("Thai") && rest(f, &["Arab"]))); v.extend(fonts.iter().filter(|f| f.has_script("Geor") && rest(f, &["Arab", "Thai"]))); @@ -131,6 +134,14 @@ mod tests { assert!(document_fonts_from(&[]).is_empty()); } + #[test] + fn document_fonts_leave_out_the_tab_title_face() { + let latin = EmbeddedFace { family: "Latin", style: "Regular", scripts: &["Latn"], index: 0, bytes: &[], role: None }; + let tab = EmbeddedFace { family: "Noto Sans", style: "Condensed SemiBold", role: Some(craft_fonts_build::TAB_ROLE), ..latin }; + let listed: Vec<_> = document_fonts_from(&[latin, tab]).into_iter().map(|f| f.family).collect(); + assert_eq!(listed, ["Latin"]); + } + #[test] fn web_fonts_follow_the_list() { if CRAFT_FONTS.is_empty() { diff --git a/docs/development.md b/docs/development.md index 404dc10f33..5a1b6efd95 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,6 +178,11 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- `startup` and `demand` faces of `crates/text/web-fonts.txt` are served under `fonts/ui/` instead: the stack fetches the UI language's at once and the others the first time text needs them. +- Document tab titles: desktop builds also embed the Noto Sans Condensed SemiBold row of the + checkout's opt-in `fonts/latin-manifest.txt` (`Embed::tab_face` in `crates/text/build.rs`). + The interface font stack draws document tab titles in it, scaled to the x-height of the + semibold face; the document font list leaves it out. Without `CRAFT_FONTS_DIR`, on the web, or + with a checkout that lacks the row (a build warning), tab titles draw in the semibold face. - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c74a8a8d7b..60dff719af 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,6 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; craft-ui's `TypeRole::TabTitle` and `craft_fonts_build::Embed::tab_face`; `craft_fonts::tests::document_fonts_leave_out_the_tab_title_face`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From 032206d8fe61c0a55cc7282174ad5ae5f6474322 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:08:44 -0800 Subject: [PATCH 027/106] Plug-ins: a left-out piece opacity is 100%, and the PDF test reads back the look docs/plugins.md said a piece's opacity, when left out, is the object's. The piece takes no opacity of its own in that case: the object's opacity applies once to all the pieces together, so the line now says 100%. The export test also opens the exported PDF and draws it: the piece is half green and grown by Offset Path, as on the canvas, so a PDF that drops the opacity or writes the original path fails the test. --- crates/engine/src/tests/plugins.rs | 9 +++++++++ docs/plugins.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a2868201ce..8afe824501 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -597,6 +597,15 @@ fn a_painted_piece_s_look_is_exported_and_expanded() { let pdf = s.execute("document.export", &json!({"format": "pdf"})).unwrap(); let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap(); assert!(pdf.windows(9).any(|w| w == b"/Multiply"), "the PDF sets the blending mode"); + let back = vectorcraft_pdf::import(&pdf).unwrap(); + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let read = vectorcraft_render::Renderer::new().render(&back, 200, 200, vectorcraft_geom::Affine::IDENTITY, &opts); + let (got_inside, got_grown) = (read.pixel(50, 50), read.pixel(37, 50)); + assert!( + near(got_inside, [128, 255, 128]) && near(got_grown, [128, 255, 128]), + "the PDF's piece is half green and grown: {got_inside:?} {got_grown:?}" + ); + assert_eq!(read.pixel(32, 50), WHITE); assert_eq!(s.doc().unwrap().doc, before, "export doesn't change the document"); run(&mut s, "select.set", json!({"ids": [id.0]})); run(&mut s, "effect.expandAppearance", json!({})); diff --git a/docs/plugins.md b/docs/plugins.md index 4659eee54e..334cf8254c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1042,7 +1042,7 @@ fill and stroke the piece returns, three more keys: the fills or strokes that an effect on a fill or a stroke returns take `opacity` and `blend` but no `effects` (its pieces still take them). A plug-in effect (`plugin.`), this effect's own included, is refused, so the effects a piece carries never run a plug-in. -- Left out, a piece's opacity is the object's, its blending mode Normal and its effects none; a fill or stroke keeps +- Left out, a piece's opacity is 100%, its blending mode Normal and its effects none; a fill or stroke keeps the opacity, blending and effects it would have without the keys. Given, a piece's opacity multiplies the object's, and its effects and a fill's or stroke's come after the ones it already has. The object's own opacity, blending mode and later effects still apply once to all the pieces together. From cbbb98149e0fd1801e5cc42ff6e7eccf018ed753 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:19:41 -0800 Subject: [PATCH 028/106] Toolbars: a toolbar's command buttons are looked up together The footer of a toolbar made with New Toolbar looked up each command button's label on its own, which rebuilt the tool homes once per button on every render. `palette::button_texts` looks up all of a toolbar's buttons from one kept build, and `command_looks` uses it. docs/mcp.md now says which errors apply to `toolbar.addCommand` and which to both commands, and that `toolbar.removeCommand` answers with the unchanged list for a command the toolbar has no button for. --- crates/ui-egui/src/custom_toolbars.rs | 9 ++------- crates/ui-egui/src/edit_toolbar/tests.rs | 19 +++++++++++++++++++ crates/ui-egui/src/palette.rs | 12 ++++++++++++ docs/mcp.md | 8 +++++--- 4 files changed, 38 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index b2f60c88d4..ff7c19fc3e 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -616,13 +616,8 @@ impl CommandLook { /// How each command button of the toolbar with id `id` looks now. fn command_looks(app: &mut VectorcraftApp, ui: &egui::Ui, id: u32) -> Vec { let commands = app.ui.custom_toolbars.iter().find(|b| b.id == id).map(|b| b.commands.clone()).unwrap_or_default(); - commands - .into_iter() - .map(|id| { - let text = crate::palette::is_command(&id).then(|| crate::palette::button_text(app, ui, &id)).flatten(); - CommandLook { id, text } - }) - .collect() + let texts = crate::palette::button_texts(app, ui, &commands); + commands.into_iter().zip(texts).map(|(id, text)| CommandLook { id, text }).collect() } /// A command button on the toolbar named `bar`: the command's label, cut short with … when it is diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index e3e8eb5dca..82bf402a18 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -607,6 +607,25 @@ fn a_missing_command_stays_dimmed_until_it_is_removed() { assert_eq!(left, json!(["object.group"])); } +/// The footer looks up all its command buttons in one call: each id gets what a lookup of it alone +/// gives, in order, and none for a tool, a command that needs params or a command that is gone. +#[test] +fn command_buttons_are_looked_up_together() { + let mut app = app(); + let ctx = ctx(); + let ids: Vec = + ["object.group", "tool:pen", "plugin:x", "toolbar.addTool", "object.path.cleanUp"].into_iter().map(str::to_string).collect(); + let together = in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &ids)); + let alone: Vec<_> = ids + .iter() + .map(|id| crate::palette::is_command(id).then(|| in_pass(&mut app, &ctx, |app, ui| crate::palette::button_text(app, ui, id))).flatten()) + .collect(); + assert_eq!(together, alone); + assert!(together[0].is_some() && together[4].is_some(), "Group and Clean Up are found: {together:?}"); + assert!(together[1..4].iter().all(Option::is_none), "a tool, a missing command and one that needs params: {together:?}"); + assert!(in_pass(&mut app, &ctx, |app, ui| crate::palette::button_texts(app, ui, &[])).is_empty()); +} + /// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one /// off, and its Add Command submenu searches the Command Palette's results other than tools: a click /// on a match adds its button at the end of the toolbar. diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index e1dfc3d5ac..0860a3e10c 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -608,12 +608,24 @@ pub(crate) struct ButtonText { /// The label, name and command of the palette result `id` in the interface language, from the /// entries built once per catalog generation; none when the palette lists no result with that id /// now (an uninstalled plug-in's command). +#[cfg(test)] pub(crate) fn button_text(app: &mut VectorcraftApp, ui: &egui::Ui, id: &str) -> Option { let built = kept_build(app, ui); let e = built.by_id.get(id).and_then(|&i| built.entries.get(i))?; Some(button_text_of(e)) } +/// The [`ButtonText`] of each result id in `ids`, in order, from one kept build: none for an id +/// that [`is_command`] does not allow or that the palette lists no longer (an uninstalled plug-in's +/// command). A toolbar's footer draws all its command buttons from one call. +pub(crate) fn button_texts(app: &mut VectorcraftApp, ui: &egui::Ui, ids: &[String]) -> Vec> { + if ids.is_empty() { + return Vec::new(); + } + let built = kept_build(app, ui); + ids.iter().map(|id| if is_command(id) { built.by_id.get(id).and_then(|&i| built.entries.get(i)).map(button_text_of) } else { None }).collect() +} + /// [`ButtonText`] of the entry `e`. fn button_text_of(e: &HelpEntry) -> ButtonText { let label = e.label().as_str().trim_end(); diff --git a/docs/mcp.md b/docs/mcp.md index d788800b32..aece27dedb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3798,9 +3798,11 @@ A toolbar made with New Toolbar holds command buttons after its tools. `toolbar. named `toolbar`, or moves the button when the toolbar has it already: at place `at` among its command buttons, 0 for the first, or at the end without `at`. `command` is a Command Palette result's id: a command's id, or `plugin:`, `effect:` or `panel:`. `toolbar.removeCommand {command, toolbar}` takes a button off. Both -answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. An unknown -command, a tool, a command that needs params a click does not give (`toolbar.addTool`), an `at` past the end or a -missing `toolbar` is an error and changes nothing. A click on a button runs what the command's menu item runs, so a +answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. A missing +`toolbar` is an error for both and changes nothing. For `toolbar.addCommand`, an unknown command, a tool, a command +that needs params a click does not give (`toolbar.addTool`) or an `at` past the end is also an error and changes +nothing. `toolbar.removeCommand` with a command the toolbar has no button for, a tool's id included, is not an error: +it answers with the toolbar's command buttons unchanged. A click on a button runs what the command's menu item runs, so a command whose item ends in … opens its dialog, and the button is dimmed while that item is. A command that is no longer installed, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it is installed again or removed. `toolbar.reset {toolbar}` takes the buttons off with the tools. The buttons are kept with From 9d34e458c102bc2e1dd6e2843ba6618672f41e81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:36:28 -0800 Subject: [PATCH 029/106] Preferences: OK writes only the settings changed in the dialog OK sent every row of the draft through prefs.set and wrote Smart Guides, Snap to Grid and Enable Contextual Task Bar back from the values copied when the dialog opened. A setting changed by a command, a panel menu or a script while Preferences was open went back to its old value, and a workspace switched to while it was open took the Contextual Task Bar of the workspace the dialog opened in. - The window keeps each row as it last read it (at open, after an import or a prefs.reset refreshes it, and after OK or Apply) and the rows set in it since then. OK and Apply write only the rows set in the window or whose value differs from the one read, so a reset in the window is still written. A row changed both ways takes the window's value. - Enable Contextual Task Bar left alone in the dialog is not written, so each workspace keeps its own bar. - OK with nothing changed runs no prefs.set, adds no undo step and does not ask the host to save the settings; original_editor::commit reports whether the Edit Original choice changed. Docs: docs/mcp.md (Preferences) and a line in docs/target-app-parity.md. --- crates/ui-egui/src/original_editor.rs | 7 +- crates/ui-egui/src/prefs_dialog.rs | 62 +++++++++++++--- crates/ui-egui/src/prefs_dialog/model.rs | 44 +++++++----- crates/ui-egui/src/prefs_dialog/tests.rs | 90 ++++++++++++++++++++++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 6 files changed, 182 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/original_editor.rs b/crates/ui-egui/src/original_editor.rs index f9b8f00543..da3bf5d5ed 100644 --- a/crates/ui-egui/src/original_editor.rs +++ b/crates/ui-egui/src/original_editor.rs @@ -14,7 +14,7 @@ use crate::VectorcraftApp; /// Opaque saved choice. Public so hosts can construct `UiState` with a struct update; its path /// has no public setter and is never read from the generic preference or dialog-field maps. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Choice { path: Option, } @@ -45,8 +45,11 @@ pub(crate) fn open(app: &mut VectorcraftApp) { app.original_editor.choice = app.ui.original_editor.clone(); } -pub(crate) fn commit(app: &mut VectorcraftApp) { +/// Saves the dialog's choice; returns whether it differs from the saved one. +pub(crate) fn commit(app: &mut VectorcraftApp) -> bool { + let changed = app.ui.original_editor != app.original_editor.choice; app.ui.original_editor = app.original_editor.choice.clone(); + changed } pub(crate) fn reset(app: &mut VectorcraftApp) { diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index cc1a102f26..c6cbd37e50 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -1,6 +1,6 @@ //! Edit → Preferences (⌘K): the framework's Preferences window over the engine's preference table //! ([`PREF_SPECS`]). The window edits a draft ([`PrefsWindow::draft`]; one key per preference, so agents can -//! `ui.dialog.set` any of them) and OK applies it through `prefs.set`. Also: persistence of engine prefs inside +//! `ui.dialog.set` any of them) and OK applies the rows changed in it through `prefs.set`. Also: persistence of engine prefs inside //! `UiState` and the per-frame application of the UI-side preferences ([`runtime`]). // PLAN: assumed import paths of the framework items below through the `craft_ui` facade (it re-exports the dialog @@ -44,9 +44,17 @@ pub struct PrefsWindow { draft: SettingsDraft, /// The draft as it was when the window opened or last applied: Apply is enabled while the draft differs. opened: SettingsDraft, + /// Each row's value as the window last read it from the preferences, the document or the UI state. OK and Apply + /// write only the rows whose draft value differs from it ([`Self::edited`]), so a setting changed outside the + /// window while it is open keeps its new value. + source: SettingsDraft, /// The Units ▸ General value Reset Preferences put in the draft, while it is still the row's value: OK then /// leaves the open document's units alone. reset_units: Option, + /// The rows set in the window (by the user, `ui.dialog.set` or a reset) since it last read them. OK writes them + /// even when they hold the value they were read with: a reset of a row a command changed while the window is + /// open, or of Units ▸ General, which shows the document's units, is still written. + touched: std::collections::BTreeSet, /// The colour picker and the Reset question, drawn in the window's own viewport. nested: DialogHost, reset_asked: Option, @@ -70,11 +78,39 @@ impl PrefsWindow { if key == "unitsGeneral" && self.reset_units.as_ref().is_some_and(|u| value.as_str() != Some(u)) { self.reset_units = None; } - self.draft.set(key, value); + self.set_row(key, value); self.sync_strings(); Ok(()) } + /// Whether the row `key` was changed in the window since it was last read: it was set there + /// ([`Self::touched`]), or its draft value differs from [`Self::source`]. Numbers compare by value, so `4` and + /// `4.0` are the same. + fn edited(&self, key: &str) -> bool { + if self.touched.contains(key) { + return true; + } + let (now, read) = (self.draft.get::(key), self.source.get::(key)); + match (now.as_ref().and_then(Value::as_f64), read.as_ref().and_then(Value::as_f64)) { + (Some(a), Some(b)) => a != b, + _ => now != read, + } + } + + /// Writes `value` at `key` in the draft and in [`Self::source`]: the row shows a value read from outside the + /// window, and OK does not write it back. + fn read(&mut self, key: &str, value: &Value) { + self.draft.set(key, value); + self.source.set(key, value); + self.touched.remove(key); + } + + /// Sets the row `key` in the window, as the user or a reset does. + fn set_row(&mut self, key: &str, value: &Value) { + self.draft.set(key, value); + self.touched.insert(key.to_string()); + } + /// Reads the draft's text and choice values again, after any write to the draft. fn sync_strings(&mut self) { use vectorcraft_engine::cmd::prefscmds::{PREF_SPECS, PrefKind}; @@ -90,7 +126,7 @@ impl PrefsWindow { fn refresh(&mut self, prefs: &Value) { for (k, v) in prefs.as_object().into_iter().flatten() { if self.draft.get::(k).is_some() { - self.draft.set(k, v); + self.read(k, v); } } self.reset_units = self.draft.get::("unitsGeneral"); @@ -102,7 +138,7 @@ impl PrefsWindow { let defaults = Prefs::default().to_json(); for key in keys { if let Some(v) = defaults.get(key) { - self.draft.set(key, v); + self.set_row(key, v); } } if self.draft.get::("unitsGeneral").is_some() { @@ -117,7 +153,9 @@ fn is_known(key: &str) -> bool { UI_FIELDS.iter().any(|f| f.0 == key) || spec(key).is_some() || PREF_GROUPS.contains(&key) } -/// Opens the window on `category` (matched ignoring case; General when it names none). +/// Opens the window on `category` (matched ignoring case; General when it names none). OK writes only the rows +/// changed in the window: a setting changed some other way while it is open (a command, a panel menu, a script) +/// keeps its new value. pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { crate::original_editor::open(app); let mut draft = SettingsDraft::default(); @@ -126,7 +164,8 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { fields.retain(|k, _| is_known(k)); // A restored settings file can hold a Hold Shortcut Delay outside its range: the window shows, // and OK sets, the delay in use. - if fields.contains_key("keyHoldDelay") { + let saved_delay = fields.get("keyHoldDelay").cloned(); + if saved_delay.is_some() { fields.insert("keyHoldDelay".into(), json!(app.session.prefs.key_hold_delay())); } // Units ▸ General shows (and OK sets) the open document's units. @@ -140,11 +179,18 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) { draft.set("__snapToGrid", &app.ui.view.snap_to_grid); draft.set("__taskBar", &app.ui.task_bar); let selected = category.and_then(|c| PREF_CATEGORIES.iter().find(|x| x.eq_ignore_ascii_case(c))).copied().unwrap_or(PREF_CATEGORIES[0]); + // The saved delay, so OK writes the delay in use in its place. + let mut source = draft.clone(); + if let Some(saved) = &saved_delay { + source.set("keyHoldDelay", saved); + } let mut w = PrefsWindow { state: PreferencesState::default(), opened: draft.clone(), + source, draft, reset_units: None, + touched: Default::default(), nested: DialogHost::new(), reset_asked: None, strings: Default::default(), @@ -362,7 +408,7 @@ fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindo } // The window shows the reset row, so OK keeps it. if let Some(w) = w.as_deref_mut() { - w.draft.set(key, &value); + w.read(key, &json!(value)); } } // And the reset preferences, the groups with a reset of every category; Units ▸ General then leaves the open @@ -373,7 +419,7 @@ fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindo for (k, v) in prefs.as_object().into_iter().flatten() { let reset = spec(k).map_or(every && PREF_GROUPS.contains(&k.as_str()), |s| in_reset(s.category)); if reset && w.draft.get::(k).is_some() { - w.draft.set(k, v); + w.read(k, v); if k == "unitsGeneral" { w.reset_units = v.as_str().map(str::to_string); } diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 0d03652289..b1e9bed4e9 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -283,7 +283,7 @@ impl Live<'_> { fn reset_ui_rows(&mut self, reset: impl Fn(&str) -> bool) { for (key, value) in super::default_ui_fields(&self.app.ui) { if UI_FIELDS.iter().any(|&(k, c, _)| k == key && reset(c)) { - self.w.draft.set(key, &value); + self.w.set_row(key, &json!(value)); } } } @@ -424,34 +424,44 @@ impl PreferencesDraft for Live<'_> { fn apply(&mut self) -> Result<(), String> { // A `prefs.reset` run since the last frame shows in the draft before OK reads it. super::apply_prefs_resets_to(self.app, Some(&mut *self.w)); - let values: Map = - self.w.draft.to::>().unwrap_or_default().into_iter().filter(|(k, _)| !k.starts_with("__")).collect(); + // Only the rows changed in the window: a setting changed outside it while it is open keeps its new value. + let edited: Map = + self.w.draft.to::>().unwrap_or_default().into_iter().filter(|(k, _)| self.w.edited(k)).collect(); + let values: Map = edited.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u)); // A refused folder, typed or picked, comes back here as the engine's message. - self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; + if !values.is_empty() { + self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?; + } + let row = |key: &str| edited.get(key).and_then(Value::as_bool); // When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being // left; otherwise after it, so a return from Touch gives it to the workspace returned to. let before_switch = touch_ws.is_some() && crate::workspaces::enters_touch(self.app, self.app.touch_screen); - if before_switch && let Some(on) = self.w.draft.get::("__taskBar") { + if before_switch && let Some(on) = row("__taskBar") { self.app.ui.task_bar = on; } if touch_ws.is_some() { crate::workspaces::sync_touch_workspace(self.app, self.app.touch_screen); } - let flag = |key: &str, now: bool| self.w.draft.get::(key).unwrap_or(now); - let (smart_guides, snap_to_grid, task_bar) = ( - flag("__smartGuides", self.app.ui.view.smart_guides), - flag("__snapToGrid", self.app.ui.view.snap_to_grid), - if before_switch { self.app.ui.task_bar } else { flag("__taskBar", self.app.ui.task_bar) }, - ); - self.app.ui.view.smart_guides = smart_guides; - self.app.ui.view.snap_to_grid = snap_to_grid; - self.app.ui.task_bar = task_bar; - crate::original_editor::commit(self.app); - super::snapshot(self.app); - self.app.prefs_changed = true; + if let Some(on) = row("__smartGuides") { + self.app.ui.view.smart_guides = on; + } + if let Some(on) = row("__snapToGrid") { + self.app.ui.view.snap_to_grid = on; + } + if !before_switch && let Some(on) = row("__taskBar") { + self.app.ui.task_bar = on; + } + let editor = crate::original_editor::commit(self.app); + // The host saves the settings only when one changed. + if !edited.is_empty() || editor { + super::snapshot(self.app); + self.app.prefs_changed = true; + } self.w.opened = self.w.draft.clone(); + self.w.source = self.w.draft.clone(); + self.w.touched.clear(); Ok(()) } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 1b09df5cb0..bf1e2d093e 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -296,6 +296,18 @@ fn reset_preferences_keeps_an_edit_of_general_units() { reset_preferences(&mut b, PromptChoice::Proceed); confirm(&mut b).unwrap(); assert_eq!(b.session.prefs.units_general, Prefs::default().units_general); + + // A document in the default unit, with another unit saved: the row opens showing the default, and the reset + // still resets the saved unit. + let mut c = app(); + c.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + c.run("prefs.set", json!({"values": {"unitsGeneral": "inches"}, "documentUnits": false})).unwrap(); + assert_eq!(c.session.active().unwrap().doc.units.key(), Prefs::default().units_general); + open(&mut c, Some("General")); + reset_preferences(&mut c, PromptChoice::Proceed); + confirm(&mut c).unwrap(); + assert_eq!(c.session.prefs.units_general, Prefs::default().units_general, "the saved unit is reset"); + assert_eq!(c.session.active().unwrap().doc.units.key(), Prefs::default().units_general, "the document's units stay"); } /// Smart Guides, Snap to Grid and Enable Contextual Task Bar, the UI-only rows. @@ -538,6 +550,84 @@ fn prefs_reset_outside_run_resets_the_ui_only_rows_in_the_next_frame() { assert!(!left_task_bar(&b, "Essentials Classic"), "the workspace left keeps the reset value"); } +/// OK writes only the rows changed in Preferences: a preference, a UI-only row or the document's units changed by a +/// command while the window is open keeps its new value, and a row changed in the window is still written. +#[test] +fn ok_keeps_settings_changed_by_commands_while_preferences_is_open() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let before = ui_rows(&a); + open(&mut a, Some("General")); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 9})).unwrap(); + a.run("document.setUnits", json!({"units": "Millimeters"})).unwrap(); + for id in ["view.smartGuides", "view.snapToGrid", "window.taskBar"] { + a.run(id, json!({})).unwrap(); + } + set_field(&mut a, "constrainAngle", json!(30.0)).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, 9.0, "the command's preference"); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Millimeters, "the command's units"); + assert_eq!(ui_rows(&a), (!before.0, !before.1, !before.2), "the commands' UI-only rows"); + assert_eq!(a.session.prefs.constrain_angle, 30.0, "the row changed in the window"); + assert_eq!(a.ui.engine_prefs["keyboardIncrement"], json!(9.0), "saved with the UI state"); + + // A row changed both ways takes the window's value; Cancel writes nothing. + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(3)).unwrap(); + set_field(&mut a, "constrainAngle", json!(15.0)).unwrap(); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 5})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, 3.0, "the window's value"); + open(&mut a, Some("General")); + set_field(&mut a, "constrainAngle", json!(45.0)).unwrap(); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 6})).unwrap(); + cancel(&mut a); + assert_eq!((a.session.prefs.keyboard_increment, a.session.prefs.constrain_angle), (6.0, 15.0), "Cancel writes nothing"); + + // A reset in the window is written even where the row already showed the default: a command changed the + // preference after the window opened. + let default = Prefs::default().keyboard_increment; + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": default})).unwrap(); + open(&mut a, Some("General")); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 8})).unwrap(); + reset_preferences(&mut a, PromptChoice::Proceed); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, default, "the reset is written"); +} + +/// OK with nothing changed in Preferences writes nothing: no preference, no undo step in the document and no save +/// of the settings. +#[test] +fn ok_with_nothing_changed_writes_nothing() { + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let undo = a.session.active().unwrap().history.undo.len(); + let prefs = a.session.prefs.clone(); + a.take_prefs_changed(); + open(&mut a, Some("Units")); + confirm(&mut a).unwrap(); + assert!(!is_open(&a)); + assert_eq!(a.session.prefs, prefs); + assert_eq!(a.session.active().unwrap().history.undo.len(), undo, "no undo step"); + assert!(!a.take_prefs_changed(), "the settings are not saved again"); +} + +/// Enable Contextual Task Bar left alone in Preferences stays with each workspace: a workspace switch while the +/// window is open keeps the bar of the workspace switched to, and the workspace left keeps its own. +#[test] +fn ok_after_a_workspace_switch_keeps_each_workspaces_task_bar() { + let off = crate::workspaces::builtins().into_iter().find(|w| !w.record.task_bar).expect("a workspace saved with the bar off"); + let mut a = app(); + crate::workspaces::switch(&mut a, crate::workspaces::ESSENTIALS).unwrap(); + assert!(a.ui.task_bar, "Essentials starts with the bar on"); + open(&mut a, Some("General")); + a.run("window.workspace", json!({"name": off.name})).unwrap(); + set_field(&mut a, "keyboardIncrement", json!(3)).unwrap(); + confirm(&mut a).unwrap(); + assert!(!a.ui.task_bar, "{} keeps its bar off", off.name); + assert!(left_task_bar(&a, crate::workspaces::ESSENTIALS), "Essentials keeps its bar on"); +} + #[test] fn old_pref_files_keep_their_brightness() { let mut a = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 61663febe2..558c6d648a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9054,7 +9054,11 @@ highlighted until another category is shown) and clears `__search`. Cmd/Ctrl+F f field with text clears it, and Escape in the empty field closes the dialog. Its Reset Preferences button opens a `resetPreferences` question (fields `message`, `detail`) over Preferences: `ui.dialog.cancel` shows Preferences again as it was, and `ui.dialog.confirm` shows it again with every preference at its default value, applied by OK in -Preferences. `prefs.reset` resets the preferences at once, without the question. +Preferences. `prefs.reset` resets the preferences at once, without the question. OK in Preferences writes only the +fields changed in the dialog since it opened or since its last Apply, so a preference, Smart Guides, Snap to Grid, +Enable Contextual Task Bar or the document's units changed some other way while it is open (a command, a panel menu, +a script) keeps its new value. A field changed both ways takes the dialog's value. OK with no field changed writes +nothing and adds no undo step. ```json {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 09c2f07001..48cf0aef8d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -895,6 +895,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences resets every setting the dialog shows:** Smart Guides and Snap to Grid also return to their defaults (on and off) when Reset Preferences is confirmed, and General's Enable Contextual Task Bar takes the value the current workspace was saved with. OK in Preferences applies them with the other defaults, and Cancel keeps the values in use. A category's own reset resets the row of that category, and File Handling's also resets the app chosen for Edit Original. `prefs.reset` (the Command Palette's Reset Preferences) resets them too, each only when it resets every category or the setting's own, and with every category or File Handling it also clears the app chosen for Edit Original. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`, `crates/ui-egui/src/original_editor.rs`. +- **Preferences OK keeps changes made outside the dialog:** OK writes only the settings changed in the dialog, so a preference, Smart Guides, Snap to Grid, Enable Contextual Task Bar or the document's units changed by a command or a script while Preferences is open keeps its new value, and a workspace switched to while it is open keeps its own Contextual Task Bar. OK with nothing changed writes nothing. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. From 812b6a2a9253c1a4d834f81a67b8fc8614758b43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:01:06 -0800 Subject: [PATCH 030/106] Toolbars: command buttons skip the tool re-homing, and the protocol doc splits the remove rule - `palette::button_texts` reads the kept palette build as it is and no longer recomputes every tool's home on each footer pass; it builds only when no build exists for the current catalog. - `docs/control-protocol.md` states the errors of `toolbar.addCommand` apart from `toolbar.removeCommand`, which answers with the unchanged list for a command the toolbar has no button for. - The edit toolbar tests run their lookups in a frame from `crate::testing::part_frame`. --- crates/ui-egui/src/edit_toolbar/tests.rs | 7 +++---- crates/ui-egui/src/palette.rs | 16 +++++++++++++++- docs/control-protocol.md | 9 ++++++--- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 82bf402a18..ea2228296f 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -479,17 +479,16 @@ fn mine_commands(app: &VectorcraftApp) -> Vec { crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone() } -/// `f` run with `app` and a `Ui` of a pass of `ctx`. +/// `f` run with `app` and a `Ui` of one frame of `ctx` as the hosts run it ([`crate::testing::part_frame`]). fn in_pass(app: &mut VectorcraftApp, ctx: &egui::Context, f: impl FnOnce(&mut VectorcraftApp, &egui::Ui) -> T) -> T { let mut f = Some(f); let mut got = None; - let mut out = ctx.run_ui(RawInput::default(), |ui| { + let _ = crate::testing::part_frame(app, ctx, RawInput::default(), |app, ui| { if let Some(f) = f.take() { got = Some(f(app, ui)); } }); - out.textures_delta.clear(); - got.expect("the pass ran") + got.expect("the frame ran") } /// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them, diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 0860a3e10c..df7c1892b1 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -622,7 +622,7 @@ pub(crate) fn button_texts(app: &mut VectorcraftApp, ui: &egui::Ui, ids: &[Strin if ids.is_empty() { return Vec::new(); } - let built = kept_build(app, ui); + let built = kept_commands(app, ui); ids.iter().map(|id| if is_command(id) { built.by_id.get(id).and_then(|&i| built.entries.get(i)).map(button_text_of) } else { None }).collect() } @@ -685,6 +685,20 @@ pub(crate) fn is_command(id: &str) -> bool { ids.contains(id) } +/// The kept build for the current [`BuildKey`] as it is, without re-homing its tool entries, for +/// looking up results other than tools, whose entries a toolbar's change leaves as they are: a +/// toolbar's footer looks its command buttons up on every pass. Without a build for the key, it is +/// [`kept_build`]. +fn kept_commands(app: &mut VectorcraftApp, ui: &egui::Ui) -> Arc { + let key = BuildKey { catalog: app.menus.catalog_generation(), native: app.services.native_menu.is_some() }; + if let Some((kept, built)) = &app.canvas.palette + && *kept == key + { + return built.clone(); + } + kept_build(app, ui) +} + /// The built entries for the current [`BuildKey`]: built again when the key moves (the index is /// as costly as production's, so not per pass or per open), with the tool entries re-homed in /// place when a toolbar changes. A home is shown and never searched, so the index stays. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e6d03ed345..5fd024c129 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -486,9 +486,12 @@ there. The same menu's Add Command submenu searches the Command Palette's result in the button's context menu), and `toolbar.removeCommand {command, toolbar}` takes one off (Remove Command in the menu, Remove from Toolbar in the context menu). `command` is a palette result's id: a command's id, or `plugin:`, `effect:` or `panel:`. A click on the button runs what the command's menu item runs, and the -button is dimmed while that item is. An unknown command, a tool, a command that needs params a click does not give -(`toolbar.addTool`), a place past the end or a missing `toolbar` is an error and changes nothing. A command that is -no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still takes it off. +button is dimmed while that item is. A missing `toolbar` is an error for both and changes nothing. For +`toolbar.addCommand`, an unknown command, a tool, a command that needs params a click does not give +(`toolbar.addTool`) or a place past the end is also an error and changes nothing. `toolbar.removeCommand` with a +command the toolbar has no button for, a tool's id included, is not an error: it answers with the toolbar's command +buttons unchanged. A command that is no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still +takes it off. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, commands, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). From d07ca8514cec3512133d5998b7702b8ac99ae71c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:24:38 -0800 Subject: [PATCH 031/106] Preferences: Apply is enabled for a reset of a row a command changed A reset in Preferences can leave a row showing the value the window opened with after a command changed the setting. OK wrote that row, but Apply stayed disabled because it compared the draft only with the values at open. Apply is now enabled while any row has been set in the window. --- crates/ui-egui/src/prefs_dialog/model.rs | 4 +++- crates/ui-egui/src/prefs_dialog/tests.rs | 27 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index 32408bf5c8..ef8197ba08 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -417,8 +417,10 @@ impl PreferencesModel for Live<'_> { } impl PreferencesDraft for Live<'_> { + /// A row set in the window counts even when it shows the value it opened with: a reset of a row a command changed + /// while the window is open is still applied. fn differs(&self) -> bool { - self.w.draft != self.w.opened + self.w.draft != self.w.opened || !self.w.touched.is_empty() } fn apply(&mut self) -> Result<(), String> { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index ed34d2c53c..948baf7f2d 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -641,6 +641,33 @@ fn ok_keeps_settings_changed_by_commands_while_preferences_is_open() { assert_eq!(a.session.prefs.keyboard_increment, default, "the reset is written"); } +/// A reset in Preferences that leaves a row showing the value it opened with, after a command changed the setting, +/// still enables Apply, and Apply writes it. +#[test] +fn apply_writes_a_reset_of_a_row_a_command_changed() { + use craft::ui::patterns::preferences::PreferencesDraft as _; + let live = |a: &mut VectorcraftApp, apply: bool| { + let mut w = a.prefs.take().expect("Preferences is open"); + let mut m = model::Live { app: &mut *a, w: &mut w }; + let differs = m.differs(); + if apply { + m.apply().unwrap(); + } + a.prefs = Some(w); + differs + }; + let mut a = app(); + let on = a.ui.view.smart_guides; + open(&mut a, Some("General")); + assert!(!live(&mut a, false), "nothing to apply at open"); + a.run("view.smartGuides", json!({})).unwrap(); + reset_preferences(&mut a, PromptChoice::Proceed); + assert_eq!(field(&a, "__smartGuides"), json!(on), "the row shows the value it opened with"); + assert!(live(&mut a, true), "Apply is enabled"); + assert_eq!(a.ui.view.smart_guides, on, "Apply writes the reset"); + assert!(!live(&mut a, false), "nothing left to apply"); +} + /// OK with nothing changed in Preferences writes nothing: no preference, no undo step in the document and no save /// of the settings. #[test] From 27c3f8cb290d115da93d6a20b59f5baa66ff93ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:44:53 -0800 Subject: [PATCH 032/106] Scripts: variables follow the topmost-first page item order and the gate's linked-file argument --- crates/engine/src/script/dom/variables.rs | 2 +- crates/engine/src/tests/script_variables.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs index d36c9f1f45..6c405f6051 100644 --- a/crates/engine/src/script/dom/variables.rs +++ b/crates/engine/src/script/dom/variables.rs @@ -352,7 +352,7 @@ fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Re if path.chars().count() > super::super::files::MAX_PATH_CHARS { return Err(HostError::Range(format!("{what}: the path is too long"))); } - let gate = h.disk.borrow().gate(Vec::new()); + let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default()); gate.check(path, access).map_err(HostError::Error)?; Ok(path.to_string()) } diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs index 5ff2301bbf..8f032a2bb8 100644 --- a/crates/engine/src/tests/script_variables.rs +++ b/crates/engine/src/tests/script_variables.rs @@ -27,12 +27,12 @@ fn undo_steps(s: &Session) -> usize { s.active().unwrap().history.undo.len() } -/// A document with a type object and a rectangle. +/// A document with a rectangle and, above it, a type object, so `pageItems[0]` is the type and `pageItems[1]` the rectangle. fn doc() -> (Session, NodeId, NodeId) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); (s, t, r) } From 13d1aa9a773dea5e694a8d9cf7636793dcb91198 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:46:22 -0800 Subject: [PATCH 033/106] Packaging Tools: store individual fold angles --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/addons.rs | 2 +- crates/engine/src/cmd/addons/packaging.rs | 8 +- .../engine/src/cmd/addons/packaging/angle.rs | 266 ++++++++++++ .../src/cmd/addons/packaging/angle/tests.rs | 409 ++++++++++++++++++ .../engine/src/cmd/addons/packaging/check.rs | 6 +- .../engine/src/cmd/addons/packaging/fold.rs | 2 +- .../engine/src/cmd/addons/packaging/roles.rs | 73 +++- .../engine/src/cmd/addons/packaging/tests.rs | 16 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/turn_direction.rs | 1 + crates/three-d/src/fold.rs | 52 ++- crates/three-d/src/fold/tests.rs | 147 ++++++- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + docs/mcp.md | 17 + docs/target-app-parity.md | 2 + 43 files changed, 1094 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/angle.rs create mode 100644 crates/engine/src/cmd/addons/packaging/angle/tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 74a10d337f..2153c7d879 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -845,7 +845,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. -pub use addons::{fold_source, print_hidden}; +pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; /// Document Info's category titles, the Objects category's count labels, and how its image rows /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -17,7 +17,7 @@ mod typetools; mod units; pub(crate) use image::{DecodedImages, refresh_color_masks}; -pub use packaging::{fold_source, print_hidden}; +pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -2,13 +2,16 @@ //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each //! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold -//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu -//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set +//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins › +//! Packaging Tools) and its Fold Lines panel are the UI's. +mod angle; mod check; mod fold; mod roles; +pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines}; pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -17,6 +20,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..f38645774f --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -0,0 +1,266 @@ +//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease, +//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of +//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a +//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side. + +use std::collections::HashSet; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::kept_angle; + +use super::super::super::edit::refuse_symbol_part; +use super::super::super::overprint::edit_counted; +use super::super::super::pathops::number_given; +use super::super::super::{CommandSpec, bad, cmd, switch_or}; +use super::check::kind; +use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots}; +use crate::{Result, Session}; + +/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export +/// leaves `vc-` keys out. +pub(crate) const KEY: &str = "vc-fold-angle"; + +const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The range a fold angle may take, in degrees. +const RANGE: std::ops::RangeInclusive = -180.0..=180.0; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.setFoldAngle", + "Set Fold Angle…", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}", + has_fold_line, + set_fold_angle + )] +} + +/// Why Set Fold Angle has nothing to change. +const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + +/// The last answer of [`has_fold_line`], with what it was for. +struct Answer { + /// The document (a weak reference keeps another document from taking the same address). + doc: Weak, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + found: bool, +} + +thread_local! { + /// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the + /// document, its revision and the objects looked at. + static LAST_ANSWER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object. +fn has_fold_line(s: &Session) -> std::result::Result<(), String> { + refuse_symbol_part(s).map_err(|e| e.to_string())?; + let st = s.doc().map_err(|e| e.to_string())?; + let objects = &st.selection.objects; + let kept = LAST_ANSWER.with_borrow(|last| match last { + Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found), + _ => None, + }); + let found = kept.unwrap_or_else(|| { + // An id of no object (given as `ids`) is left to the command, which names it. + let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects); + LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found })); + found + }); + if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) } +} + +/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through +/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`] +/// takes them, an object inside another one given is left out (a crease in a selected layer counts +/// no more than the layer does), a layer is left out, and a path of a compound path stands for the +/// compound path, which holds its role, unless it is locked or hidden. +fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool { + fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool { + match &n.kind { + // A group's clipping path draws no stroke. + NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)), + _ => hit(n), + } + } + let table = RoleTable::of(d); + let editable = d.editable(); + let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id); + let given: HashSet = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + let a = d.ancestry(id)?; + let (_, up) = a.split_last()?; + if up.iter().any(|p| given.contains(p)) { + return None; + } + match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) { + // A locked or hidden path of a compound path is left out, as `editable_members` leaves it. + Some(_) if !editable(id) => None, + Some(compound) => Some(compound), + None => Some(id), + } + }; + // An object given twice is looked through once. + let mut seen = HashSet::new(); + roots + .iter() + .filter_map(|id| outer(*id)) + .filter(|id| seen.insert(*id)) + .filter_map(|id| d.node(id)) + .filter(|n| !n.is_layer()) + .any(|n| find(n, &hit)) +} + +/// The text `n`'s data holds under [`KEY`], if any. +fn stored(n: &Node) -> Option<&str> { + n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str()) +} + +/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from +/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as +/// no angle of its own. +pub(super) fn own_angle(n: &Node) -> Option { + stored(n)?.trim().parse::().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle) +} + +/// Whether a line with `role` folds: every role but Cut. +pub(super) fn folds(role: Role) -> bool { + kind(role).fold_angle().is_some() +} + +/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed. +fn store(d: &mut Document, id: NodeId, angle: Option) -> bool { + // `+ 0.0` turns -0 into 0, so a line set to 0° reads "0". + let text = angle.map(|a| format!("{}", a + 0.0)); + // Read first: taking the node to change it copies it, its geometry included. An angle stored + // as other text for the same number ("45.0") is kept; a reset removes any stored text. + let same = |n: &Node| match angle { + Some(a) => own_angle(n) == Some(a), + None => stored(n).is_none(), + }; + if d.node(id).is_none_or(same) { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.edit_attrs(|a| match text { + Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) { + Some(e) => e.1 = text, + None => a.data.push((KEY.into(), text)), + }, + None => a.data.retain(|(k, _)| k != KEY), + }); + true +} + +fn set_fold_angle(s: &mut Session, p: &Value) -> Result { + let angle = number_given(p, "angle", SET_FOLD_ANGLE)?; + let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?; + let angle = match (angle, reset) { + (Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")), + (None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")), + (Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")), + // Kept to the millionth of a degree, the angle the line folds at. + (a, _) => a.map(kept_angle), + }; + let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?; + let d = &s.doc()?.doc; + let (targets, skipped) = role_targets(d, &roots, false); + let mut skipped = skipped + named; + let mut ids = folding(d, &RoleTable::of(d), &targets); + { + let editable = d.editable(); + ids.retain(|id| editable(*id)); + } + skipped += targets.len() - ids.len(); + if ids.is_empty() { + return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE)); + } + let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" }; + let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed, "skipped": skipped })) +} + +/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order. +fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect() +} + +/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip +/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FoldAngles { + /// How many lines that fold it can change. + pub lines: usize, + /// The angle they all fold at (their own or their role's); `None` when they differ or there + /// are none. + pub angle: Option, + /// How many of them have an angle of their own. + pub own: usize, + /// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away. + pub stored: usize, +} + +/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them +/// with no `ids` (nothing, while it would refuse the selection). +pub fn selection_fold_angles(s: &Session) -> FoldAngles { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots), + _ => FoldAngles::default(), + } +} + +/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes +/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the +/// lines it changes. +pub fn selection_fold_lines(s: &Session) -> Vec { + match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) { + (Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(), + _ => Vec::new(), + } +} + +/// The [`FoldAngles`] of the outermost objects `roots` of `d`. +pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles { + let mut f = FoldAngles::default(); + for (n, role) in changeable(d, roots) { + f.add(n, role); + } + f +} + +/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change, +/// with their roles, in order. +fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> { + let table = RoleTable::of(d); + let editable = d.editable(); + let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0; + // The role first: whether an object can be edited can take its bounds to find out. + targets + .iter() + .filter_map(|id| d.node(*id)) + .filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r))) + .collect() +} + +impl FoldAngles { + /// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out. + pub(super) fn add(&mut self, n: &Node, role: Role) { + let Some(default) = kind(role).fold_angle() else { return }; + let own = own_angle(n); + let a = own.unwrap_or(default); + self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) }; + self.lines += 1; + self.own += usize::from(own.is_some()); + self.stored += usize::from(stored(n).is_some()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -0,0 +1,409 @@ +//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it. + +use serde_json::{Value, json}; + +use super::{KEY, fold_angles, own_angle}; +use crate::*; + +const SET: &str = "addon.packaging.setFoldAngle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(SET, &p).unwrap_err().to_string() +} + +/// The text object `id`'s data holds under the fold angle key. +fn stored(s: &Session, id: u64) -> Option { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone())) +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases: top, right, bottom, left). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of +/// its outline's points (absolute moves and lines only) is above the base. +fn top_wall(p: &Value) -> bool { + let d = p["outline"].as_str().unwrap(); + let n: Vec = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + (ys.0 + ys.1) / 2.0 < 140.0 +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +#[test] +fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + assert_eq!(steps(&s), before + 1, "one undo step"); + // The same angle again changes nothing and records no undo step. + let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(0)); + assert_eq!(steps(&s), before + 1); + // An angle is kept to the millionth of a degree, so one closer to 45 than that is 45. + let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}"); + s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap(); + assert_eq!(stored(&s, creases[3]).as_deref(), Some("180")); + s.execute("edit.undo", &json!({})).unwrap(); + // A number as text, and the selection when ids is left out; -0 is kept as 0. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + let r = s.execute(SET, &json!({"angle": "-0"})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "{r}"); + assert_eq!(stored(&s, creases[1]).as_deref(), Some("0")); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}"); + assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None)); + // Nothing left to reset: no undo step. + let at = steps(&s); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at)); + // Undo brings the angle back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); +} + +#[test] +fn bad_angles_and_targets_are_refused() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let plain = path(&mut s, "M10 10 L50 50"); + let before = steps(&s); + let ids = json!([creases[0]]); + assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`")); + assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both")); + assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180")); + assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number")); + assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false")); + // A cut line and a path without a role do not fold. + assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation")); + // An id of no object is named as such, alone or beside a crease. + assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999")); + assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999")); + assert_eq!(steps(&s), before, "no refusal records an undo step"); + // The ends of the range are allowed; cut lines and plain paths among fold lines are skipped. + let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}"); + s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("180")); + assert_eq!(stored(&s, outline), None); +} + +#[test] +fn set_fold_angle_is_dimmed_without_a_line_it_can_change() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok(); + assert!(!enabled(&s), "nothing selected"); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!(!enabled(&s), "a cut line does not fold"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap(); + assert!(enabled(&s)); + s.execute("object.lock", &json!({})).unwrap(); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed"); + // A group holding a crease is enough. + s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + assert!(enabled(&s)); + // A layer selected with a crease in it: the crease is inside the layer, which is left out, as + // Set Fold Angle itself leaves them out. + let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap(); + s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert!(!enabled(&s), "dimmed as the command refuses it"); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); + // With nothing selected the counts are the document's, but Set Fold Angle takes no line. + s.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(s.execute(SET, &json!({"angle": 30})).is_err()); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!(r["scope"].as_str(), Some("document"), "{r}"); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}"); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}"); +} + +#[test] +fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [outline]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold"); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + assert_eq!(r["changed"].as_u64(), Some(1), "{r}"); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line"); +} + +#[test] +fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap(); + let f = crate::cmd::selection_fold_angles(&s); + assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}"); +} + +#[test] +fn a_locked_crease_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(stored(&s, creases[1]), None); +} + +#[test] +fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320")); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + role(&mut s, "crease", &[compound]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(NodeId(a)) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation")); + // Named twice, it is skipped once. + let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}"); + assert_eq!(stored(&s, compound), None); + assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed"); + assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation")); + assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0); + let r = s.execute("addon.packaging.roles", &json!({})).unwrap(); + assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}"); + assert_eq!(stored(&s, compound), None); + // With its compound, given or selected, the locked path is part of the compound, not skipped. + let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute("select.set", &json!({"ids": [compound, a]})).unwrap(); + let r = s.execute(SET, &json!({"angle": 25})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}"); + s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap(); + // The compound named by id takes the angle; its other path, not locked, names it too. + let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap(); + assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}"); + assert_eq!(stored(&s, compound).as_deref(), Some("30")); +} + +#[test] +fn a_damaged_angle_reads_as_none_of_its_own() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap(); + for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] { + n.edit_attrs(|a| { + a.data.retain(|(k, _)| k != KEY); + a.data.push((KEY.into(), text.into())); + }); + assert_eq!(own_angle(&n), want, "{text:?}"); + } +} + +#[test] +fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() { + let mut s = session(); + let (_, creases) = tray(&mut s); + let id = NodeId(creases[0]); + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into()))); + } + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}"); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0")); + s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!(stored(&s, creases[0]), None); + // A reset also removes text that is not an angle. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(id) { + n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into()))); + } + Ok(()) + }) + .unwrap(); + let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap(); + assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}"); +} + +#[test] +fn a_line_keeps_its_own_angle_through_a_role_change() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + role(&mut s, "partialCut", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); + role(&mut s, "none", &[creases[0]]); + assert_eq!(stored(&s, creases[0]).as_deref(), Some("45")); + role(&mut s, "crease", &[creases[0]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}"); +} + +#[test] +fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap(); + let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap(); + let svg = svg["text"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned()); + assert!(svg.contains(" = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + assert!(angles.contains(&120.0), "{r}"); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // The top wall (y 100 to 140) folds at 45°. + s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut angles: Vec = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect(); + angles.sort_by(f64::total_cmp); + assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]); + for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) { + let z = vector(&p["frame"]["z"]); + let top = top_wall(p); + let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}"); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.fold", &json!({})).unwrap(); + let base = r["base"].as_u64().unwrap() as usize; + let mut up = 0; + for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) { + // The top wall folds toward the print, so its printed side faces back over the base + // (toward -y in the y-up frame); the other walls stand square to the base as before. + let top = top_wall(p); + let z = vector(&p["frame"]["z"]); + if top { + assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}"); + up += 1; + } else { + assert!(z[2].abs() < 1e-9, "{p}"); + } + } + assert_eq!(up, 1); +} + +#[test] +fn roles_reports_the_angle_the_selected_fold_lines_share() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}"); + s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}"); + let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap(); + assert!(r["foldAngle"].is_null(), "{r}"); + // A partial cut folds at -90° unless it has an angle of its own. + role(&mut s, "partialCut", &[creases[2]]); + let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap(); + assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}"); +} + +#[test] +fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() { + let mut s = session(); + let (_, creases) = tray(&mut s); + s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap(); + s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0].0; + s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap(); + assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}"); + assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}"); + // So Reset has nothing to change, as the panel shows it. + let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}"); + let (lines, angle, own) = { + let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]); + (f.lines, f.angle, f.own) + }; + assert_eq!((lines, angle, own), (1, Some(90.0), 0)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::angle::own_angle; use super::roles::{Role, RoleTable, can_carry, role_targets}; use crate::{Result, Session}; @@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) } -fn kind(role: Role) -> LineKind { +/// The kind of fold line a line with `role` is. +pub(super) fn kind(role: Role) -> LineKind { match role { Role::Cut => LineKind::Cut, Role::Crease => LineKind::Crease, @@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec) -> Lines { non_printing.push(id.0); } segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); - lines.push(FoldLine { path, kind: kind(role), key: id.0 }); + lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) }); } Lines { scope, lines, non_printing } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..65d9356da3 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fold", [], None, - "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. A hinge takes the angle of the line with the most length in it, with the lowest id winning a tie: its stored angle (addon.packaging.setFoldAngle), or its role's angle when none is stored. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", has_doc, fold_command )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use super::super::super::edit::{outermost, refuse_symbol_part, roots_of}; use super::super::super::overprint::edit_counted; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param}; use crate::{Result, Session}; @@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool { } } +/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of +/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that +/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out +/// before it stands for its compound, and how many such paths were left out, each once. +pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec, usize)> { + if p.get("ids").is_some_and(|v| !v.is_null()) { + let roots = checked_ids_or_selection(s, p, command)?; + return Ok(editable_members(&s.doc()?.doc, roots)); + } + refuse_symbol_part(s)?; + let st = s.doc()?; + // An object inside another selected one is left out first, as it is from `ids`. + let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc))); + Ok((roots_of(&st.doc, kept), left)) +} + +/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or +/// hidden group or layer, or on a locked artboard), and how many different ones were left out. +pub(super) fn editable_members(d: &Document, ids: Vec) -> (Vec, usize) { + let ok = d.editable(); + let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + let mut left = std::collections::HashSet::new(); + let kept = ids + .into_iter() + .filter(|id| { + let out = member(*id) && !ok(*id); + if out { + left.insert(*id); + } + !out + }) + .collect(); + (kept, left.len()) +} + /// The objects under the outermost objects `roots` that can carry a role, through groups and clip /// groups, each once, and /// how many of `roots` and their members can't (text, images, symbol instances and other objects). @@ -257,7 +293,7 @@ pub fn specs() -> Vec { "Make Fold Line", ["Object", "Plug-ins", "Packaging Tools"], None, - "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", + "{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}", has_selection, set_role ), @@ -266,7 +302,7 @@ pub fn specs() -> Vec { "Fold Lines", [], None, - "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out", + "{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes", has_doc, roles ), @@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai fn set_role(s: &mut Session, p: &Value) -> Result { let role = role_param(p, SET_ROLE, true)?; let overprint = switch_or(p, "overprint", true, SET_ROLE)?; - let roots = checked_ids_or_selection(s, p, SET_ROLE)?; + let (roots, left) = taken_roots(s, p, SET_ROLE)?; let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true); + let skipped = skipped + left; if ids.is_empty() { return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role")); } @@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result { fn roles(s: &mut Session, p: &Value) -> Result { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, ROLES)?; - let d = &s.doc()?.doc; + // The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand + // for its compound there. They are the objects the counts are of unless such a path was left + // out, and only then are those found apart. + let (taken, left) = taken_roots(s, p, ROLES)?; + let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) }; + let st = s.doc()?; + let d = &st.doc; let (scope, ids) = match (given, roots.is_empty()) { (true, _) => ("ids", role_targets(d, &roots, false).0), (false, false) => ("selection", role_targets(d, &roots, false).0), (false, true) => ("document", document_targets(d)), }; + let whole = scope == "document"; + // The lines Set Fold Angle can change are those of the objects it takes: with nothing selected, + // or a selection that holds no such object (only a layer and what is in it), it takes none, + // though the counts are the document's. + let angles_of_all = given || !roots.is_empty(); let table = RoleTable::of(d); let mut counts = [0usize; 4]; - for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) { + let editable = d.editable(); + let mut angles = super::angle::FoldAngles::default(); + for n in ids.iter().filter_map(|id| d.node(*id)) { + let Some(r) = table.role_of(n) else { continue }; if let Some(c) = counts.get_mut(r.index()) { *c += 1; } + if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) { + angles.add(n, r); + } + } + if !whole && left > 0 { + angles = super::angle::fold_angles(d, &angle_roots); } let rows: Vec = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count }) }) .collect(); - Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() })) + Ok(json!({ + "roles": rows, "scope": scope, "selected": roots.len(), + "foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored, + })) } fn set_role_swatch(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() { let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]})); assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1))); assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // A locked member named by id is skipped, and its compound keeps its role. + s.edit("Test", |d, _| { + if let Some(n) = d.node_mut(a) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden")); + // The same with the locked path selected. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden")); + assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]); + // Named twice, it is skipped once. + let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]})); + assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}"); } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 9a715abf11..5e75fcf438 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..b9905b82b8 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -1297,9 +1316,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1365,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..c43ab8c38e 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,142 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cbc03abcfc..7cc7edc299 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -8601,6 +8601,10 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Set Fold Angle… Задай ъгъл на сгъване… + Set Fold Angle Задай ъгъл на сгъване + Reset Fold Angle Нулирай ъгъла на сгъване +@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита Check Провери Check Fold Lines Провери линиите на сгъване @msg No cut lines are in the selection. В селекцията няма линии за рязане. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 4548a6576a..1ffc754fd6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7985,6 +7985,10 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Set Fold Angle… Postavi ugao savijanja… + Set Fold Angle Postavi ugao savijanja + Reset Fold Angle Poništi ugao savijanja +@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena Check Provjeri Check Fold Lines Provjeri linije savijanja @msg No cut lines are in the selection. U odabiru nema linija rezanja. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e17017d95b..13f6d88662 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -9049,6 +9049,10 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Set Fold Angle… Defineix l’angle de plegat… + Set Fold Angle Defineix l’angle de plegat + Reset Fold Angle Restableix l’angle de plegat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada Check Comprova Check Fold Lines Comprova les línies de plegat @msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2433a0b12e..021010561e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -10832,6 +10832,10 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Set Fold Angle… Nastavit úhel skladu… + Set Fold Angle Nastavit úhel skladu + Reset Fold Angle Obnovit úhel skladu +@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Místo popisku zobrazí kartu s tím, co dělá nástroj z panelu a co dělají jeho klávesy; vyžaduje Zobrazovat popisky nástrojů. Selects whole objects and groups to move, resize or rotate them. Vybírá celé objekty a skupiny, abyste je mohli přesunout, změnit jejich velikost nebo je otočit. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4fbda43ec7..333d89e0b5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10920,6 +10920,10 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Set Fold Angle… Angiv foldevinkel… + Set Fold Angle Angiv foldevinkel + Reset Fold Angle Nulstil foldevinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult Check Kontrollér Check Fold Lines Kontrollér foldelinjer @msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7d788abf48..d359e67e27 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -10474,6 +10474,10 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Set Fold Angle… Faltwinkel festlegen… + Set Fold Angle Faltwinkel festlegen + Reset Fold Angle Faltwinkel zurücksetzen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zeigt statt des Tooltips eine Karte, was ein Werkzeug der Werkzeugleiste und seine Tasten tun; erfordert Tooltips anzeigen. Selects whole objects and groups to move, resize or rotate them. Wählt ganze Objekte und Gruppen aus, um sie zu verschieben, zu skalieren oder zu drehen. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2e7c180df4..d1fe508cff 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -9022,6 +9022,10 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Set Fold Angle… Ορισμός γωνίας δίπλωσης… + Set Fold Angle Ορισμός γωνίας δίπλωσης + Reset Fold Angle Επαναφορά γωνίας δίπλωσης +@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή Check Έλεγχος Check Fold Lines Έλεγχος γραμμών δίπλωσης @msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 37eea18b4c..3934609ffa 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -10766,6 +10766,10 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Set Fold Angle… Definir ángulo de plegado… + Set Fold Angle Definir ángulo de plegado + Reset Fold Angle Restablecer ángulo de plegado +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta Check Comprobar Check Fold Lines Comprobar líneas de plegado @msg No cut lines are in the selection. No hay líneas de corte en la selección. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c95d681244..3eff88d491 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -9105,6 +9105,10 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Set Fold Angle… Aseta taittokulma… + Set Fold Angle Aseta taittokulma + Reset Fold Angle Palauta taittokulma +@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu Check Tarkista Check Fold Lines Tarkista taittoviivat @msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index efab0b71ea..d7e93c0320 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -10827,6 +10827,10 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Set Fold Angle… Définir l’angle de pliage… + Set Fold Angle Définir l’angle de pliage + Reset Fold Angle Réinitialiser l’angle de pliage +@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée Tap Appui bref Clear Hold Effacer le maintien Hold Shortcuts Raccourcis de maintien diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index fb9295675a..57f7129027 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5666,6 +5666,10 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો… + Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો + Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો +@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય Check ચેક કરો Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો @msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 082e4c8e03..1d4d9852fd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10450,6 +10450,10 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Set Fold Angle… फ़ोल्ड कोण सेट करें… + Set Fold Angle फ़ोल्ड कोण सेट करें + Reset Fold Angle फ़ोल्ड कोण रीसेट करें +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. टूलबार का टूल और उसकी कुंजियाँ क्या करती हैं, यह टिप की जगह एक कार्ड में दिखाता है; इसके लिए टूल युक्तियाँ दिखाएँ चालू होना चाहिए। Selects whole objects and groups to move, resize or rotate them. पूरे ऑब्जेक्ट और समूह चुनता है, ताकि उन्हें खिसकाया, आकार बदला या घुमाया जा सके। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 669e5723c9..ce4429b3d6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -10820,6 +10820,10 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Set Fold Angle… Hajtásszög beállítása… + Set Fold Angle Hajtásszög beállítása + Reset Fold Angle Hajtásszög visszaállítása +@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Az elemleírás helyett kártyán mutatja, mit csinál az eszköztár egy eszköze és a billentyűi; ehhez az Elemleírások megjelenítése szükséges. Selects whole objects and groups to move, resize or rotate them. Teljes objektumokat és csoportokat jelöl ki áthelyezéshez, átméretezéshez vagy forgatáshoz. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 725ef12327..a7fd0253e1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8701,6 +8701,10 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Set Fold Angle… Atur sudut lipat… + Set Fold Angle Atur sudut lipat + Reset Fold Angle Atur ulang sudut lipat +@msg select a crease, partial cut or perforation line that is neither locked nor hidden pilih garis lekuk, garis potong sebagian, atau garis perforasi yang tidak terkunci dan tidak tersembunyi Check Periksa Check Fold Lines Periksa garis lipat @msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d00eb9be50..8962b3e65a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -10508,6 +10508,10 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Set Fold Angle… Imposta angolo di piega… + Set Fold Angle Imposta angolo di piega + Reset Fold Angle Reimposta angolo di piega +@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleziona una linea di cordonatura, di taglio parziale o di perforazione che non sia bloccata né nascosta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra una scheda con ciò che fanno uno strumento della barra e i suoi tasti al posto della descrizione; richiede Mostra descrizioni comandi. Selects whole objects and groups to move, resize or rotate them. Seleziona oggetti e gruppi interi per spostarli, ridimensionarli o ruotarli. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 8dba701981..73e38a5405 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10570,6 +10570,10 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Set Fold Angle… 折り角度を設定… + Set Fold Angle 折り角度を設定 + Reset Fold Angle 折り角度をリセット +@msg select a crease, partial cut or perforation line that is neither locked nor hidden ロックも非表示もされていない筋入れ線、半抜き線またはミシン目線を選択してください # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. ツールバーのツールとそのキーの働きを、ヒントの代わりにカードで表示。ツールヒントを表示がオンのときに使用 Selects whole objects and groups to move, resize or rotate them. オブジェクトやグループ全体を選択して、移動、サイズ変更、回転を行います。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0a29222b28..1282649ace 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -11149,6 +11149,10 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მარკირებისთვის. Remove Fold Line Role ხაზის ტიპის მოხსნა + Set Fold Angle… მოკეცვის კუთხის დაყენება… + Set Fold Angle მოკეცვის კუთხის დაყენება + Reset Fold Angle მოკეცვის კუთხის ჩამოყრა +@msg select a crease, partial cut or perforation line that is neither locked nor hidden მონიშნეთ ბიგის, ნაწილობრივი ჭრის ან პერფორაციის ხაზი, რომელიც არც ჩაკეტილია და არც დამალული Check შემოწმება Check Fold Lines მოკეცვის ხაზების შემოწმება @msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 78dc8d7b97..c20b39b13f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -10471,6 +10471,10 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Set Fold Angle… 접는 각도 설정… + Set Fold Angle 접는 각도 설정 + Reset Fold Angle 접는 각도 재설정 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 잠기거나 숨겨지지 않은 오시선, 하프 컷 선 또는 미싱선을 선택하세요 # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. 도구 막대의 도구와 그 키가 하는 일을 도움말 대신 카드로 표시합니다. 도구 설명 표시가 켜져 있어야 합니다. Selects whole objects and groups to move, resize or rotate them. 개체와 그룹 전체를 선택하여 이동하거나 크기를 조정하거나 회전합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index bbe1681764..31683d653f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10870,6 +10870,10 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Set Fold Angle… Vouwhoek instellen… + Set Fold Angle Vouwhoek instellen + Reset Fold Angle Vouwhoek herstellen +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecteer een rillijn, halve snijlijn of perforatielijn die niet vergrendeld of verborgen is # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Toont in plaats van de tooltip een kaart met wat een gereedschap in de werkbalk en zijn toetsen doen; vereist Tooltips tonen. Selects whole objects and groups to move, resize or rotate them. Selecteert hele objecten en groepen om ze te verplaatsen, te schalen of te draaien. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index be22f98247..f677e3edfa 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -10697,6 +10697,10 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Set Fold Angle… Ustaw kąt zgięcia… + Set Fold Angle Ustaw kąt zgięcia + Reset Fold Angle Resetuj kąt zgięcia +@msg select a crease, partial cut or perforation line that is neither locked nor hidden zaznacz linię bigowania, nacięcia lub perforacji, która nie jest zablokowana ani ukryta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Zamiast podpowiedzi pokazuje kartę z tym, co robią narzędzie z paska i jego klawisze; wymaga opcji Pokaż podpowiedzi. Selects whole objects and groups to move, resize or rotate them. Zaznacza całe obiekty i grupy, aby je przesuwać, skalować lub obracać. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2be19bf7e..215bfa2b92 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -10904,6 +10904,10 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Set Fold Angle… Definir Ângulo de Dobra… + Set Fold Angle Definir Ângulo de Dobra + Reset Fold Angle Redefinir Ângulo de Dobra +@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecione uma linha de vinco, de meio-corte ou de perfuração que não esteja bloqueada nem oculta # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Mostra um cartão com o que uma ferramenta da barra e suas teclas fazem, no lugar da dica; requer Mostrar Dicas de Ferramenta. Selects whole objects and groups to move, resize or rotate them. Seleciona objetos e grupos inteiros para movê-los, redimensioná-los ou girá-los. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e722b4e782..8198d65093 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10918,6 +10918,10 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Set Fold Angle… Задать угол сгиба… + Set Fold Angle Задать угол сгиба + Reset Fold Angle Сбросить угол сгиба +@msg select a crease, partial cut or perforation line that is neither locked nor hidden выделите линию биговки, надреза или перфорации, которая не закреплена и не скрыта Check Проверить Check Fold Lines Проверить линии сгиба @msg No cut lines are in the selection. В выделении нет линий реза. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2c9b16b092..aa1a286be7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10957,6 +10957,10 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Set Fold Angle… Ange falsvinkel… + Set Fold Angle Ange falsvinkel + Reset Fold Angle Återställ falsvinkel +@msg select a crease, partial cut or perforation line that is neither locked nor hidden markera en biglinje, halvskärlinje eller perforeringslinje som varken är låst eller dold Check Kontrollera Check Fold Lines Kontrollera falslinjer @msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 81accf43c5..77d707da54 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10789,6 +10789,10 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Set Fold Angle… Katlama Açısını Ayarla… + Set Fold Angle Katlama Açısını Ayarla + Reset Fold Angle Katlama Açısını Sıfırla +@msg select a crease, partial cut or perforation line that is neither locked nor hidden kilitli ya da gizli olmayan bir pilyaj, yarım kesim veya perforaj çizgisi seçin # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Araç çubuğundaki bir aracın ve tuşlarının ne yaptığını ipucu yerine bir kartta gösterir; Araç İpuçlarını Göster gerekir. Selects whole objects and groups to move, resize or rotate them. Taşımak, yeniden boyutlandırmak veya döndürmek için nesnelerin ve grupların tamamını seçer. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e1700dbb94..0b2eb9990f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -10484,6 +10484,10 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Set Fold Angle… Задати кут згину… + Set Fold Angle Задати кут згину + Reset Fold Angle Скинути кут згину +@msg select a crease, partial cut or perforation line that is neither locked nor hidden виділіть лінію біговки, надрізу або перфорації, яка не закріплена й не прихована # Tool cards (General › Show Tool Cards): one sentence on what each tool does. Shows a card with what a toolbar tool does and what its keys do instead of its tip; it needs Show Tool Tips. Замість підказки показує картку з тим, що роблять інструмент панелі та його клавіші; потрібно Показувати підказки. Selects whole objects and groups to move, resize or rotate them. Виділяє об’єкти й групи цілком, щоб переміщувати, масштабувати або обертати їх. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 278a8c10e9..e1b55f5b7e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8604,6 +8604,10 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Set Fold Angle… Đặt góc gấp… + Set Fold Angle Đặt góc gấp + Reset Fold Angle Đặt lại góc gấp +@msg select a crease, partial cut or perforation line that is neither locked nor hidden hãy chọn một đường cấn, đường cắt một phần hoặc đường đục lỗ không bị khóa và không bị ẩn Check Kiểm tra Check Fold Lines Kiểm tra đường gấp @msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ae265a4fc7..eb33e45b40 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -10707,6 +10707,10 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Set Fold Angle… 设置折叠角度… + Set Fold Angle 设置折叠角度 + Reset Fold Angle 重置折叠角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 请选择未锁定且未隐藏的压痕线、半切线或打孔线 Check 检查 Check Fold Lines 检查折线 @msg No cut lines are in the selection. 所选内容中没有切割线。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7d83822f05..3935da5e74 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -10523,6 +10523,10 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Set Fold Angle… 設定摺疊角度… + Set Fold Angle 設定摺疊角度 + Reset Fold Angle 重設摺疊角度 +@msg select a crease, partial cut or perforation line that is neither locked nor hidden 請選取未鎖定且未隱藏的壓痕線、半切線或打孔線 Check 檢查 Check Fold Lines 檢查摺線 @msg No cut lines are in the selection. 選取範圍中沒有切割線。 diff --git a/docs/mcp.md b/docs/mcp.md index 437569a1f9..0d26efb1c5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16331,6 +16331,23 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold angles + +`addon.packaging.setFoldAngle` gives Crease, Partial Cut, and Perforation lines an angle from -180 to 180 degrees. +Pass `angle`, or pass `reset: true` to remove their stored angles. The command accepts `ids` or uses the selection, +looks through groups and clip groups, and skips locked or hidden objects, Cut lines, and objects without a role. +It reports `{ids, changed, skipped}` and records one undo step when a value changes. Angles are rounded to the +millionth of a degree. A positive angle folds away from the printed side; a negative angle folds toward it. + +The line stores its angle under `vc-fold-angle` and keeps it through role changes. Native save and SVG with +Preserve Editing retain it; plain SVG export leaves it out. Without an angle, a Crease or Perforation folds at +90 degrees and a Partial Cut at -90 degrees. Fold Preview and `addon.packaging.fold` use each hinge's longest line. + +`addon.packaging.roles` also reports `foldLines` (editable lines that fold), `foldAngle` (their shared angle, or +null when they differ or there are none), `ownAngles` (lines with a valid stored angle), and `storedAngles` +(lines with stored angle text, including damaged values). With nothing selected and no `ids`, the role counts +describe the document and these angle fields report no editable lines. The range and rounding are VectorCraft's own. + ### Fold Preview `addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 043ae5c403..120c31be11 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +- `addon.packaging.setFoldAngle` stores or resets individual fold angles for editable Crease, Partial Cut, and Perforation lines. The fold commands read those angles, and role queries report their shared value and stored-angle counts. Engine tests cover validation, locked compound members, one-step undo, native save, and SVG exports. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From 54ff9ac3234d77e4a3947ec2deef337fb67e1f04 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:01:27 -0800 Subject: [PATCH 034/106] Scripts: invalidate page-item and layer handles after revert --- crates/engine/src/script/dom.rs | 36 +++++++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 22 ++++++++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 ++ 4 files changed, 51 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9c137c96bd..8ac9af150a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -365,12 +365,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result [f64; 5] { + let [high, low] = id_parts(id); + [float(h.run), float(st.uid), high, low, float(st.reverts)] +} + +fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { + let &[run, uid, high, low, reverts] = handle else { return None }; + let doc = find_doc(h, run, uid)?; + if h.session.borrow().documents().get(doc.index)?.reverts != whole(reverts)? { + return None; + } + Some((doc, id_of(high, low)?)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if handle.len() != 5 { + return Err(HostError::Type("this is not a page item".into())); + } + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { @@ -407,8 +422,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &node_handle(h, st, id)), + None => host_ref("Layer", &node_handle(h, st, id)), }, None => Data::Null, } @@ -1883,17 +1898,16 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(handle) = handle.filter(|parts| parts.len() == 5) else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -2057,9 +2071,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 43ee65ba46..4b045220fe 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1196,6 +1196,28 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert"); + let path = folder.join("saved's art.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = "var d = app.activeDocument, i = d.pageItems[0], l = i.parent; i.name = 'changed'; vc.run('file.revert');"; + let out = log(&mut s, &format!("{held} vc.log(d.pageItems.length); vc.log(d.pageItems[0] === i); vc.log(d.pageItems[0].parent === l);")); + assert_eq!(out, vec![json!(2), json!(false), json!(false)]); + for operation in [ + "i.name", + "i.name = 'wrong'", + "l.name", + "i.move(d.pageItems[1], ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].duplicate(i, ElementPlacement.PLACEBEFORE)", + "d.pageItems[1].move(l, ElementPlacement.PLACEATEND)", + ] { + let source = format!("{held} try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);"); + assert_eq!(log(&mut s, &source), vec![json!("Stale page item"), json!(2)], "{operation}"); + } +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 0de3513eac..743159ce7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2850,7 +2850,8 @@ other files through `$`: changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was - deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that + deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws + `Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 022ff2bb6c..ae250b8e21 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -34,6 +34,8 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. +Script page-item and layer objects become stale after `file.revert`, including when the file reuses node IDs. The document object and its collections remain available and return new objects for the reverted content. `crates/engine/src/tests/script_dom.rs` covers reads, assignments, and relative targets for moves and copies. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. From a89c27a9d3a0487dce610a5f9a9f5f7f823195aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:23:30 -0800 Subject: [PATCH 035/106] Clarify default packaging fold angles --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index bff185a671..96ae668100 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16363,8 +16363,9 @@ describe the document and these angle fields report no editable lines. The range `addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it -to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from -the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of +to the base, each by its angle times `amount` (0 is flat, 1 is folded). A valid stored angle sets the fold angle. +Without one, a Crease or a Perforation folds 90° away from the printed side, so the print ends up outside, and a +Partial Cut folds 90° toward it. A hinge that closes a loop of panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything From 956ac0bb578b327987a7d2337290aae083aebc89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:31:32 -0800 Subject: [PATCH 036/106] Keep appearance drags in their source document --- crates/ui-egui/src/canvas/drops.rs | 8 ++- crates/ui-egui/src/canvas/drops/tests.rs | 30 ++++++++++- crates/ui-egui/src/panel_drag.rs | 2 +- crates/ui-egui/src/panels/appearance.rs | 4 +- crates/ui-egui/src/panels/graphic_styles.rs | 56 ++++++++++++++++++-- crates/ui-egui/src/panels/layers/cells.rs | 23 ++++---- crates/ui-egui/src/panels/layers/controls.rs | 6 ++- 7 files changed, 107 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index f2ae87a7a8..732984f606 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -170,7 +170,11 @@ impl Component for CanvasDrops<'_> { } if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. - let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); + let panel = Target::new(rect, view, covered, |p: &PanelDrag| match p { + PanelDrag::Art { .. } => None, + PanelDrag::Appearance { document, .. } if *document != self.document => None, + _ => Some(Payload::Panel(p.clone())), + }); let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); @@ -370,7 +374,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), } run(app, cmd, params) } - Payload::Panel(PanelDrag::Appearance(source)) => { + Payload::Panel(PanelDrag::Appearance { document, source }) if app.session.active().is_some_and(|st| st.uid == *document) => { let Some(hit) = hit() else { return Ok(()) }; let target = top_object(app, &hit)?; if target == source.0 { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 6fdaf1b7af..869737b188 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -119,12 +119,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(PanelDrag::paint(Paint::Gradient(Box::new(gradient)))), on_b, Move).unwrap(); assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none()), "a gradient fits the object it lands on"); app.run("transparency.set", json!({"opacity": 40})).unwrap(); - drop_at(&mut app, Payload::Panel(PanelDrag::Appearance(a)), on_b, Move).unwrap(); + let document = app.session.active().unwrap().uid; + let appearance = |source| Payload::Panel(PanelDrag::Appearance { document, source }); + drop_at(&mut app, appearance(a), on_b, Move).unwrap(); let doc = &app.session.active().unwrap().doc; let (na, nb) = (doc.node(a).unwrap(), doc.node(b).unwrap()); assert_eq!((&nb.appearance, nb.opacity), (&na.appearance, na.opacity), "the appearance is copied"); let n = undo_len(&app); - drop_at(&mut app, Payload::Panel(PanelDrag::Appearance(b)), on_b, Move).unwrap(); + drop_at(&mut app, appearance(b), on_b, Move).unwrap(); assert_eq!(undo_len(&app), n, "dropped on its own source: nothing changes"); let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap()); @@ -292,3 +294,27 @@ fn an_anchor_dragged_off_the_canvas_is_not_carried() { frame(&mut app, &ctx, vec![]); assert!(craft::ui::runtime::drag::active::(&ctx).is_none()); } + +#[test] +fn a_foreign_appearance_drop_never_copies_a_matching_local_object() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + let source = add(&mut app, 20); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = add(&mut app, 20); + assert_eq!(source, other, "both documents have different objects with the same local ID"); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + drop_at(&mut app, Payload::Panel(PanelDrag::Appearance { document, source }), Point::new(250.0, 70.0), DropOperation::Move).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "a foreign appearance drop makes no edit"); +} diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 83ebf46070..5f4f6f0a1f 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -19,7 +19,7 @@ pub enum PanelDrag { /// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it, or with Alt held /// replaces the style it is dropped on with it (`graphicStyle.redefine`). - Appearance(vectorcraft_doc::NodeId), + Appearance { document: u64, source: vectorcraft_doc::NodeId }, /// The selected art, dragged off the canvas with the Selection tool (`document`: the uid of the /// document it came from): the Graphic Styles panel makes a style of the first object /// (`graphicStyle.new`), or with Alt held replaces the style it is dropped on with that diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 2ae612ca36..154f9e55f5 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -799,8 +799,8 @@ fn object_row<'r>(cx: &'r RowCx<'_>) -> ListRow<'r> { None => cx.app.session.paint.fill.clone(), }; let row = row.thumb(ThumbSize::Small, move |painter, rect| paint_preview::paint_rect(painter, rect, &fill)); - match cx.node.filter(|_| cx.mix.is_none()) { - Some(n) => row.part_drag(RowDragSpot::Thumb(ThumbTarget::First), PanelDrag::Appearance(n.id)), + match cx.node.filter(|_| cx.mix.is_none()).zip(cx.app.session.active()) { + Some((n, st)) => row.part_drag(RowDragSpot::Thumb(ThumbTarget::First), PanelDrag::Appearance { document: st.uid, source: n.id }), None => row, } } diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 380a605cd2..bb87966d80 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -601,11 +601,11 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent>) { } /// The object whose look a dropped payload carries: the first of the art dragged from this document, or the -/// Appearance panel's object. +/// Appearance panel's object from this document. fn dropped_object(drag: &PanelDrag, uid: u64) -> Option { match drag { PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(), - PanelDrag::Appearance(id) => Some(*id), + PanelDrag::Appearance { document, source } if *document == uid => Some(*source), _ => None, } } @@ -1322,7 +1322,7 @@ mod tests { let (red, green) = (doc(&app).graphic_style("Red").unwrap().appearance.fill_paint(), doc(&app).node(oval).unwrap().appearance.fill_paint()); let n = names(&app); let document = app.session.active().unwrap().uid; - for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] { + for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance { document, source: oval }] { drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true); let d = doc(&app); assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green); @@ -1388,6 +1388,56 @@ mod tests { assert_eq!(names(&p.app()).len(), before.len() + 1, "a same-document drop still makes a style"); } + #[test] + fn graphic_styles_rejects_a_foreign_appearance_after_next_document() { + use crate::tests::panel_harness::Panel as PanelHarness; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::runtime::drag; + + fn with_appearance(app: &mut VectorcraftApp, ui: &mut Ui) { + let st = app.session.active().unwrap(); + let source = st.selection.objects.first().copied(); + let document = st.uid; + ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new("Appearance source") + .drag_payload(move |_: &ListDrag| source.map(|source| PanelDrag::Appearance { document, source })) + .show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged appearance")); + }); + show(app, ui); + } + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let first = app.session.active().unwrap(); + let (source_document, source_object) = (first.uid, first.selection.objects[0]); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 50})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap(); + let second = app.session.active().unwrap(); + assert_eq!(source_object, second.selection.objects[0], "both documents have distinct objects with the same local ID"); + let target_document = second.uid; + let before = names(&app); + assert!(app.session.set_active(0)); + + let mut p = PanelHarness::new(app, with_appearance); + let from = p.rect("Dragged appearance").center(); + let to = p.rect("Drop Target").center(); + p.drag_hold_role("Dragged appearance", craft::ui::contract::Role::LIST_ITEM, to - from); + assert!(drag::mark(p.ctx()).is_some()); + p.key(egui::Key::F6, egui::Modifiers::COMMAND); + assert_eq!(p.app().session.active().unwrap().uid, target_document, "Next Document switches tabs during the drag"); + let carried = drag::active::(p.ctx()); + assert_eq!(carried.as_deref(), Some(&PanelDrag::Appearance { document: source_document, source: source_object })); + assert!(drag::mark(p.ctx()).is_none(), "the target withdraws its drop indicator for the foreign appearance"); + p.release(); + assert_eq!(names(&p.app()), before, "the foreign drop creates no style from the current document's same-ID object"); + + p.drag("Dragged appearance", "Drop Target", egui::Modifiers::NONE); + assert_eq!(names(&p.app()).len(), before.len() + 1, "a same-document appearance still makes a style"); + } + /// A style dropped on another with Alt takes that style's look; on itself it does nothing. #[test] fn a_style_dropped_on_another_with_alt_replaces_that_style() { diff --git a/crates/ui-egui/src/panels/layers/cells.rs b/crates/ui-egui/src/panels/layers/cells.rs index 1b9bdadd43..130e16c2c3 100644 --- a/crates/ui-egui/src/panels/layers/cells.rs +++ b/crates/ui-egui/src/panels/layers/cells.rs @@ -92,6 +92,7 @@ impl Outcome for CellOutput { pub(super) struct TargetCircle { #[common] common: Common, + document: u64, id: NodeId, targeted: bool, styled: bool, @@ -101,18 +102,19 @@ pub(super) struct TargetCircle { } impl TargetCircle { - fn new(id: NodeId, targeted: bool, styled: bool) -> Self { - Self { common: Common::new(), id, targeted, styled, held: false, pick: None } + fn new(document: u64, id: NodeId, targeted: bool, styled: bool) -> Self { + Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None } } /// A targeted circle with an appearance, for the suite. fn sample() -> Self { - Self::new(NodeId(1), true, true).label("Target") + Self::new(1, NodeId(1), true, true).label("Target") } } /// The circle as a drop target: it takes another row's appearance. struct TakesAppearance { + document: u64, own: NodeId, rect: Rect, } @@ -122,7 +124,9 @@ impl DropTarget for TakesAppearance { fn accept(&self, payload: &PanelDrag, _: Pos2, op: DropOperation) -> Option<(NodeId, bool)> { match payload { - PanelDrag::Appearance(source) if *source != self.own => Some((*source, op == DropOperation::Copy)), + PanelDrag::Appearance { document, source } if *document == self.document && *source != self.own => { + Some((*source, op == DropOperation::Copy)) + } _ => None, } } @@ -165,13 +169,12 @@ impl Component for TargetCircle { self.pick = Some(CellPick::Target(activation.mods)); } if primary_drag_start(cx) { - cx.start_drag(PanelDrag::Appearance(self.id), DragPreview::None); + cx.start_drag(PanelDrag::Appearance { document: self.document, source: self.id }, DragPreview::None); } let rect = cx.rect; - let own = self.id; - self.held = - cx.dragging::().is_some_and(|(drag, at)| rect.contains(at) && matches!(*drag, PanelDrag::Appearance(source) if source != own)); - if let Some((source, copy)) = cx.drop_target::(&TakesAppearance { own, rect }) { + let target = TakesAppearance { document: self.document, own: self.id, rect }; + self.held = cx.dragging::().is_some_and(|(drag, at)| rect.contains(at) && target.accept(&drag, at, DropOperation::Move).is_some()); + if let Some((source, copy)) = cx.drop_target::(&target) { self.pick = Some(CellPick::TakeAppearance { source, copy }); } } @@ -373,7 +376,7 @@ pub(super) fn build(tree: &DocLayers<'_>, row: &RowId, info: &LayerInfo) -> Cell let is_sel = selected(id); let (full, holds) = square_marks(tree, n); let art = if full || holds { st.selection.objects.clone() } else { vec![] }; - let circle = TargetCircle::new(id, shows_targeted(tree, n, is_sel), has_styled_target(n)) + let circle = TargetCircle::new(st.uid, id, shows_targeted(tree, n, is_sel), has_styled_target(n)) .label(crate::i18n::fmt(tl!("Target {row}"), &[("row", info.name.as_str())])); let square = SelectionSquare::new(Some(id), full, holds, color, art) .label(crate::i18n::fmt(tl!("Select art of {row}"), &[("row", info.name.as_str())])); diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index b337508c90..df30e7e731 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -464,8 +464,10 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value if let Some(drop) = &output.dropped { let run = if let Some(d) = drop.payload::>>() { footer_drop(tree, drop.index, FooterPayload::Rows(&d.keys)) - } else if let Some(PanelDrag::Appearance(id)) = drop.payload::() { - footer_drop(tree, drop.index, FooterPayload::Appearance(id.0)) + } else if let Some(PanelDrag::Appearance { document, source }) = drop.payload::() + && *document == st.uid + { + footer_drop(tree, drop.index, FooterPayload::Appearance(source.0)) } else { None }; From c192dfbd768c28ffb4427301cdfa12c4abdefdcf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:51:29 -0800 Subject: [PATCH 037/106] Preserve explicit preference edits and refresh Apply baselines --- crates/ui-egui/src/prefs_dialog.rs | 30 ++++++++- crates/ui-egui/src/prefs_dialog/model.rs | 29 ++++++++- crates/ui-egui/src/prefs_dialog/tests.rs | 78 ++++++++++++++++++++++++ docs/mcp.md | 9 ++- docs/target-app-parity.md | 2 +- 5 files changed, 139 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index a5040f5022..8724cbe520 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -105,6 +105,26 @@ impl PrefsWindow { self.touched.remove(key); } + fn explicitly_edited(&self, key: &str) -> bool { + if self.touched.contains(key) { + return true; + } + let (now, opened) = (self.draft.get::(key), self.opened.get::(key)); + match (now.as_ref().and_then(Value::as_f64), opened.as_ref().and_then(Value::as_f64)) { + (Some(a), Some(b)) => a != b, + _ => now != opened, + } + } + + fn read_external(&mut self, key: &str, value: &Value) { + if self.explicitly_edited(key) { + self.source.set(key, value); + } else { + self.read(key, value); + self.opened.set(key, value); + } + } + /// Sets the row `key` in the window, as the user or a reset does. fn set_row(&mut self, key: &str, value: &Value) { self.draft.set(key, value); @@ -127,6 +147,7 @@ impl PrefsWindow { for (k, v) in prefs.as_object().into_iter().flatten() { if self.draft.get::(k).is_some() { self.read(k, v); + self.opened.set(k, v); } } self.reset_units = self.draft.get::("unitsGeneral"); @@ -408,7 +429,7 @@ fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindo } // The window shows the reset row, so OK keeps it. if let Some(w) = w.as_deref_mut() { - w.read(key, &json!(value)); + w.read_external(key, &json!(value)); } } // And the reset preferences, the groups with a reset of every category; Units ▸ General then leaves the open @@ -419,8 +440,9 @@ fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindo for (k, v) in prefs.as_object().into_iter().flatten() { let reset = spec(k).map_or(every && PREF_GROUPS.contains(&k.as_str()), |s| in_reset(s.category)); if reset && w.draft.get::(k).is_some() { - w.read(k, v); - if k == "unitsGeneral" { + let edited = w.explicitly_edited(k); + w.read_external(k, v); + if k == "unitsGeneral" && !edited { w.reset_units = v.as_str().map(str::to_string); } } @@ -429,7 +451,9 @@ fn apply_prefs_resets_to(app: &mut VectorcraftApp, mut w: Option<&mut PrefsWindo } // The Edit Original row shows the app's Edit Original choice. if spec("editOriginalSystemDefaults").is_some_and(|s| in_reset(s.category)) { + let before = app.ui.original_editor.clone(); crate::original_editor::reset_saved(app); + app.prefs_changed |= before != app.ui.original_editor; } true } diff --git a/crates/ui-egui/src/prefs_dialog/model.rs b/crates/ui-egui/src/prefs_dialog/model.rs index ef8197ba08..af35fcdb84 100644 --- a/crates/ui-egui/src/prefs_dialog/model.rs +++ b/crates/ui-egui/src/prefs_dialog/model.rs @@ -427,8 +427,20 @@ impl PreferencesDraft for Live<'_> { // A `prefs.reset` run since the last frame shows in the draft before OK reads it. super::apply_prefs_resets_to(self.app, Some(&mut *self.w)); // Only the rows changed in the window: a setting changed outside it while it is open keeps its new value. - let edited: Map = - self.w.draft.to::>().unwrap_or_default().into_iter().filter(|(k, _)| self.w.edited(k)).collect(); + let current = self.app.session.prefs.to_json(); + let edited: Map = self + .w + .draft + .to::>() + .unwrap_or_default() + .into_iter() + .filter(|(k, _)| { + self.w.edited(k) + && (k != "keyHoldDelay" + || self.w.explicitly_edited(k) + || current.get(k).and_then(Value::as_f64) == self.w.source.get::(k).as_ref().and_then(Value::as_f64)) + }) + .collect(); let values: Map = edited.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool); let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u)); @@ -463,10 +475,23 @@ impl PreferencesDraft for Live<'_> { } // The row shows the task bar in use: after OK enters Touch, that is Touch's, not the value the workspace left // took, so a later Apply does not give the workspace left's value to Touch. + let current = self.app.session.prefs.to_json(); + for (key, value) in current.as_object().into_iter().flatten() { + if self.w.draft.get::(key).is_some() { + self.w.draft.set(key, value); + } + } + if let Some(state) = self.app.session.active() { + self.w.draft.set("unitsGeneral", &state.doc.units.key()); + } + self.w.draft.set("__smartGuides", &self.app.ui.view.smart_guides); + self.w.draft.set("__snapToGrid", &self.app.ui.view.snap_to_grid); self.w.draft.set("__taskBar", &self.app.ui.task_bar); self.w.opened = self.w.draft.clone(); self.w.source = self.w.draft.clone(); self.w.touched.clear(); + self.w.reset_units = None; + self.w.sync_strings(); Ok(()) } diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index af3e9487cb..b4e3b3843f 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -61,6 +61,84 @@ fn field(a: &VectorcraftApp, key: &str) -> Value { fields(a).and_then(|f| f.get(key).cloned()).unwrap_or(Value::Null) } +#[test] +fn applying_a_reset_allows_a_later_explicit_document_units_edit() { + use craft::ui::patterns::preferences::PreferencesDraft as _; + let mut a = app(); + a.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + a.run("document.setUnits", json!({"units": "Inches"})).unwrap(); + open(&mut a, Some("General")); + reset_preferences(&mut a, PromptChoice::Proceed); + let mut window = a.prefs.take().unwrap(); + model::Live { app: &mut a, w: &mut window }.apply().unwrap(); + a.prefs = Some(window); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Inches); + set_field(&mut a, "unitsGeneral", json!("points")).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.active().unwrap().doc.units, vectorcraft_doc::Unit::Points); +} + +#[test] +fn imported_rows_follow_a_later_external_reset() { + let mut a = app(); + open(&mut a, Some("General")); + let data = json!({"format": "vectorcraft-preferences", "version": 1, "prefs": {"keyboardIncrement": 7}}).to_string(); + a.run("prefs.import", json!({"data": data})).unwrap(); + a.run("prefs.reset", json!({"category": "General"})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, Prefs::default().keyboard_increment); +} + +#[test] +fn a_command_changed_delay_survives_opening_time_normalization() { + let mut a = app(); + a.session.prefs.key_hold_delay = 5.0; + open(&mut a, Some("General")); + a.run("prefs.set", json!({"key": "keyHoldDelay", "value": 0.6})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.key_hold_delay, 0.6); +} + +#[test] +fn an_external_reset_keeps_rows_edited_in_preferences() { + let mut a = app(); + open(&mut a, Some("General")); + set_field(&mut a, "keyboardIncrement", json!(9)).unwrap(); + let smart = !a.ui.view.smart_guides; + set_field(&mut a, "__smartGuides", json!(smart)).unwrap(); + a.run("prefs.reset", json!({})).unwrap(); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.keyboard_increment, 9.0); + assert_eq!(a.ui.view.smart_guides, smart); +} + +#[test] +fn an_external_editor_reset_requests_a_settings_save() { + let mut a = app(); + a.ui.original_editor = serde_json::from_value(json!({"path": "editor"})).unwrap(); + a.prefs_changed = false; + a.session.execute("prefs.reset", &json!({"category": "File Handling"})).unwrap(); + a.prefs_changed = false; + apply_prefs_resets(&mut a); + assert!(a.prefs_changed); +} + +#[test] +fn apply_refreshes_untouched_rows_from_current_preferences() { + use craft::ui::patterns::preferences::PreferencesDraft as _; + let mut a = app(); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 7})).unwrap(); + open(&mut a, Some("General")); + a.run("prefs.set", json!({"key": "keyboardIncrement", "value": 9})).unwrap(); + set_field(&mut a, "constrainAngle", json!(30)).unwrap(); + let mut w = a.prefs.take().unwrap(); + model::Live { app: &mut a, w: &mut w }.apply().unwrap(); + assert_eq!(w.draft.get::("keyboardIncrement"), Some(json!(9.0))); + assert_eq!(w.opened.get::("keyboardIncrement"), Some(json!(9.0))); + assert_eq!(w.source.get::("keyboardIncrement"), Some(json!(9.0))); + assert!(!w.edited("keyboardIncrement")); +} + /// One row per kind is saved by OK: the model's value conversion reaches `prefs.set` for each. #[test] fn ok_saves_every_row_kind() { diff --git a/docs/mcp.md b/docs/mcp.md index cf426c00e1..d2c53c2d7b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9358,8 +9358,11 @@ as it was, and `ui.dialog.confirm` shows it again with every preference at its d Preferences. `prefs.reset` resets the preferences at once, without the question. OK in Preferences writes only the fields changed in the dialog since it opened or since its last Apply, so a preference, Smart Guides, Snap to Grid, Enable Contextual Task Bar or the document's units changed some other way while it is open (a command, a panel menu, -a script) keeps its new value. A field changed both ways takes the dialog's value. OK with no field changed writes -nothing and adds no undo step. +a script) keeps its new value when its dialog field is unchanged. A field changed both ways takes the dialog's value. +An opening-time correction of Hold Shortcut Delay does not overwrite a later command change. Apply refreshes the +dialog's baseline from the current preferences and UI values. OK also saves an opening-time Hold Shortcut Delay +correction when no later command changed that value. With no field change or delay correction, OK writes nothing +and adds no undo step. ```json {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"unitsGeneral","value":"millimeters"}}} @@ -9368,7 +9371,7 @@ nothing and adds no undo step. Reset Preferences also sets the dialog's `__smartGuides`, `__snapToGrid` and `__taskBar` fields to their defaults (`__taskBar` takes the value the current workspace was saved with). A category's own reset sets the field of that category (Smart Guides, Guides & Grid or General), and File Handling's also resets the app chosen for Edit Original. -`prefs.reset` run while Preferences is open shows the values it reset in the dialog. In the app, `prefs.reset` also resets Smart Guides, +`prefs.reset` run while Preferences is open updates its unchanged fields and preserves edits in the dialog. In the app, `prefs.reset` also resets Smart Guides, Snap to Grid and Enable Contextual Task Bar when it resets every category or their category (Smart Guides, Guides & Grid and General), and the app chosen for Edit Original when it resets every category or File Handling. A `category` left out or `null` resets every category, and one that is not a string is an error. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7fbbf7c200..cdd0bb8796 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -910,7 +910,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences resets every setting the dialog shows:** Smart Guides and Snap to Grid also return to their defaults (on and off) when Reset Preferences is confirmed, and General's Enable Contextual Task Bar takes the value the current workspace was saved with. OK in Preferences applies them with the other defaults, and Cancel keeps the values in use. A category's own reset resets the row of that category, and File Handling's also resets the app chosen for Edit Original. `prefs.reset` (the Command Palette's Reset Preferences) resets them too, each only when it resets every category or the setting's own, and with every category or File Handling it also clears the app chosen for Edit Original. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`, `crates/ui-egui/src/original_editor.rs`. -- **Preferences OK keeps changes made outside the dialog:** OK writes only the settings changed in the dialog, so a preference, Smart Guides, Snap to Grid, Enable Contextual Task Bar or the document's units changed by a command or a script while Preferences is open keeps its new value, and a workspace switched to while it is open keeps its own Contextual Task Bar. OK with nothing changed writes nothing. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences OK keeps changes made outside the dialog:** OK preserves command or script changes to fields left unchanged in the dialog, including preferences, Smart Guides, Snap to Grid, Enable Contextual Task Bar and document units. A field edited in both places takes the dialog's value. OK saves an opening-time Hold Shortcut Delay correction unless a later command changed that value. An external reset preserves dialog edits, and Apply refreshes the baseline from current preferences and UI values. A workspace switched to while the dialog is open keeps its own Contextual Task Bar. With no field change or delay correction, OK writes nothing. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. From 70b1be0b5764326d0aa0d57d30e410218f13e787 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:09:48 -0800 Subject: [PATCH 038/106] Qualify the color crate SHA-256 lock dependency --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] From a0f140310d198e6546b0773df7da30f8bf26bed7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 20:05:23 -0800 Subject: [PATCH 039/106] Identify browser Place sources independently of duplicate filenames --- crates/tools/src/place.rs | 28 ++++++++- crates/ui-egui/src/place.rs | 36 ++++++++---- crates/ui-egui/src/tests/place.rs | 97 ++++++++++++++++++++++++++++++- docs/mcp.md | 5 +- 4 files changed, 148 insertions(+), 18 deletions(-) diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index 813ec99429..3564bb3667 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -12,6 +12,8 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool /// One loaded file. #[derive(Clone, Debug, PartialEq)] struct Entry { + /// Its position in the original load, retained when other entries are discarded. + source_index: usize, /// `file.place` params (the file and its options). params: Value, name: String, @@ -141,12 +143,13 @@ impl Tool for PlaceTool { Cursor::Crosshair } - /// `{count, current, name, width, height, names}`: what the cursor holds (no file data). + /// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data). fn options(&self) -> Value { let e = self.entry(); json!({ "count": self.entries.len(), "current": self.current, + "sourceIndex": e.map(|e| e.source_index), "name": e.map(|e| &e.name), "width": e.map(|e| e.width), "height": e.map(|e| e.height), @@ -163,8 +166,10 @@ impl Tool for PlaceTool { .as_array() .into_iter() .flatten() - .filter_map(|e| { + .enumerate() + .filter_map(|(source_index, e)| { Some(Entry { + source_index, params: e.get("params").filter(|p| p.is_object())?.clone(), name: e["name"].as_str().unwrap_or_default().to_string(), width: e["width"].as_f64().filter(|v| v.is_finite())?, @@ -359,4 +364,23 @@ mod tests { t.key(&c, ToolKey::Escape, Mods::default()); assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]); } + + #[test] + fn source_indices_survive_removal_and_never_enter_place_params() { + let (d, _) = doc_with_rect(); + let (s, p) = (Default::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = loaded(3); + t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(t.options()["sourceIndex"], 1); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!((t.options()["current"].clone(), t.options()["sourceIndex"].clone()), (json!(1), json!(2))); + t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0)); + let acts = t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0)); + assert_eq!(acts, vec![Action::Exec("file.place".into(), json!({"path": "f2.png", "rect": [0.0, 0.0, 40.0, 20.0]}))]); + assert_eq!(t.options()["sourceIndex"], 0); + assert!(t.check_option("sourceIndex", &json!(0)).is_err(), "the source identity is read only"); + t.key(&c, ToolKey::Escape, Mods::default()); + assert_eq!(t.options()["sourceIndex"], Value::Null); + } } diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index 478cc4157d..30851eaa74 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -85,7 +85,7 @@ pub fn is_document(name: &str) -> bool { /// The app's Place state (not saved with the preferences). #[derive(Default)] pub struct PlaceState { - /// Web: the bytes of the files picked for the Place dialog, by name. + /// Web: the bytes of the files picked for the Place dialog, by selection token. pub(crate) picked: Vec<(String, Vec)>, /// The loaded cursor's thumbnails by file name. thumbs: Vec<(String, Thumb)>, @@ -140,6 +140,7 @@ const SET_ASIDE: &str = "__placeCursorOptions"; /// A place cursor thumbnail, decoded when the cursor is loaded. struct Thumb { + source_index: usize, image: std::sync::Arc, } @@ -175,6 +176,13 @@ impl PlaceState { pub(crate) fn thumbnails(&self) -> Vec<&str> { self.thumbs.iter().map(|(n, _)| n.as_str()).collect() } + + /// The current entry's thumbnail, even after earlier entries with the same name are removed. + pub(crate) fn cursor_thumbnail(&self, options: &Value) -> Option<(usize, &egui::ColorImage)> { + let source_index = usize::try_from(options["sourceIndex"].as_u64()?).ok()?; + let (_, thumb) = self.thumbs.iter().find(|(_, thumb)| thumb.source_index == source_index)?; + Some((source_index, thumb.image.as_ref())) + } } /// Run engine command `id` itself (past the UI's handling of the same id); an error shows in the @@ -346,14 +354,15 @@ fn pick(app: &mut VectorcraftApp, p: &Value) -> Value { paths.into_iter().map(|path| with_importer(json!({ "path": path.to_string_lossy() }), &with)).collect() } Picked::Contents(files) => { - // The next Place dialog replaces the previous selection, including its source bytes. + // A replacement selection owns a new set of source bytes. app.place.picked.clear(); files .into_iter() .map(|(name, bytes)| { - app.place.picked.retain(|(n, _)| *n != name); - let entry = with_importer(json!({ "name": name }), &with); - app.place.picked.push((name, bytes)); + static SOURCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let source = SOURCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed).to_string(); + let entry = with_importer(json!({ "name": name, "__pickedSource": source }), &with); + app.place.picked.push((source, bytes)); entry }) .collect() @@ -476,7 +485,9 @@ fn source(app: &VectorcraftApp, file: &Value) -> Option { return Some(with_importer(json!({ "path": path }), file)); } let name = file.get("name").and_then(Value::as_str)?; - let bytes = app.place.picked.iter().find(|(n, _)| n == name).map(|(_, b)| b)?; + // The selection token is UI bookkeeping; only the original name and bytes reach the engine. + let source = file.get("__pickedSource").and_then(Value::as_str).unwrap_or(name); + let bytes = app.place.picked.iter().find(|(n, _)| n == source).map(|(_, b)| b)?; Some(with_importer(json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), file)) } @@ -771,11 +782,12 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) { .as_array() .into_iter() .flatten() - .filter_map(|f| { + .enumerate() + .filter_map(|(source_index, f)| { let png = vectorcraft_format::base64_decode(f["thumbnailBase64"].as_str()?)?; let img = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &png).ok()?; let color = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], &img.to_rgba8()); - Some((f["name"].as_str()?.to_string(), Thumb { image: std::sync::Arc::new(color) })) + Some((f["name"].as_str()?.to_string(), Thumb { source_index, image: std::sync::Arc::new(color) })) }) .collect(); } @@ -787,15 +799,15 @@ pub fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos let opts = app.session.tool_options(); let count = opts["count"].as_u64().unwrap_or(0); let name = opts["name"].as_str().unwrap_or_default(); - let found = app.place.thumbs.iter().enumerate().find(|(_, (n, _))| n == name); + let found = (app.place.queue_load == app.session.place_queue_loads()).then(|| app.place.cursor_thumbnail(&opts)).flatten(); let revision = Revision::new(app.place.queue_load); let room = egui::Rect::from_min_max(at, ui.max_rect().max.max(at)); ui.scope_builder(egui::UiBuilder::new().max_rect(room), |ui| { match found { - Some((key, (_, thumb))) => { + Some((key, image)) => { let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX); - let [w, h] = thumb.image.size; - Picture::new(name.to_string(), key as u64, &|| (*thumb.image).clone()) + let [w, h] = image.size; + Picture::new(name.to_string(), key as u64, &|| image.clone()) .revision(revision) .aspect(ThumbAspect::new(side(w), side(h))) .extent(PictureSize::Thumb(ThumbSize::Medium)) diff --git a/crates/ui-egui/src/tests/place.rs b/crates/ui-egui/src/tests/place.rs index 5aad0ffa32..52faf0b85e 100644 --- a/crates/ui-egui/src/tests/place.rs +++ b/crates/ui-egui/src/tests/place.rs @@ -134,11 +134,12 @@ fn cancelling_browser_place_releases_the_picked_file_buffers() { crate::file_asks::poll(&mut app); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1); + let source = app.place.picked[0].0.clone(); // Cancelling a replacement file picker leaves the existing Place selection usable. app.run("file.place", json!({})).unwrap(); picker.cancel(); crate::file_asks::poll(&mut app); - assert_eq!(app.place.picked[0].0, name); + assert_eq!(app.place.picked[0].0, source); dismiss(&mut app); crate::place::pump(&mut app, &ctx); assert!(app.place.picked.is_empty(), "a cancelled Place selection no longer owns file bytes"); @@ -210,7 +211,7 @@ fn an_old_place_ok_cannot_consume_a_newer_dialogs_browser_bytes() { assert_eq!(app.ui.status, "new selection", "the retired OK reports no stale error"); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1); - assert_eq!(app.place.picked[0].0, "new.png"); + assert_eq!(app.place.picked[0].1.as_slice(), bytes.as_slice()); assert!(app.session.active().unwrap().doc.layers[0].children().unwrap().is_empty()); answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); assert!(app.place.picked.is_empty()); @@ -234,7 +235,7 @@ fn an_old_place_cancellation_keeps_a_newer_dialogs_browser_bytes() { crate::place::pump(&mut app, &ctx); assert_eq!(dialog_kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); assert_eq!(app.place.picked.len(), 1, "the replacement owns only its own source bytes"); - assert_eq!(app.place.picked[0].0, "new.png"); + assert_eq!(app.place.picked[0].1.as_slice(), bytes.as_slice()); answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); assert!(app.place.picked.is_empty(), "confirmation transfers the bytes out of the dialog cache"); assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1, "the newer file still places"); @@ -323,6 +324,96 @@ fn selected_image(app: &VectorcraftApp) -> vectorcraft_doc::Node { n } +/// Browser file names are labels, not unique source identities. Both the bytes and the cursor +/// thumbnail must follow each selection through cycling, placement and discarding another file. +#[test] +fn browser_place_keeps_same_named_files_and_their_cursor_thumbnails_distinct() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + let load = |app: &mut VectorcraftApp| { + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.png", &a), ("same.png", &b)]); + poll(app, &ctx); + assert_eq!( + fields(app)["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect::>(), + ["same.png", "same.png"] + ); + answer(app, &[("link", json!(false)), ("showImportOptions", json!(false))]); + assert_eq!(app.session.tool_options()["count"], 2); + }; + let thumbnail = |app: &VectorcraftApp| { + let options = app.session.tool_options(); + let (source, image) = app.place.cursor_thumbnail(&options).expect("the selected entry has its own thumbnail"); + (source, image.size) + }; + let placed = |app: &VectorcraftApp, size| { + let node = selected_image(app); + assert_eq!(node.name.as_deref(), Some("same.png")); + let NodeKind::Image(image) = node.kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + }; + load(&mut app); + let first = thumbnail(&app); + tool_key(&mut app, vectorcraft_tools::ToolKey::Right); + let second = thumbnail(&app); + assert_eq!((first.0, second.0), (0, 1)); + assert_ne!(first.1, second.1, "the distinct image proportions have distinct thumbnails"); + tool_key(&mut app, vectorcraft_tools::ToolKey::Left); + click(&mut app); + placed(&app, (8, 5)); + assert_eq!(thumbnail(&app), second, "removing the first entry must not shift the thumbnail identity"); + click(&mut app); + placed(&app, (3, 2)); + + load(&mut app); + tool_key(&mut app, vectorcraft_tools::ToolKey::Escape); + assert_eq!(thumbnail(&app), second, "discarding the first entry preserves the second thumbnail"); + click(&mut app); + placed(&app, (3, 2)); +} + +/// Each browser selection places its own bytes, in selection order, with its original name. +#[test] +fn browser_place_keeps_same_named_file_bytes_in_order() { + let mut app = app(); + let ctx = window(&app); + let picker = scripted(&mut app); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("same.png", &a), ("same.png", &b)]); + poll(&mut app, &ctx); + answer(&mut app, &[("link", json!(false)), ("showImportOptions", json!(false))]); + for size in [(8, 5), (3, 2)] { + click(&mut app); + let node = selected_image(&app); + assert_eq!(node.name.as_deref(), Some("same.png")); + let NodeKind::Image(image) = node.kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + } +} + +/// Automation already supplies each file's bytes directly; the same names retain their order too. +#[test] +fn an_automated_place_queue_keeps_same_named_file_bytes_in_order() { + let mut app = app(); + let (a, b) = (png(8, 5, 72.0), png(3, 2, 72.0)); + app.run( + "file.place.queue", + json!({"link": false, "files": [ + {"name": "same.png", "dataBase64": vectorcraft_format::base64_encode(&a)}, + {"name": "same.png", "dataBase64": vectorcraft_format::base64_encode(&b)} + ]}), + ) + .unwrap(); + for size in [(8, 5), (3, 2)] { + click(&mut app); + let NodeKind::Image(image) = selected_image(&app).kind else { panic!("Place selects the raster just placed") }; + assert_eq!((image.width, image.height), size); + } +} + /// A tiny SVG document. const SVG: &str = r#""#; diff --git a/docs/mcp.md b/docs/mcp.md index 151708f897..d219517ee5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9840,7 +9840,10 @@ its allocation limit. Importing individual layers with `layers: true` retains it `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and -`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The cursor keeps an encrypted PDF, `.ai` +`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The place tool's state includes a +read-only `sourceIndex`: the current file's zero-based position in the original load, or null when empty. +It stays with that file when other files are placed or discarded; `current` indexes the remaining files. +The cursor keeps an encrypted PDF, `.ai` or `.ait` file that it cannot read without the password, at 612 × 792 pt (VectorCraft's own size) with `needsPassword: true` and no thumbnail; in the app a click or drag on it asks for the password, and headless it places nothing. `file.place`, `file.place.queue` and From 1513db4d8c33a9409e23f36f89de69110c00104e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:27:28 -0800 Subject: [PATCH 040/106] Keep Average path approvals with their opening drawing --- crates/ui-egui/src/dialogs/path_ops.rs | 89 +++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 65179c95ca..d246535baa 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -426,7 +426,8 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem app.status("There is no window to show the dialog in."); return; }; - let document = app.session.active().map(|state| state.uid); + let drawing = app.session.active().map(|state| (state.uid, state.reverts)); + let document = drawing.map(|(uid, _)| uid); if op.previews() && document.is_none() { app.status("Open a document before editing paths."); return; @@ -450,6 +451,9 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem let Some(mut record) = take_open(app, op) else { return Err(tl!("The path dialog is closed.").to_owned()) }; record.commit(app, cmd, params).inspect_err(|_| app.object_dialogs.path.push(record))?; } else { + if app.session.active().map(|state| (state.uid, state.reverts)) != drawing { + return Err(tl!("Return to the opening drawing, or reopen this dialog after File Revert.").to_owned()); + } app.run(cmd, params).map(drop)?; } match op { @@ -616,6 +620,89 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> { .collect() } +#[cfg(test)] +mod average_document_tests { + use super::*; + use crate::dialogs::tests::{app, cancel, confirm, is_open, set}; + + fn lines(app: &mut VectorcraftApp, top: i32) -> [u64; 2] { + let a = app.run("shape.line", json!({"x1": 10, "y1": top, "x2": 50, "y2": top})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.line", json!({"x1": 60, "y1": top + 20, "x2": 100, "y2": top + 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + [a, b] + } + + fn opening_owns_approval(op: PathOp) { + for revert in [false, true] { + let mut app = app(); + let source_paths = lines(&mut app, 20); + let uid = app.session.active().unwrap().uid; + let generation = app.session.active().unwrap().reverts; + let dir = vectorcraft_testkit::TempDir::new("average-path-dialog-drawing"); + if revert { + let path = dir.join("saved-paths.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap(); + app.run("object.move", json!({"ids": source_paths, "dx": 12, "dy": 0})).unwrap(); + } else { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert_eq!(lines(&mut app, 80), source_paths); + app.run("document.activate", json!({"index": 0})).unwrap(); + } + let open = |app: &mut VectorcraftApp| { + crate::menus::invoke(app, op.key(), json!({})); + assert!(is_open(app)); + if op == PathOp::Average { + set(app, "axis", json!("both")); + } else { + set(app, "to", json!("smooth")); + } + }; + open(&mut app); + if revert { + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.set", json!({"ids": source_paths})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, generation + 1)); + } else { + app.run("document.activate", json!({"index": 1})).unwrap(); + assert_ne!(app.session.active().unwrap().uid, uid); + } + let wrong = app.session.active().unwrap(); + let (before, undo) = (wrong.doc.clone(), wrong.history.undo.len()); + let accepted = confirm(&mut app); + let after = app.session.active().unwrap(); + assert!(after.doc == before, "the old path approval must leave the other drawing contents intact"); + assert_eq!(after.history.undo.len(), undo); + assert!(!accepted && is_open(&app)); + + if revert { + assert!(cancel(&mut app)); + open(&mut app); + } else { + app.run("document.activate", json!({"index": 0})).unwrap(); + } + let before = app.session.active().unwrap(); + let (geometry, undo) = (before.doc.clone(), before.history.undo.len()); + assert!(confirm(&mut app)); + let after = app.session.active().unwrap(); + assert!(after.doc != geometry, "a current approval edits the intended paths"); + assert_eq!(after.history.undo.len(), undo + 1); + } + } + + #[test] + fn average_path_approval_stays_with_its_drawing() { + opening_owns_approval(PathOp::Average); + } + + #[test] + fn average_join_approval_stays_with_its_drawing() { + opening_owns_approval(PathOp::AverageJoin); + } +} + #[cfg(test)] mod split_tests { use serde_json::json; From f12a8f6ffe846f18aee8488b49a79c864695d076 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:44:59 -0800 Subject: [PATCH 041/106] Retire path options after File Revert --- crates/ui-egui/src/dialogs/path_ops.rs | 91 +++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 12205dca03..c31f379d09 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -114,6 +114,7 @@ pub(crate) struct Open { op: PathOp, id: DialogId, document: u64, + reverts: u64, preview: LivePreview, /// A distinct selection snapshot identifies the interaction that ran this preview. preview_selection: Option>, @@ -371,6 +372,7 @@ impl Open { let Some(selection) = &self.preview_selection else { return false }; app.session.active().is_some_and(|state| { state.uid == self.document + && state.reverts == self.reverts && state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection)) }) } @@ -382,8 +384,11 @@ impl Open { } fn commit(&mut self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result<(), String> { - if app.session.active().is_none_or(|state| state.uid != self.document) { + let Some(state) = app.session.active().filter(|state| state.uid == self.document) else { return Err(tl!("Return to the document where this dialog opened.").to_owned()); + }; + if state.reverts != self.reverts { + return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } if app.session.in_interaction() && !self.owns_preview(app) { return Err(tl!("Finish the active edit before confirming.").to_owned()); @@ -471,6 +476,7 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem if let Some(old) = take_open(app, op) { old.cancel(app); } + let reverts = app.session.active().map_or(0, |state| state.reverts); let id = if op.previews() { let cancel = Box::new(move |app: &mut VectorcraftApp| { // A cancelled opening can leave a replacement with the same dialog ID. @@ -494,6 +500,7 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem op, id, document, + reverts, preview: LivePreview::default(), preview_selection: None, last: Value::Null, @@ -562,7 +569,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { fn step(app: &mut VectorcraftApp, r: &mut Open) { let Some((on, fields)) = dialog_state(app, r.id) else { return }; - let Some(state) = app.session.active().filter(|state| state.uid == r.document) else { return }; + let Some(state) = app.session.active().filter(|state| state.uid == r.document && state.reverts == r.reverts) else { return }; if !r.owns_preview(app) { r.preview = LivePreview::default(); r.preview_selection = None; @@ -796,6 +803,8 @@ mod split_tests { #[cfg(test)] mod preview_document_tests { + use craft::ui::dialog::HeldOk; + use super::*; use crate::dialogs::tests::{app, cancel, confirm, frame, set}; @@ -821,6 +830,84 @@ mod preview_document_tests { crate::dialogs::simplify_slider::more_options(app).unwrap(); } + fn show_path_options(app: &mut VectorcraftApp, op: PathOp) { + if op == PathOp::Simplify { + more_options(app); + } else { + crate::menus::invoke(app, op.key(), json!({})); + set(app, "offset", json!(12.0)); + } + set(app, "preview", json!(false)); + } + + fn path_options_after_revert(op: PathOp, hold_ok: bool) -> (VectorcraftApp, DialogId) { + let mut app = app(); + let id = if op == PathOp::Simplify { + dense_path(&mut app, 50.0) + } else { + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap() + }; + let folder = vectorcraft_testkit::TempDir::new("path-options-revert"); + let path = folder.join("paths.vectorcraft"); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": path})).unwrap(); + app.run("object.move", json!({"ids": [id], "dx": 5, "dy": 0})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let source = app.session.active().unwrap(); + let (uid, reverts) = (source.uid, source.reverts); + show_path_options(&mut app, op); + let dialog_id = app.object_dialogs.path.iter().find(|open| open.op == op).unwrap().id; + if hold_ok { + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id))); + } + app.run("file.revert", json!({"confirmed": true})).unwrap(); + let restored = app.session.active().unwrap(); + assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1)); + assert!(restored.doc.node(NodeId(id)).is_some()); + app.run("select.set", json!({"ids": [id]})).unwrap(); + (app, dialog_id) + } + + #[test] + fn path_options_revert_drops_old_preview() { + for op in [PathOp::Simplify, PathOp::OffsetPath] { + let (mut app, _) = path_options_after_revert(op, false); + let restored = app.session.active().unwrap().doc.clone(); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.active().unwrap().doc == restored, "the old path preview reached restored artwork"); + assert!(!app.session.in_interaction()); + } + } + + #[test] + fn path_options_revert_refuses_held_ok_and_accepts_a_new_opening() { + for op in [PathOp::Simplify, PathOp::OffsetPath] { + let (mut app, dialog) = path_options_after_revert(op, true); + let source = app.session.active().unwrap(); + let (restored, undo) = (source.doc.clone(), source.history.undo.len()); + frame(&mut app, vec![]); + let after = app.session.active().unwrap(); + assert!(after.doc == restored, "the old path OK reached restored artwork"); + assert_eq!(after.history.undo.len(), undo); + let held = app.dialogs().unwrap().with(|host| host.held_state(dialog)); + let Some(HeldOk::Refused(message)) = held else { panic!("expected a held refusal") }; + assert_eq!(message.as_str(), "The document was reverted. Reopen this dialog to continue."); + + assert!(cancel(&mut app)); + show_path_options(&mut app, op); + set(&mut app, "preview", json!(true)); + frame(&mut app, vec![]); + assert!(app.session.in_interaction(), "a new opening can preview the restored paths"); + assert!(confirm(&mut app)); + let after = app.session.active().unwrap(); + assert!(after.doc != restored, "the fresh OK applies the preview"); + assert_eq!(after.history.undo.len(), undo + 1); + } + } + #[test] fn simplify_options_skip_the_other_drawings_artwork() { for from_slider in [false, true] { From 6e40ce3c7e4f1c4fee09fea7d5eee6a8d1c5f583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:50:54 -0800 Subject: [PATCH 042/106] Keep CJK settings with the opening text selection --- crates/ui-egui/src/dialogs/tate_chu_yoko.rs | 29 ++++++++++++- crates/ui-egui/src/dialogs/warichu.rs | 27 ++++++++++++- crates/ui-egui/src/panels/character.rs | 45 +++++++++++++++++++-- 3 files changed, 96 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs index e2f32ef4fd..34eb857f53 100644 --- a/crates/ui-egui/src/dialogs/tate_chu_yoko.rs +++ b/crates/ui-egui/src/dialogs/tate_chu_yoko.rs @@ -39,6 +39,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Tate-chu-yoko Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let target = crate::panels::character::format_target_kept(app)?; let active = app.session.active().ok_or("no document")?; let (document, reverts) = (active.uid, active.reverts); let (up, right) = crate::panels::character::shared_tcy_offsets(app); @@ -65,7 +66,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if active.reverts != reverts { return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } - crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) + crate::panels::character::run_format_at_target(app, Value::Object(p), &target).map(|_| ()) }) .ok_or("no window")?; Ok(Value::Null) @@ -206,6 +207,32 @@ mod tests { assert_eq!(offsets(&app, id), [(0.0, 6.0), (0.0, 0.0)]); } + #[test] + fn tate_chu_yoko_approval_keeps_its_opening_text_target() { + let (mut app, id) = app(); + let select = |app: &mut VectorcraftApp, anchor, caret| { + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": anchor, "caret": caret})); + }; + app.session.select_tool("type", Default::default()).unwrap(); + select(&mut app, 0, 2); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.tateChuYokoSettings", json!({})).unwrap(); + driver::set(&mut app, "tcyLeftRight", json!(6)); + + select(&mut app, 2, 4); + assert_eq!(crate::panels::character::text_editing(&app), Some((NodeId(id), 2, 4))); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(offsets(&app, id), [(0.0, 0.0)], "the new text range keeps its formatting"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + + select(&mut app, 0, 2); + assert!(crate::dialogs::tests::confirm(&mut app)); + assert_eq!(offsets(&app, id), [(0.0, 6.0), (0.0, 0.0)]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + #[test] fn tate_chu_yoko_approval_refuses_to_change_restored_text() { let (mut app, id) = app(); diff --git a/crates/ui-egui/src/dialogs/warichu.rs b/crates/ui-egui/src/dialogs/warichu.rs index c297df5160..2001db0934 100644 --- a/crates/ui-egui/src/dialogs/warichu.rs +++ b/crates/ui-egui/src/dialogs/warichu.rs @@ -69,6 +69,7 @@ fn rows(lengths: LengthUnits) -> Vec { /// Open Warichu Settings on the characters the Character panel acts on. pub fn open(app: &mut VectorcraftApp) -> Result { crate::panels::character::text_style(app).ok_or("select some type first")?; + let target = crate::panels::character::format_target_kept(app)?; let active = app.session.active().ok_or("no document")?; let (document, reverts) = (active.uid, active.reverts); let shared = crate::panels::character::shared_warichu(app); @@ -96,7 +97,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { if active.reverts != reverts { return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } - crate::panels::character::run_format(app, Value::Object(p)).map(|_| ()) + crate::panels::character::run_format_at_target(app, Value::Object(p), &target).map(|_| ()) }) .ok_or("no window")?; Ok(Value::Null) @@ -342,6 +343,30 @@ mod tests { assert_eq!(settings(&app, id), [(false, 2, 0.0, 50.0, WarichuAlign::JustifyAll), (false, 2, 0.0, 50.0, WarichuAlign::Auto)]); } + #[test] + fn warichu_approval_keeps_its_opening_text_target() { + let (mut app, first) = app(); + let second = app.run("text.create", json!({"x": 12, "y": 100, "text": "second"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [first]})).unwrap(); + let before = settings(&app, second); + let undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.warichuSettings", json!({})).unwrap(); + driver::set(&mut app, "warichuLines", json!(4)); + + app.run("select.set", json!({"ids": [second]})).unwrap(); + let dialog = craft::ui::dialog::dialog_id(KIND); + crate::tests::picks::answer_dialog(&mut app, dialog, &[], true); + assert_eq!(settings(&app, second), before, "the second text object keeps its formatting"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_)))); + + app.run("select.set", json!({"ids": [first]})).unwrap(); + assert!(crate::dialogs::tests::confirm(&mut app)); + assert_eq!(settings(&app, first), [(false, 4, 0.0, 50.0, WarichuAlign::Auto)]); + assert_eq!(settings(&app, second), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + #[test] fn warichu_approval_refuses_to_change_restored_text() { let (mut app, id) = app(); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 6804b53c4d..bfcb770b7e 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -33,7 +33,7 @@ use egui::Ui; use serde_json::{Value, json}; use vectorcraft_doc::setup::{LANGUAGES, char_language_name}; use vectorcraft_doc::text::TypeAntiAlias; -use vectorcraft_doc::{CharStyle, NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, SymbolPart}; use vectorcraft_engine::DocState; use vectorcraft_tools::{Mods, ToolKey}; @@ -289,8 +289,13 @@ pub(crate) fn format(app: &mut VectorcraftApp, p: Value) { /// [`format`] that returns the command's result: `text.setRangeStyle` on the range the Type tool /// has selected (the whole text when nothing is selected) while it edits text, else /// `text.setFormat` on the selected stories ([`selected_stories`]). -pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result { - let Some((id, a, b)) = text_editing_kept(app)? else { +pub(crate) fn run_format(app: &mut VectorcraftApp, p: Value) -> Result { + let editing = text_editing_kept(app)?; + run_format_after_typing(app, p, editing) +} + +fn run_format_after_typing(app: &mut VectorcraftApp, mut p: Value, editing: Option<(NodeId, usize, usize)>) -> Result { + let Some((id, a, b)) = editing else { target_selected_stories(app, &mut p); return app.run("text.setFormat", p); }; @@ -305,6 +310,40 @@ pub(crate) fn run_format(app: &mut VectorcraftApp, mut p: Value) -> Result, Option), + Story(Vec), + Range(NodeId, usize, usize), +} + +fn format_target(app: &VectorcraftApp, editing: Option<(NodeId, usize, usize)>) -> FormatTarget { + if let Some((id, start, end)) = editing { + return text_story(app).map_or(FormatTarget::Range(id, start, end), FormatTarget::Story); + } + let mut ids = selected_stories(app); + ids.sort_unstable_by_key(|id| id.0); + let part = app.session.active().and_then(|st| st.selection.symbol_part.clone()); + FormatTarget::Objects(ids, part) +} + +pub(crate) fn format_target_kept(app: &mut VectorcraftApp) -> Result { + let editing = text_editing_kept(app)?; + Ok(format_target(app, editing)) +} + +/// Apply a settings dialog to its opening text only. Compare before keeping typing so a +/// refused confirmation on different text does not commit that text's in-progress edit. +pub(crate) fn run_format_at_target(app: &mut VectorcraftApp, p: Value, target: &FormatTarget) -> Result { + let check = |current: FormatTarget| { + if ¤t != target { Err(tl!("The selected text changed. Restore the selection to continue.").to_owned()) } else { Ok(()) } + }; + check(format_target(app, text_editing(app)))?; + let editing = text_editing_kept(app)?; + check(format_target(app, editing))?; + run_format_after_typing(app, p, editing) +} + /// The Tate-chu-yoko Settings Up/Down and Left/Right the characters the panels act on share, in /// document points; `None` where they differ, or with no type. pub(crate) fn shared_tcy_offsets(app: &VectorcraftApp) -> (Option, Option) { From 7e9d9979fd7a4532036317205875dfafef378ec0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 22:09:34 -0800 Subject: [PATCH 043/106] Restore Action selector drafts after a canceled choice --- crates/ui-egui/src/dialogs/action_new.rs | 111 ++++++++++++++++++++++- crates/ui-egui/src/dialogs/actions.rs | 8 +- 2 files changed, 110 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs index 58980c099c..dda71b4984 100644 --- a/crates/ui-egui/src/dialogs/action_new.rs +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -138,9 +138,7 @@ impl StackDialog for NewActionDialog { TextField::new(label("Name:"), Bind::bound(&mut fields.name)).show(ui); }); Field::new(label("Action Set:")).show(ui, |ui, _| { - if let Some(set) = Select::new(label("Action Set:"), Bind::given(fields.set), &sets).show(ui).value().copied() { - fields.set = set; - } + Select::new(label("Action Set:"), Bind::bound(&mut fields.set), &sets).show(ui); }); key_and_color(ui, &mut fields.options); automatic_align_options(ui, &mut fields.options); @@ -164,3 +162,110 @@ impl StackDialog for NewActionDialog { self.form.set_field(ctx, field, value) } } + +#[cfg(test)] +mod tests { + use craft::automation::actions::{ActionColor, ActionList}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use super::*; + use crate::dialogs::action_set_options::SetOptionsDialog; + use crate::panels::actions::{FUNCTION_KEYS, STOP_RECORDING, model}; + use crate::tests::panel_harness::Panel; + + fn panel() -> Panel { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.actions = ActionList::new(); + app.ui.actions.new_set("First").unwrap(); + app.ui.actions.new_set("Second").unwrap(); + app.ui.action_set = Some("First".into()); + Panel::new(app, crate::tests::picks::dialogs) + } + + fn fields(panel: &Panel) -> NewActionFields { + panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().form.values.clone()) + } + + fn popup(panel: &mut Panel, name: &str) { + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + } + + #[test] + fn cancelled_choices_keep_the_new_action_destination_key_and_color() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + let original = fields(&panel); + for name in ["Action Set", "Function Key", "Color"] { + popup(&mut panel, name); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + assert!(panel.enabled("Record")); + panel.click("Record"); + panel.frame(); + panel.frame(); + { + let app = panel.app(); + assert!(app.ui.recording.is_some()); + assert_eq!(model::members(&app.ui.actions, "First").len(), 1); + assert!(model::members(&app.ui.actions, "Second").is_empty()); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.name, original.name); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + panel.app().run(STOP_RECORDING, json!({})).unwrap(); + crate::dialogs::action_set_options::open_action(&mut panel.app(), 0, 0); + panel.frame(); + let options = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().json_fields().unwrap()); + let original = options(&panel); + for name in ["Function Key", "Color"] { + popup(&mut panel, name); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(options(&panel), original, "Action Options restores {name}"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, ActionColor::None); + assert!(model::function_key(action).is_none()); + } + + #[test] + fn committed_choices_are_used_by_record() { + let mut panel = panel(); + open(&mut panel.app()).unwrap(); + panel.frame(); + popup(&mut panel, "Action Set"); + panel.key(Key::Enter, Modifiers::NONE); + popup(&mut panel, "Color"); + panel.key(Key::Enter, Modifiers::NONE); + let key = (1..=FUNCTION_KEYS).find(|&key| key_reason(&ActionOptions { key, ..Default::default() }).is_none()).unwrap(); + panel.click_role("Function Key", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + for _ in 0..key { + panel.key(Key::ArrowDown, Modifiers::NONE); + } + panel.key(Key::Enter, Modifiers::NONE); + let chosen = fields(&panel); + assert_eq!((chosen.set, chosen.options.key, chosen.options.color), (1, key, ActionColor::ALL[1])); + panel.click("Record"); + panel.frame(); + panel.frame(); + let app = panel.app(); + assert!(model::members(&app.ui.actions, "First").is_empty()); + assert_eq!(model::members(&app.ui.actions, "Second").len(), 1); + let action = app.ui.actions.actions().first().unwrap(); + assert_eq!(action.color, chosen.options.color); + assert_eq!(model::function_key(action).map(|key| key.key), Some(key)); + assert!(app.ui.recording.is_some()); + } +} diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 8a6de85fe4..10a0647fc9 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -243,9 +243,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let modifier = if crate::keymap::platform() == craft::keymap::Platform::Mac { "⌘" } else { "Ctrl" }; Field::new(label("Function Key:")).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { - if let Some(key) = Select::new(label("Function Key:"), Bind::given(options.key), &keys).show(ui).value().copied() { - options.key = key; - } + Select::new(label("Function Key:"), Bind::bound(&mut options.key), &keys).show(ui); Checkbox::new(Bind::bound(&mut options.cmd)).label(modifier).show(ui); Checkbox::new(Bind::bound(&mut options.shift)).label(label("Shift")).show(ui); }); @@ -255,9 +253,7 @@ pub(crate) fn key_and_color(ui: &mut Ui, options: &mut ActionOptions) { let colors: Vec> = ActionColor::ALL.into_iter().map(|color| Entry::new(color, label_color_label(color.label_color(), &words))).collect(); Field::new(label("Color:")).show(ui, |ui, _| { - if let Some(color) = Select::new(label("Color:"), Bind::given(options.color), &colors).show(ui).value().copied() { - options.color = color; - } + Select::new(label("Color:"), Bind::bound(&mut options.color), &colors).show(ui); }); } From ee446c8dcf5b4c88a6d7ba8442aaa5830ca45e22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 22:09:51 -0800 Subject: [PATCH 044/106] Keep symbol instance effects from its part selection --- .../panels/properties/appearance_section.rs | 13 ++++++---- crates/ui-egui/src/panels/properties/tests.rs | 26 +++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/appearance_section.rs b/crates/ui-egui/src/panels/properties/appearance_section.rs index b3266b032d..bd0c4d68b2 100644 --- a/crates/ui-egui/src/panels/properties/appearance_section.rs +++ b/crates/ui-egui/src/panels/properties/appearance_section.rs @@ -61,6 +61,7 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { /// The fx button that opens the effect menu, as the Appearance panel's does, the Delete icon and /// the icon that shows the Appearance panel. fn effects_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { + let editable = app.session.active().is_some_and(|st| st.selection.symbol_part.is_none()); // The effects of one selected object: the fill's and stroke's as well as its own. let effects: Vec<(Option, usize, &str)> = if panels::selection_len(app) == 1 { let own = n.appearance.effects.iter().enumerate().map(|(k, e)| (None, k, e.id.as_str())); @@ -71,9 +72,11 @@ fn effects_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { vec![] }; Row::new().show(ui, |ui, _| { - let fx = Button::new("fx").tooltip(tl!("Add New Effect")).show(ui); - Menu::new(tl!("Add New Effect")).opened_by(&fx.response, Trigger::Click).show(ui, |ui, _| appearance::fx_menu(app, ui)); - effect_delete(app, ui, n.id, &effects); + let fx = Button::new("fx").tooltip(tl!("Add New Effect")).enabled(editable).show(ui); + if editable { + Menu::new(tl!("Add New Effect")).opened_by(&fx.response, Trigger::Click).show(ui, |ui, _| appearance::fx_menu(app, ui)); + } + effect_delete(app, ui, n.id, &effects, editable); panel_button("ellipsis", "appearance", tl!("Appearance panel")).show(ui); }); } @@ -82,12 +85,12 @@ fn effects_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { /// (): /// with one effect applied, its name and an icon that removes it (`effect.remove`); with several, /// the icon shows the Appearance panel to remove them there. Nothing without effects. -fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[(Option, usize, &str)]) { +fn effect_delete(app: &mut VectorcraftApp, ui: &mut Ui, id: NodeId, effects: &[(Option, usize, &str)], editable: bool) { match effects { [] => {} [(item, k, effect)] => { Text::new(appearance::shown_effect_label(effect)).elide(Elide::End).show(ui); - if IconButton::new(IconId::new("trash-2")).label(tl!("Remove Effect")).show(ui).clicked() { + if IconButton::new(IconId::new("trash-2")).label(tl!("Remove Effect")).enabled(editable).show(ui).clicked() { app.run("effect.remove", json!({"ids": [id.0], "item": item, "index": k})).ok(); } } diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index faeb91c166..bb50b38a58 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1300,6 +1300,32 @@ fn one_effect_has_a_delete_icon_in_appearance() { assert!(!panel.shows(&name), "two objects"); } +#[test] +fn properties_remove_effect_requires_the_whole_symbol_instance() { + let mut app = new_app(); + let left = rect(&mut app, 20.0, 20.0, 20.0, 20.0); + let right = rect(&mut app, 60.0, 20.0, 20.0, 20.0); + let instance = app.run("symbol.new", json!({"type": "dynamic", "ids": [left, right]})).unwrap()["id"].clone(); + let node = vectorcraft_doc::NodeId(instance.as_u64().unwrap()); + app.run("effect.apply", json!({"ids": [instance], "effect": "stylize.dropShadow"})).unwrap(); + app.run("symbol.instance.selectPart", json!({"id": instance, "path": [0]})).unwrap(); + let mut panel = Panel::new(app, show); + let effects = |panel: &Panel| panel.app().session.active().unwrap().doc.node(node).unwrap().appearance.effects.len(); + let depth = undo_depth(&panel.app()); + + assert_eq!(effects(&panel), 1); + panel.click("Remove Effect"); + assert_eq!((effects(&panel), undo_depth(&panel.app())), (1, depth), "a part cannot remove the whole instance’s effect"); + assert!(!panel.enabled("Remove Effect")); + assert!(panel.shows("Appearance panel"), "Appearance remains available for inspection"); + + panel.app().run("select.set", json!({"ids": [instance]})).unwrap(); + panel.frame(); + assert!(panel.enabled("Remove Effect")); + panel.click("Remove Effect"); + assert_eq!((effects(&panel), undo_depth(&panel.app())), (0, depth + 1)); +} + /// A rectangle at 100, 100, 100 × 60 pt, selected, with `then` run on it, and the Transform /// panel's reference point on the top-left square. fn reference_setup(then: &[(&str, Value)]) -> VectorcraftApp { From 4940fddf0b988937ee9d317463c0cfbc3edc8326 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 21:55:02 -0800 Subject: [PATCH 045/106] Keep instance mask controls off a selected symbol part --- crates/ui-egui/src/panels/tests_maskview.rs | 37 +++++++++++++++++++++ crates/ui-egui/src/panels/transparency.rs | 6 ++-- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_maskview.rs b/crates/ui-egui/src/panels/tests_maskview.rs index c6479f1d23..43c3f27de8 100644 --- a/crates/ui-egui/src/panels/tests_maskview.rs +++ b/crates/ui-egui/src/panels/tests_maskview.rs @@ -33,6 +33,43 @@ fn click_mask(panel: &mut Panel, mods: Modifiers) { panel.click_part(ROW, ThumbTarget::Extra(0).part(), mods); } +#[test] +fn the_mask_thumbnail_only_edits_the_whole_symbol_instance() { + for mods in [Modifiers::ALT, Modifiers::NONE] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let rect = |app: &mut VectorcraftApp, x| run(app, "shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20}))["id"].clone(); + let left = rect(&mut app, 10); + let right = rect(&mut app, 50); + let symbol = run(&mut app, "symbol.new", json!({"name": "Pair", "type": "dynamic", "ids": [left, right]}))["id"].clone(); + let mask = rect(&mut app, 20); + run(&mut app, "transparency.makeOpacityMask", json!({"ids": [symbol, mask]})); + run(&mut app, "symbol.instance.selectPart", json!({"id": symbol, "path": [0]})); + let mut panel = Panel::new(app, transparency::show); + let undo = panel.app().session.active().unwrap().history.undo.len(); + + click_mask(&mut panel, mods); + { + let app = panel.app(); + let st = app.session.active().unwrap(); + assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "the part cannot enter the instance mask with {mods:?}"); + assert_eq!(st.history.undo.len(), undo); + assert!(st.selection.symbol_part.is_some()); + } + for label in ["Release", "Clip", "Invert Mask", "Isolate Blending", "Knockout Group", "Opacity & Mask Define Knockout Shape"] { + assert!(!panel.enabled(label), "{label} applies to the whole instance"); + } + assert!(panel.enabled("Opacity") && panel.enabled("Blend Mode")); + + run(&mut panel.app(), "select.set", json!({"ids": [symbol]})); + click_mask(&mut panel, mods); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.mask_edit.map(|edit| edit.object.0), symbol.as_u64()); + assert_eq!(st.shown_mask().map(|id| id.0), mods.alt.then(|| symbol.as_u64().unwrap())); + } +} + /// In pattern editing mode a click or an Alt-click on the mask thumbnail of a masked object in the /// tile does not edit the mask, and the status bar says to finish editing the pattern first. Make /// Mask is off for one object, which it would take into mask editing. After Done a click edits the diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 3f6e38014b..72a2223707 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -78,10 +78,10 @@ pub(crate) fn state(app: &mut VectorcraftApp) -> (TransparencyInfo, Option bool { - editing || app.session.appearance_item().is_none() + editing || (app.session.appearance_item().is_none() && !app.session.active().is_some_and(|st| st.selection.symbol_part.is_some())) } /// The key of one mask-row thumbnail: the masked object, the background it sits on and which picture it is. From 40aadc491c1a2cd9b6903e827637820c23c908a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 22:15:16 -0800 Subject: [PATCH 046/106] Keep selected Relink instances after a canceled scope choice --- crates/ui-egui/src/dialogs/relink.rs | 64 ++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index ac99cf9b0c..7220750be8 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -256,9 +256,7 @@ impl StackDialog for RelinkDialog { } }); Field::new(tl!("Replace:")).show(ui, |ui, _| { - if let Some(next) = Select::new(tl!("Replace:"), Bind::given(scope.clone()), &entries).show(ui).value().cloned() { - *scope = next; - } + Select::new(tl!("Replace:"), Bind::bound(scope), &entries).show(ui); }); true }); @@ -453,6 +451,66 @@ mod tests { check_relink_stays_in_opening_drawing(true); } + #[test] + fn replace_popup_cancel_preserves_selected_instances_and_enter_relinks_all() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + for commit in [false, true] { + let (mut app, dir) = setup(if commit { "popup-commit" } else { "popup-cancel" }, &["photo.png", "other.png"]); + let _scratch = Scratch(dir.clone()); + let a = place(&mut app, &dir.join("photo.png")); + let b = place(&mut app, &dir.join("photo.png")); + let c = place(&mut app, &dir.join("other.png")); + let picker = scripted(&mut app); + let chosen = new_file(&dir, "replacement.png"); + let original_path = dir.join("photo.png").to_string_lossy().into_owned(); + let other_path = link_path(&app, c); + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(900.0, 700.0)); + panel.app().run("ui.relinkDialog", json!({"ids": [a]})).unwrap(); + panel.frame(); + let before = fields(&panel.app()); + panel.click_role("Replace:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(fields(&panel.app())["scope"], "all", "the open popup previews All Instances"); + panel.key(if commit { Key::Enter } else { Key::Escape }, Modifiers::NONE); + assert_eq!(fields(&panel.app())["scope"], if commit { "all" } else { "selected" }); + if !commit { + assert_eq!(fields(&panel.app()), before, "Escape preserves all pending Relink fields"); + } + assert_eq!(panel.app().session.active().unwrap().doc, original); + assert_eq!(panel.app().session.active().unwrap().revision, revision); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + panel.click("Relink…"); + assert_eq!(picker.requests().len(), 1); + picker.answer(&[&chosen]); + panel.frame(); + panel.frame(); + assert!(open_dialogs(&panel.app()).is_empty()); + { + let app = panel.app(); + assert_eq!(link_path(&app, a), chosen); + assert_eq!(link_path(&app, b), if commit { chosen.clone() } else { original_path.clone() }); + assert_eq!(link_path(&app, c), other_path); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + } + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + } + #[test] fn relink_opens_with_the_replace_choice_and_all_instances_relinks_every_copy() { let (mut app, dir) = setup("all", &["photo.png", "other.png"]); From 3498066d9347c132d86fa54832f8d43f1a99a50d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 22:15:17 -0800 Subject: [PATCH 047/106] Keep Artboard Options geometry drafts local until commit --- .../ui-egui/src/dialogs/artboard_options.rs | 113 +++++++++++++++++- 1 file changed, 111 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 1e3013b69a..8cb212aebb 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -351,7 +351,8 @@ fn length_row(ui: &mut Ui, label: impl Into