diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..ff70d04bdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] @@ -27,9 +27,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index ae5b2d5804..5faad39835 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -140,6 +140,12 @@ fn units_choose_the_default_scale() { assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); } + // Miles and kilometers have no unit of their own, so they read as millimeters at their scale. + for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] { + let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap(); + assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); + assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); + } let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document; assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect); let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap(); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 75a5fdc2a5..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -197,6 +197,11 @@ mod tests { assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); + // The labels are written here and the ids come from the framework: a few shown labels read + // back as their rules. + for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] { + assert_eq!(parse(label(h)), Some(h), "{}", label(h)); + } } #[test] diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 31b9950296..083cfa65d9 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -174,7 +174,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -975,7 +975,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result { add_look(s, "Pen", path_kind(path, None), look, None) } +/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one. +fn text_parent(s: &Session, p: &Value) -> Result> { + const C: &str = "text.create"; + let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + Ok(Some(parent)) +} + +/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { + let id = s.edit("Type", |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, kind); + NewArt::plain(Appearance::default()).apply(d, &mut n); + super::object::align_new_object(d, &mut n); + n.bbox_angle = bbox_angle; + d.insert(Some(parent), usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + fn text_create(s: &mut Session, p: &Value) -> Result { + let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; super::paint::check_keep_model(p, "text.create")?; @@ -1012,8 +1043,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; + let made = match parent { + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, + None => { + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? + } + }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 469ff2721e..3a52534ac8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1017,13 +1017,22 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // The clipping path stays at the bottom of its clip group or clipping layer. + let from = d.parent_of(id); + let clips = |p: Option| p.and_then(|p| d.node(p)).filter(|p| p.clips()); + let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id); + if is_mask && (parent != from || index != 0) { + return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first")); + } + let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index }; // An empty compound path takes the paint of the first path that goes into it: the path's own, // or the paint of the compound path it leaves, which is what painted it. let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); let into = compound.map(|c| c.id); - let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned); + // A compound path that is pixel-aligned already snaps the path it takes, too. + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned) || compound.is_some_and(|c| c.extras().pixel_aligned); // A path that leaves a compound path for a layer or a group takes the compound path's paint and // pixel alignment, as Release Compound Path gives them to its paths. let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); @@ -1032,7 +1041,6 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; - let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2ef29a124f..b781bfe7aa 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -54,7 +54,7 @@ //! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an //! error. A run that fails leaves the tool as it was. //! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of -//! the paths in the object; a clipping group counts its clipping path only. +//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's. //! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), //! in view-number order, and none without one. View objects keep their window's identity when //! windows are renumbered. The screen mode is the app's: @@ -496,7 +496,7 @@ fn point_method(link: &Link, f: Member) -> HostMember { pub(super) type Described = (String, HostMember, MemberInfo); /// A property's or a method's result's type for `reflect`. -fn typed(data_type: &str) -> MemberInfo { +pub(super) fn typed(data_type: &str) -> MemberInfo { MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } } @@ -507,7 +507,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, layer, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point, text range or `GroupItems` collection +/// `this` is still there. /// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and /// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { @@ -532,6 +533,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "TextRange" => { text::check_range(&h, arg(&a, 0))?; } + "GroupItems" => { + layers::check_groups(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -2391,13 +2395,17 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) + // A clipping layer emptied of its art releases its mask, so art added later is not made its + // clipping path. + let released = masks_cleared_by(&st.doc, &ids); + let tracing = release_makes_tracing(&st.doc, &released, &ids); + (ids, refused, on_locked, released, tracing) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2407,8 +2415,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(NOT_A_TRACING.into())); + } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } Ok(Data::Undefined) } @@ -2696,26 +2707,39 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } -/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an -/// object with nothing in it. +/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths +/// in the item. fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, true)?; - let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); - match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) { - Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), - None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), - } + // An object with nothing in it reads zeros, as its other bounds do. + let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) }; + // Each object and anchor the walk visits is charged, so reading a large group's bounds again + // and again counts against the run. + let mut steps = 0u64; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps))); + h.charge_call(steps)?; + Ok(f.bounds(h.dom.coords.get(), r)) } -/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown -/// paths in its children (a clip group's from its clipping path). -fn handle_bounds(n: &crate::doc::Node) -> Option { - match &n.kind { - NodeKind::Path { path, .. } => path.control_bounds(), - NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), - _ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))), +/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and +/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as +/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping +/// path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { + *steps += 1; + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return r; } + for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + *steps += 1; + r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); + } + let children = n.children().map_or(&[][..], Vec::as_slice); + let children = if n.clips() { &children[..children.len().min(1)] } else { children }; + for c in children { + r = take_in_handles(c, r, steps); + } + r } fn item_position(h: &Host, a: &[Data]) -> Answer { @@ -2888,11 +2912,55 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { return Err(HostError::Error(NOT_A_TRACING.into())); } + let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); + // A clip group named as a tracing, released with an image left first, would become one too. + if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + let params = json!({"ids": [item.id.0], "keepEmpty": true}); + paths::see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, ¶ms))); + h.dom.editing.set(kept); + r?; Ok(Data::Undefined) } +/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping +/// path releases its mask, so the object above it does not become the clipping path. +pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|i| { + let p = d.parent_of(*i)?; + let n = d.node(p)?; + (n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p) + }) + .collect() +} + +/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups +/// an ordinary group named as a tracing with an image first in it, which would make it a tracing. +pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool { + if released.is_empty() { + return false; + } + let removed: std::collections::HashSet = removed.iter().copied().collect(); + released.iter().filter_map(|g| d.node(*g)).any(|g| { + matches!(g.kind, NodeKind::Group { .. }) + && g.name.as_deref() == Some(crate::cmd::TRACE_NAME) + && g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }) +} + +/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. +pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { + for g in released { + command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; + } + command(h, "edit.clear", params) +} + /// The error of `remove()` and `removeAll()` for an object on a locked artboard. pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; @@ -3041,6 +3109,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> } } +/// Whether deleting every object in `removed` together would leave one of their parents, an +/// ordinary group named as a tracing, with an image first in it, which would make it a tracing. +pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool { + let going: std::collections::HashSet = removed.iter().copied().collect(); + let mut parents: Vec = removed.iter().filter_map(|i| d.parent_of(*i)).collect(); + parents.sort_unstable_by_key(|p| p.0); + parents.dedup(); + parents + .into_iter() + .filter(|p| named_as_tracing(d, *p)) + .any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { @@ -3056,6 +3137,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); } let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; + // The clipping path itself, put back where it is, stays the clipping path. + let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0); let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -3067,11 +3150,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul { i -= 1; } - if how == Placement::Above { i + 1 } else { i } + let at = if how == Placement::Above { i + 1 } else { i }; + // A place behind a clipping path is refused; an object put into the clip group + // itself goes directly above the clipping path. + if clips && at == 0 && !mask_stays { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } + at } (_, None) => count, }; - let at = if clips { at.max(1) } else { at }; + // Any other place for the clipping path is left to `node.move`, which refuses it. + let stays = mask_stays && at == 0; + let at = if clips && !stays { at.max(1) } else { at }; // The index `node.move` puts the object at: art stays below the ruler guides. // This is `Node::insert_index` on the parent's children without the object, read in place // so that no list of them is copied. @@ -3230,7 +3321,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } /// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. -fn named_text(class: &str, name: Answer) -> Answer { +pub(super) fn named_text(class: &str, name: Answer) -> Answer { match name? { Data::String(n) => Ok(text(format!("[{class} {n}]"))), _ => Ok(text(format!("[{class} ]"))), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..3f40ad4c11 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -68,6 +68,8 @@ enum Kind { Compound, /// Paths (`PathItem`). Path, + /// Type (`TextFrame`), whose collection's other members are in `text.rs`. + Text, } impl Kind { @@ -77,6 +79,7 @@ impl Kind { Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", Kind::Path => "PathItems", + Kind::Text => "TextFrames", } } @@ -86,6 +89,7 @@ impl Kind { Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), Kind::Path => typename(n) == Some("PathItem"), + Kind::Text => typename(n) == Some("TextFrame"), } } } @@ -245,7 +249,9 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v})) + // The number the getter reports, or one that stores as the opacity the layer has, leaves the + // layer as it is. + set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { @@ -289,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let parent = st.doc.parent_of(id); - let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); - h.charge_call(count as u64)?; - let list = layer_list(&st.doc, parent); + let list = layers_listed(h, st, st.doc.parent_of(id))?; h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -642,6 +646,10 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("a document needs at least one layer".into())); } let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; + // `layer.delete` takes at most this many rows; more is refused before anything is deleted. + if ids.len() > crate::cmd::layer::MAX_ROWS { + return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -760,8 +768,17 @@ fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { }; } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) { + Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))), + // The text of a number that is not an array index is looked up as a name. + None => with_doc(h, doc, |_, st| { + let ids = art_list(h, st, kind, c)?; + h.charge_call(ids.len() as u64)?; + let name = vectorcraft_js::number_to_string(*n); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id))) + }), + } } fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { @@ -778,6 +795,11 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), + // A number is a position only. A stale collection throws its stale error first. + Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + art_scope(h, arg(a, 0), kind.class())?; + Err(HostError::Error(NOT_FOUND.into())) + } Data::Number(_) => match art_at(h, a, kind)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -833,6 +855,10 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" ))); } + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } @@ -982,6 +1008,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +fn held_text(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Text) +} + +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + art_scope(h, d, Kind::Text.class()) +} + +/// The type objects directly in `container`, topmost first. +pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result>> { + art_list(h, st, Kind::Text, Some(container)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -1035,8 +1075,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), @@ -1317,9 +1358,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer { Ok(text("[Layers]")) } fn groups_to_string(h: &Host, a: &[Data]) -> Answer { - art_scope(h, arg(a, 0), Kind::Group.class())?; + check_groups(h, arg(a, 0))?; Ok(text("[GroupItems]")) } +/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone. +pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> { + art_scope(h, d, Kind::Group.class()).map(|_| ()) +} fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { art_scope(h, arg(a, 0), Kind::Compound.class())?; Ok(text("[CompoundPathItems]")) @@ -1511,17 +1556,17 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("textFrames", get(l, held_text), listed("TextFrames")), ("zOrderPosition", get(l, layer_z_position), typed("number")), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), ("isIsolated", get(l, layer_is_isolated), typed("boolean")), - ("move", method(l, layer_move), typed("Layer")), + ("move", method(l, layer_move), returns("Layer", &[("relativeObject", "*"), ("insertionLocation", "ElementPlacement")])), ("remove", method(l, layer_remove), returns("undefined", &[])), - ("zOrder", method(l, layer_z_order), typed("undefined")), + ("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, layer_to_string), returns("string", &[])), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index ebfe900ee4..b14b065c84 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1,4 +1,4 @@ -//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its //! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , @@ -8,6 +8,9 @@ //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`, +//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden +//! or locked layer or group throws. //! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so //! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves //! out to the whole character. One item of `characters` is one code point. @@ -63,6 +66,10 @@ pub const STALE_RANGE: &str = "Stale text range"; /// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit /// is stale. const MAX_EDITS: usize = 100_000; +/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of +/// the other frames are given up; their text, generations and edits stay, and each frame's tables +/// are made again when it is next read. +const INDEX_BUDGET: usize = 64 << 20; /// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. pub(super) struct Index { @@ -106,6 +113,22 @@ impl Index { Self { text, chars, bytes, words, paras } } + /// The text alone, without its offset tables, for a frame whose tables were given up under + /// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read. + fn bare(text: String) -> Self { + Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() } + } + + fn is_bare(&self) -> bool { + self.chars.is_empty() + } + + /// The bytes the offset tables hold. + fn table_bytes(&self) -> usize { + let pairs = self.words.capacity() + self.paras.capacity(); + (self.chars.capacity() + self.bytes.capacity()) * size_of::() + pairs * size_of::<(usize, usize)>() + } + fn len(&self) -> usize { self.chars.last().copied().unwrap_or(0) } @@ -206,10 +229,32 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]). + table_bytes: Cell, /// The styles the run's style objects name. styles: styles::StyleState, } +/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within +/// [`INDEX_BUDGET`], giving up the tables of other frames first. +fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) { + let mut total = state.table_bytes.get() + index.table_bytes(); + if let Some(l) = frames.get_mut(&key) { + total -= l.index.table_bytes(); + l.index = Rc::new(index); + } + for (k, l) in frames.iter_mut() { + if total <= INDEX_BUDGET { + break; + } + if *k != key && !l.index.is_bare() { + total -= l.index.table_bytes(); + l.index = Rc::new(Index::bare(l.index.text.clone())); + } + } + state.table_bytes.set(total); +} + fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { match &st.doc.node(id)?.kind { NodeKind::Text(t) => Some(t), @@ -235,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc {} + let fresh = match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None, Some(l) => { - if l.reverts != st.reverts || !same_text(t, &l.index.text) { + let changed = l.reverts != st.reverts || !same_text(t, &l.index.text); + if changed { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); - l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + changed.then(|| t.plain_text()) } None => { let l = Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, - index: Rc::new(Index::new(t.plain_text())), + index: Rc::new(Index::bare(String::new())), stamp: 0, floor: 0, edits: VecDeque::new(), }; frames.insert(key, l); + Some(t.plain_text()) } + }; + // Tables given up under the budget are made again from the text the log keeps. + let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone())); + if let Some(text) = fresh { + set_index(&h.dom.text, &mut frames, key, Index::new(text)); } let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok((l.index.clone(), l.stamp)) @@ -348,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser l.floor = l.stamp; l.edits.clear(); } - l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now)); Ok(()) }) } @@ -776,7 +828,11 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { } else if handle_of(rel, "TextRange").is_some() { span_of(h, rel, &["TextRange"])? } else { - return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into())); + // A range of a removed frame keeps its own error. + span_of(h, rel, &["TextRange"]).map_err(|e| match e { + HostError::Error(m) if m == STALE_RANGE => HostError::Error(m), + _ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()), + })? }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); @@ -1312,32 +1368,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result>, Ho Ok(ids) } +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + super::layers::text_scope(h, arg(a, 0)) +} + fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "TextFrames") + Ok(frames_scope(h, a)?.0) +} + +/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those +/// directly in a layer or group, topmost first. +fn listed(h: &Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + match container { + None => frame_ids(h, st), + Some(c) => super::layers::text_list(h, st, c), + } } fn frames_length(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64))) + let (doc, c) = frames_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(doc_ref(h, doc.uid)) + let (doc, c) = frames_scope(h, a)?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } fn frames_at(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st)?; + let ids = listed(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1365,29 +1435,40 @@ fn vertical_of(d: &Data) -> std::result::Result { } } -/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. -fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on +/// top of the contents of `container` when there is one. +fn point_text(h: &Host, (doc, container): (Doc, Option), anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let (_, r) = - on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical}); + if let Some(c) = container { + check_open(h, doc, c)?; + if let Some(o) = params.as_object_mut() { + o.insert("parent".into(), json!(c.0)); + } + } + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", ¶ms))?; new_ref(h, doc, result_id(&r)) } +/// The error for a layer or group that takes no new type. +const SHUT_CONTAINER: &str = "the layer or group is hidden or locked"; + /// `add()`: empty point type at the origin. fn frames_add(h: &Host, a: &[Data]) -> Answer { - point_text(h, frames_doc(h, a)?, None, false) + point_text(h, frames_scope(h, a)?, None, false) } /// `pointText(anchor, orientation?)`. fn frames_point_text(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let scope = frames_scope(h, a)?; let anchor = point(arg(a, 1), "anchor")?; - point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) + point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?) } -/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves +/// it on top of the contents of the collection's layer or group when there is one. fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, container) = frames_scope(h, a)?; if handle_of(arg(a, 1), "PathItem").is_none() { return Err(HostError::Type("textPath must be a PathItem".into())); } @@ -1407,12 +1488,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { } let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); - let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - let id = result_id(&r); - if let (Some((base, postfix)), Some(id)) = (base, id) { - threads::thread_new(h, base, id, postfix)?; + // Makes the type, threaded after or before the base frame when there is one. + let make = |h: &Host| -> std::result::Result, HostError> { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + let id = result_id(&r); + if let (Some((base, postfix)), Some(id)) = (base, id) { + threads::thread_new(h, base, id, postfix)?; + } + Ok(id) + }; + let Some(c) = container else { + return new_ref(h, doc, make(h)?); + }; + check_open(h, doc, c)?; + // The path is moved as well as converted, so it must be one that `move` takes. + if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) { + return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0))); } - new_ref(h, doc, id) + super::refuse_protected_edit(h, path)?; + let id = super::atomically(h, |h| { + let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?; + new_ref(h, doc, Some(id)) +} + +/// Refuses a hidden or locked layer or group as the place for new type. +fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> { + if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) } } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. @@ -1425,17 +1529,22 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a -/// locked artboard, stops it first, as `PageItems.removeAll()` does. +/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or +/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st)?; + let (doc, c) = frames_scope(h, a)?; + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { + let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + // Type that clips a group or layer releases its mask, so the object above it is not made + // the clipping path. + let released = super::masks_cleared_by(&st.doc, &ids); + // So would deleting the type above an image in an ordinary group named as a tracing. + let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1445,8 +1554,13 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + // A clip group named as a tracing, released with an image left first, would become one. + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); + super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; } Ok(Data::Undefined) } @@ -1802,8 +1916,8 @@ pub(super) fn classes(l: &Link) -> Vec { named(vec![ ("typename", get(l, frames_typename), typed("string")), ("length", get(l, frames_length), typed("number")), - ("parent", get(l, frames_parent), typed("Document")), - ("index", method(l, frames_index), returns("number", &[("itemKey", "*")])), + ("parent", get(l, frames_parent), typed("*")), + ("index", method(l, frames_index), returns("TextFrame", &[("itemKey", "*")])), ("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])), ("add", method(l, frames_add), returns("TextFrame", &[])), ("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])), diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e2ea567acd..b105a3fd90 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -1020,6 +1020,31 @@ fn moves_are_validated() { assert_eq!(parent(&s, sub), None); } +/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group +/// or move up in it, and a row moved to index 0 goes directly above it. +#[test] +fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0)); + let layer = parent(&s, a).unwrap(); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + let g = id(&run(&mut s, "object.clippingMask.make", json!({}))); + let before = children(&s, g); + let mask = before[0]; + for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] { + let err = s.execute("node.move", &p).unwrap_err().to_string(); + assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); + assert_eq!(children(&s, g), before, "{p}"); + } + run(&mut s, "node.move", json!({"id": mask.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g), before, "the clipping path stays where it is"); + let d = rect(&mut s, 90.0); + run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path"); + run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, before[2]]); +} + /// The Layers panel's commands refuse a switch given as text or as another value that is not true /// or false, and leave the document, the selection, the highlighted rows and the undo history as /// they were; true, false and null still work. diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index a655002a4d..173414f266 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -479,6 +479,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() { assert!(halves(&pts), "slice: {pts:?}"); } +/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither +/// the path nor where it came from was pixel-aligned. +#[test] +fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); + let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0); + assert!(!aligned(&s, loose)); + s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c))); + let pts = compound_points(&s, c); + assert_eq!(pts.len(), 12); + assert!(halves(&pts), "{pts:?}"); +} + /// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an /// artboard copied with its art, stay on the pixel grid. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index b036382bb9..5ffdbcbd9e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -134,6 +134,65 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the direction handles of a curve, which reach past its visible bounds. +#[test] +fn control_bounds_take_in_the_direction_handles() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!(top(&out[0]) < 180.0, "{out:?}"); + assert_eq!(top(&out[1]), 200.0, "{out:?}"); + assert_eq!(out[1][2].as_f64().unwrap(), out[0][2].as_f64().unwrap(), "{out:?}"); +} + +/// The `controlBounds` of a group leave out the handles of a hidden curve in it. +#[test] +fn control_bounds_leave_out_hidden_paths() { + let (mut s, a, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, id]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"id": id, "visible": false})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.selection[0].parent; vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[1], out[0], "{out:?}"); +} + +/// Each anchor `controlBounds` visits counts toward the data a run passes, so reading the bounds of +/// a large path again and again ends the run where reading its geometric bounds does not. +#[test] +fn control_bounds_count_the_anchors_they_visit() { + let (mut s, _, _) = doc(); + let d: String = (0..2000u32).map(|i| format!(" L{} {}", i % 300, (i * 7) % 200)).collect(); + let id = s.execute("path.create", &json!({"d": format!("M0 0{d}")})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // 100 reads of 2001 anchors are about 200 KB of steps, over a 64 KiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let read = |s: &mut Session, what: &str| run(s, &format!("var i = app.activeDocument.selection[0]; for (var n = 0; n < 100; n++) i.{what};")); + let geometric = read(&mut s, "geometricBounds"); + let control = read(&mut s, "controlBounds"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + geometric.unwrap(); + let e = control.unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + +/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping +/// path. +#[test] +fn control_bounds_of_a_clip_group_come_from_its_clipping_path() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + let mask = rect(&mut s, 100.0, 150.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[0], json!(true), "{out:?}"); + assert_eq!(out[2], out[1], "{out:?}"); +} + /// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. #[test] fn page_item_control_bounds_take_in_the_handles() { @@ -543,6 +602,36 @@ fn app_undo_and_redo_step_through_the_runs_edits() { assert!(failure(&mut s, "app.redo();").contains("No active document")); } +/// A layer, page item or artboard read before `app.undo()` took it away is stale, even when an +/// object added afterwards takes its id; one that `app.redo()` brings back, and one that was there +/// before the undone step, still work. +#[test] +fn a_handle_from_before_an_undo_does_not_name_a_later_object() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, kept = d.layers[0], m;\ + var a = d.layers.add(); app.undo(); var b = d.layers.add(); b.name = 'b';\ + m = ''; try { a.name = 'x'; } catch (e) { m = e.message; } vc.log([m, b.name]);\ + m = ''; try { a.groupItems.length; } catch (e) { m = e.message; } vc.log(m);\ + var p = d.groupItems.add(); app.undo(); var q = d.groupItems.add(); q.name = 'q';\ + m = ''; try { p.name = 'y'; } catch (e) { m = e.message; } vc.log([m, q.name]);\ + var r = d.artboards.add([500, 300, 700, 100]); app.undo(); var t = d.artboards.add([800, 300, 1000, 100]); t.name = 't';\ + m = ''; try { r.name = 'z'; } catch (e) { m = e.message; } vc.log([m, t.name]);\ + var c = d.layers.add(); app.undo(); app.redo(); c.name = 'c'; kept.name = 'kept'; vc.log([c.name, kept.name]);", + ); + assert_eq!( + out, + vec![ + json!(["Stale layer", "b"]), + json!("Stale layer"), + json!(["Stale page item", "q"]), + json!(["Stale artboard", "t"]), + json!(["c", "kept"]), + ] + ); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] @@ -727,6 +816,28 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { } } +/// An opacity near the one an item has, but not the one it reports, is set. +#[test] +fn an_opacity_close_to_the_current_one_is_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.opacity = 50.00009; vc.log(i.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); +} + +/// A layer opacity near the one the layer has, but not the one it reports, is set. +#[test] +fn a_layer_opacity_close_to_the_current_one_is_set() { + let (mut s, _, _) = doc(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 50; l.opacity = 50.00009; vc.log(l.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); + // The same number again stores as the opacity the layer has, and runs no command. + let sets = |s: &Session| s.journal.iter().filter(|(id, _)| id == "object.setProps").count(); + let before = sets(&s); + log(&mut s, "app.activeDocument.layers[0].opacity = 50.00009;"); + assert_eq!(sets(&s), before); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -734,6 +845,18 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // In either order, the refused assignment leaves nothing selected while the script runs. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + function pick(list) { var m = ''; try { d.selection = list; } catch (e) { m = e.message; } vc.log([m, d.selection.length === 0]); }\ + pick([p[0], p[1]]); pick([p[1], p[0]]);", + ); + assert_eq!(out.len(), 2); + for o in &out { + assert!(o[0].as_str().is_some_and(|m| m.contains("Cannot select PathItem")), "{o}"); + assert_eq!(o[1], json!(true), "{o}"); + } // With the valid item first and the error caught, the run sees the selection unchanged. let out = log( &mut s, @@ -953,6 +1076,45 @@ fn move_and_duplicate_place_by_element_placement() { assert!(e.contains("hidden or locked"), "{e}"); } +/// An object cannot go behind a clip group's clipping path; one put at the end of the group goes +/// directly above the clipping path. +#[test] +fn an_object_cannot_go_behind_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = kids(&s); + s.execute("object.setProps", &json!({"id": before[0].0, "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"id": before[1].0, "name": "art"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); + assert!(e.contains("an object cannot go below a clipping mask"), "{e}"); + assert_eq!(kids(&s), before); + // The clipping path moved directly below the object above it stays where it is. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + // The clipping path put at the end of its own clip group stays where it is; put on top of the + // group's contents, it is refused. + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + for place in ["INSIDE", "PLACEATBEGINNING"] { + let e = failure( + &mut s, + &format!("var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.{place});"), + ); + assert!(e.contains("the clipping path stays at the bottom of its clip group"), "{place}: {e}"); + assert_eq!(kids(&s), before, "{place}"); + } + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), [before[0], c, before[1]]); +} + #[test] fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); @@ -1389,6 +1551,30 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +/// A path saved with selected segments and no anchor entry gets its segments back, and only the +/// anchors at their ends, which `select.segments` selects with them. +#[test] +fn an_edit_gives_a_path_with_only_segments_no_other_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let ends = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert_eq!(ends.as_ref().map(|e| e.len()), Some(2)); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + s.active_mut().unwrap().selection.anchors.remove(&a); + let before = s.active().unwrap().selection.clone(); + assert!(before.segments.contains_key(&a) && !before.anchors.contains_key(&a)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.anchors.get(&a), ends.as_ref()); + assert_eq!(sel.segments.get(&a), before.segments.get(&a)); + let mut objects = sel.objects.clone(); + objects.sort(); + let mut was = before.objects.clone(); + was.sort(); + assert_eq!(objects, was, "the same objects are selected"); +} + #[test] fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { let (mut s, a, b) = doc(); @@ -2224,6 +2410,47 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does. +#[test] +fn a_layers_page_items_read_names_as_the_documents_do() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.layers[0].pageItems;\ + vc.log([p['Logo'].name, 'Logo' in p, 'none' in p, p[-1] === undefined, p.index(0).name, String(p)]);\ + var m = ''; try { p['none']; } catch (e) { m = e.message; } vc.log(m);\ + var n = ''; try { p.index(1.5); } catch (e) { n = e.message; } vc.log(n);", + ); + assert_eq!(out, vec![json!(["Logo", true, false, true, "Logo", "[PageItems]"]), json!("Not found"), json!("Not found")]); +} + +/// A layer's `textFrames.areaText` refuses a path in a locked layer and leaves it as it was. +#[test] +fn area_text_into_a_layer_refuses_a_locked_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var d = app.activeDocument, p = d.pathItems[d.pathItems.length - 1], l = d.layers.add(); l.textFrames.areaText(p);"); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().doc.node(a).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); +} + +/// `clipped` on a group on a locked artboard throws `Cannot edit` and keeps the group as it was. +#[test] +fn clipping_a_group_on_a_locked_artboard_is_refused() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert!(!s.active().unwrap().doc.layers[0].children().unwrap().iter().any(|n| n.clips())); +} + /// A layer's or group's collection and an artboard read before File › Revert are stale after it, /// while the document's own collections follow the loaded document. #[test] @@ -2337,7 +2564,8 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { fn scoped_remove_all_refuses_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": g, "name": "locked"})).unwrap(); let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); @@ -2350,20 +2578,32 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // A path and a group on a second, unlocked artboard, made last so each lists first in its + // scope, are not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let u = rect(&mut s, 1300.0, 100.0, 20.0, 20.0); + let v = rect(&mut s, 1100.0, 100.0, 20.0, 20.0); + let w = rect(&mut s, 1150.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [v.0, w.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); let before = format!("{:?}", s.active().unwrap().doc.layers); let steps = undo_steps(&s); for scope in [ "app.activeDocument.layers[0].pageItems", "app.activeDocument.layers[0].groupItems", "app.activeDocument.groupItems", - "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.groupItems.getByName('locked').pageItems", "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", ] { - let err = failure(&mut s, &format!("{scope}.removeAll();")); - assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + // The error is caught, so the run keeps whatever `removeAll()` did before it threw. + let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); + assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); assert_eq!(undo_steps(&s), steps, "{scope}"); + let doc = &s.active().unwrap().doc; + assert!([u, v, w].iter().all(|i| doc.node(*i).is_some()), "{scope}"); } lock(&mut s, false); let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); @@ -3404,7 +3644,7 @@ fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() { } #[test] -fn a_compound_paths_path_items_are_path_items() { +fn a_compound_paths_path_items_are_page_items() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.compoundPath.make", &json!({})).unwrap(); @@ -3470,6 +3710,9 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { let b = run(&mut s, in_order).unwrap(); assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); + // A list built again for each lookup would add a host call to both. Building the document's + // page items for `groupItems` counts one call. + assert_eq!(a["hostCalls"], json!(51), "{a}"); } /// A loop over `layers.length` and `layers[i]` lists the layers once while the document is @@ -3489,6 +3732,39 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// Reading `zOrderPosition` for every layer lists the layers once while the document is unchanged. +#[test] +fn z_order_position_of_each_layer_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, k = L.length, z = []; for (var i = 0; i < k; i++) { z.push(L[i].zOrderPosition); } vc.log(z[0]); vc.log(z[k - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// `groupItems.createFromFile` on a collection whose group is gone reports the stale object before +/// the member that is not available yet. +#[test] +fn create_from_file_on_a_stale_group_collection_reports_it_stale() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var g = app.activeDocument.groupItems[0], c = g.groupItems; g.remove(); c.createFromFile(new File('x.svg'));"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.groupItems[0].groupItems.createFromFile(new File('x.svg'));"); + assert!(e.contains("GroupItems.createFromFile is not available yet"), "{e}"); +} + /// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the /// document's `pageItems`, also when the list was already built. #[test] @@ -3697,6 +3973,82 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for +/// every number, a negative one included. +#[test] +fn a_stale_containers_list_throws_its_stale_error_for_any_index() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-stale-index"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pageItems", "groupItems"] { + let source = + format!("var d = app.activeDocument, p = d.layers[0].{list}; d.pageItems[0].name = 'changed'; vc.run('file.revert'); p.index(-1);"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{list}: {e}"); + } +} + +/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is +/// not its clipping path; the run's one undo step puts everything back. +#[test] +fn remove_all_on_a_clip_group_releases_its_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); g.groupItems.add(); vc.log(g.clipped);"); + assert_eq!(out, [json!(false), json!(false)]); + assert!(!s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert!(st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // `groupItems.removeAll()` leaves the clipping path, and the group keeps its mask. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.groupItems.add(); g.groupItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);", + ); + assert_eq!(out, [json!(true), json!(2)]); +} + +/// `remove()` on a clip group's clipping path while other art stays in the group releases the +/// mask, so the art above it is not made the clipping path, and so does emptying a clipping layer +/// with the document's `pageItems.removeAll()`. +#[test] +fn deleting_a_clipping_path_releases_its_mask() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let mask = kids(&s)[0]; + assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. })); + s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap(); + let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips(); + assert!(clips(&s)); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);"); + assert_eq!(out, [json!([false, 2])]); + assert!(!clips(&s)); + assert_eq!(kids(&s), [a, b]); + // A clipping layer emptied by `pageItems.removeAll()` releases its mask too. + let (mut s, _, _) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].clips()); + log(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(!s.active().unwrap().doc.layers[0].clips()); +} + /// Choosing the artboard that is active only by default keeps that artboard: one inserted before it /// moves it to the next index, and the report gives that index. #[test] @@ -3909,6 +4261,41 @@ fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { assert!(e.contains("at most 10000"), "{e}"); } +#[test] +fn has_selected_artwork_on_an_empty_layer_passes_a_full_selection() { + let (mut s, a, _) = doc(); + let n = crate::script::dom::MAX_LISTED; + // Each Duplicate of everything doubles the objects. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..n.ilog2() { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + assert!(s.active().unwrap().selection.objects.len() > n); + // The empty layer adds nothing, so the selection's size does not matter. + run(&mut s, "app.activeDocument.layers.add().hasSelectedArtwork = true;").unwrap(); + // A layer with an unselected object would take the selection past the limit. + s.execute("select.toggle", &json!({"ids": [a.0]})).unwrap(); + assert!(s.active().unwrap().selection.objects.len() > n); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").contains("at most")); + assert!(!s.active().unwrap().selection.objects.contains(&a)); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn artboards_insert_gives_undefined_and_index_reflects_an_artboard() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([500, 300, 700, 100], 0));\ + function info(o, n) { var m = o.reflect.methods; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType + ':' + m[i].arguments[0].dataType; }\ + function prop(o, n) { var m = o.reflect.properties; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType; }\ + vc.log(info(A, 'index')); vc.log(prop(app.activeDocument.pageItems, 'parent'));", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard:*"), json!("*")]); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..403510d73c 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1197,6 +1197,102 @@ fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and +/// `textFrames.removeAll()` refuse it when an image would be left first in the released group. +#[test] +fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("release-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\ + vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\ + d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing +/// refuse to leave an image first in it, before the document changes, and delete when another +/// object stays first. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("remove-all-trace-name"); + let refused = json!("Only Image Trace can make a tracing"); + for (under, call) in [ + ("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"), + ("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"), + ] { + let (mut s, _) = session(&base, false); + // The group holds the type or group at the bottom and the image above it. + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\ + d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);" + ), + ); + assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}"); + assert_eq!(undo_steps(&s), steps, "{call}"); + assert!(traces(&s).is_empty()); + } + // With a rectangle left first, the type goes and the group stays an ordinary group. + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\ + t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\ + g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);", + ); + assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 480779c60c..7b7bb91078 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -467,8 +467,13 @@ fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); let db = vectorcraft_text::FontDb::global(); - let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); - if !covers(from) || covers(to) { + // Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is + // missing, and without them it is skipped. A lookup that falls back to another face counts + // as missing. + let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular"); + let faces = regular(from).zip(regular(to)); + assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available"); + if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) { return; // Installed fonts of these names cover other characters. } let mut s = Session::new(); @@ -694,6 +699,11 @@ fn collections_of_text_add_words_characters_and_paragraphs() { ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + // A range of a frame that is gone stays stale rather than of the wrong type. + ( + "var o = app.activeDocument.textFrames[1].characters[0]; app.activeDocument.textFrames[1].remove(); t.words.add('x', o)", + "Stale text range", + ), ] { let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); @@ -757,6 +767,20 @@ fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); } +/// Text added after a range that ends inside a character goes after the whole character, and the +/// range returned holds the added text. +#[test] +fn text_added_after_half_a_character_goes_after_it() { + let (mut s, id) = doc_with("a\u{1F600}b"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\ + var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);", + ); + assert_eq!(out, vec![json!([3, "X"])]); + assert_eq!(plain(&s, id), "a\u{1F600}Xb"); +} + #[test] fn text_fonts_find_a_bundled_face_by_its_postscript_name() { let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { @@ -831,6 +855,120 @@ fn type_made_with_a_large_id_is_the_new_type() { assert_eq!(plain(&s, NodeId(big)), ""); } +/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a +/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type +/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current. +const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\ + function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\ + put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\ + var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\ + var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\ + var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\ + function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }"; + +#[test] +fn a_layers_and_a_groups_text_frames_list_only_their_own_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + &format!( + "{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\ + vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\ + vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\ + vc.log(d.textFrames.length);" + ), + ); + assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"])); + assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"])); + assert_eq!(out[2], json!(["front", "back", true])); + assert_eq!(out[3], json!(6)); + // Type inside the layer's group or sublayer is not the layer's own. + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');")); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn text_frames_of_a_layer_or_group_put_new_type_in_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap(); + let before = undo_steps(&s); + // The rectangle is in the first layer, which becomes `base`; `other` is current while the + // collections of `base` and `g` add type. + let out = log( + &mut s, + &format!( + "var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\ + var t = L0.textFrames.add(); t.name = 'added';\ + vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\ + var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\ + var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\ + g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);" + ), + ); + assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"])); + assert_eq!(out[1], json!(["g", "g-added"])); + assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"])); + // removeAll takes the group's own type and leaves the type inside its group. + assert_eq!(out[3], json!(["gg", "added,front,back"])); + assert_eq!(undo_steps(&s), before + 1); + // A locked layer and a hidden group take no new type, and the run changes nothing. + let before = undo_steps(&s); + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();")); + assert!(e.contains("hidden or locked"), "{e}"); + let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);")); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), before); +} + +/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the +/// type stays an ordinary member and is not made the clipping path. +#[test] +fn text_frames_remove_all_releases_a_mask_the_type_clips() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id); + assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path"); + let steps = undo_steps(&s); + let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);"); + assert_eq!(out, [json!(false)]); + let st = s.active().unwrap(); + assert!(!st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // The run is one undo step, and undoing it puts back both the type and its mask. + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(first(&s), Some(NodeId(t))); +} + +#[test] +fn text_create_puts_type_in_the_layer_or_group_it_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // A new layer is current, and a locked one takes no type. + let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap(); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = undo_steps(&s); + for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] { + assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before); + let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group))); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 7dab7dccf6..33b5f988e1 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -152,7 +152,7 @@ const INSIDE: &[(&str, &str)] = &[ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ - textFrames= toString typename visible visible= zOrder zOrderPosition", + toString typename visible visible= zOrder zOrderPosition", ), ("Layers.", "prototype"), ("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"), @@ -160,7 +160,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "GroupItem.prototype.", "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ - rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + rasterItems rasterItems= symbolItems symbolItems= textFrames", ), ("GroupItems.", "prototype"), ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"), diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index 086b711aec..a7e83e56f3 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() { assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true)); assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false)); } + +/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint +/// transform [`GOLD_TINT`]). +fn gold_space(spaces: &str) -> Space { + use craft::pdf::interpret::Function; + use craft::pdf::syntax::object::{FromBytes, Object}; + let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap()); + let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap(); + Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None) +} + +const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + +/// The scan for ink spaces looks 32 levels into an object and no deeper. +#[test] +fn ink_spaces_nested_past_the_scan_depth_are_not_found() { + let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]"); + let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels)); + assert_eq!(gold_space(&nested(20)), Space::Inks(0)); + assert_eq!(gold_space(&nested(40)), Space::Other); +} + +/// The scan keeps 4,096 ink spaces: a space after that many others is not found. +#[test] +fn ink_spaces_past_the_scan_count_are_not_found() { + let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>"; + let spaces = |n: usize| -> String { + let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect(); + format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]") + }; + assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095)); + assert_eq!(gold_space(&spaces(4096)), Space::Other); +} + +/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are +/// decoded; the same samples read at a smaller size are not. +#[test] +fn one_ink_images_past_the_pixel_cap_are_refused() { + use std::io::Write; + let side = 8193u32; + let row = (side as usize).div_ceil(8); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![0u8; row * side as usize]).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect(); + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap(); + let st = file + .objects() + .into_iter() + .find_map(|o| match o { + craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s), + _ => None, + }) + .unwrap(); + assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS)); + assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32])); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 731f18ff06..5697e70bb2 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -370,6 +370,53 @@ fn tiling_patterns_become_pattern_swatches() { assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]); } +/// Links in the chains of nested patterns and soft masks below: more than are read. +const CHAIN: usize = 12; + +/// The warnings of opening a page drawing `content` with `resources`, plus `objects`. +fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec { + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + open_with(&one_page(content, resources, &extra), |_| {}).warnings +} + +/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a +/// chain of them opens, with a warning. +#[test] +fn patterns_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let cells: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = if i + 1 < CHAIN { + (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f") + } else { + (String::new(), "1 0 0 rg 0 0 5 5 re f") + }; + let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10"; + stream(&format!("{cell} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}"); +} + +/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain +/// of them opens, with a warning. +#[test] +fn soft_masks_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let groups: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = + if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") }; + let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>"; + stream(&format!("{group} /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}"); +} + // ---------- text ---------- const HELVETICA: &str = diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 33ada6d549..3badde2181 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's +/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with +/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default +/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over +/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden. +#[test] +fn membership_dictionaries_show_art_by_their_policy() { + let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]"); + let both = format!("[{a} 0 R {b} 0 R]"); + let runs = [ + ("AllOn", format!("{both} /P /AllOn")), + ("AnyOff", format!("{both} /P /AnyOff")), + ("AllOff", format!("{both} /P /AllOff")), + ("AnyOn", both.clone()), + ("OffAlone", format!("{b} 0 R /P /AllOff")), + ("OnAlone", format!("{a} 0 R /P /AllOff")), + ]; + let memberships: Vec = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect(); + let first = first_extra(1) + 2; + // Every ink has the same tint transform: only the walk tells the interpreter's paths apart. + let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + let mut content = String::new(); + let (mut props, mut spaces) = (String::new(), String::new()); + for (i, (ink, _)) in runs.iter().enumerate() { + content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i); + props += &format!("/M{i} {} 0 R ", first + i); + spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] "); + } + let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) }; + let mut extra: Vec<&str> = vec![&objs[0], &objs[1]]; + extra.extend(memberships.iter().map(String::as_str)); + let options = ImportOptions { layers: false, ..Default::default() }; + let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap(); + assert_eq!(names(&r.document), ["Page 1"]); + let inks: Vec> = r.document.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + }) + .collect(); + let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string())); + assert_eq!(inks, shown, "{:?}", r.warnings); +} diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f2a7e4835e..78ff31af5f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -190,6 +190,40 @@ mod alias_tests { assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); } + /// The file search for a character no loaded font covers skips font files over 40 MiB + /// without reading them, and loads the same font at its own length. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_skips_font_files_over_40_mib() { + use crate::{FileFontInfo, FileGlyph, build_file_font}; + use kurbo::Shape; + let pua = '\u{E123}'; + let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let font = build_file_font(&info, &[glyph]).unwrap(); + // Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let search = |name: &str, bytes: &[u8]| { + let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir(&dir.0).unwrap(); + std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.0.clone()]); + let found = db.system_fallback(pua); + std::fs::remove_dir_all(&dir.0).unwrap(); + found + }; + assert!(search("small", &font), "a font at its own length is loaded"); + let mut padded = font.clone(); + padded.resize(41 << 20, 0); + assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 54e4125e88..2fd95fd6b2 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, #[cfg(test)] mod tests { - use super::longest_start_tried; + use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried}; + use vectorcraft_geom::{Rect, shapes}; + + /// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline. + fn block(w: f64, h: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((w, 0.0)); + p.line_to((w, h)); + p.line_to((0.0, h)); + p.close_path(); + p + } + + fn end_points(path: &BezPath) -> Vec { + path.elements() + .iter() + .filter_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), + PathEl::ClosePath => None, + }) + .collect() + } + + /// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge + /// follows a circle `h` farther along the path's normal; its corners stay at the ends of its + /// step along the path. Moving it off the path (`rise`) moves both edges by the same amount. + #[test] + fn an_outline_bent_along_a_circle_follows_it() { + let (center, r) = (Point::new(100.0, 100.0), 100.0); + let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + let (w, h, s) = (40.0, 20.0, 30.0); + let (p0, d0) = ap.at(s); + let (p1, _) = ap.at(s + w); + // Which way the path's normal points: away from the center (+1) or towards it (-1). + let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum(); + let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r); + for rise in [0.0, 5.0] { + let bend = GlyphBend { s, step: w, advance: w, rise }; + let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline"); + let points = end_points(&bent); + let (base, top) = (r + side * rise, r + side * (rise + h)); + let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)]; + for c in corners { + assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}"); + } + // The edges are cut into pieces that stay between the two circles; a straight chord + // between the corners would pass inside the inner one. + assert!(points.len() > 8, "rise {rise}: {} points", points.len()); + let (inner, outer) = (base.min(top), base.max(top)); + for p in &points { + let d = p.distance(center); + assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}"); + } + let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count(); + assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle"); + } + } + + /// A path that does not turn under the glyph, and a glyph with no advance, leave the outline + /// as it is. + #[test] + fn an_outline_on_a_straight_path_is_not_bent() { + let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0))); + let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none()); + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some()); + let no_advance = GlyphBend { advance: 0.0, ..bend }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none()); + } /// The longest start that fits is found among the ones tried; past the tries, a binary search /// finds one that fits, with as many more tries as halvings of the rest. diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index d128aba2e4..0c2f8503ef 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -647,14 +647,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { /// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its /// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the /// file's own text. -pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value { let given = p.get("textAs").is_some_and(|v| !v.is_null()); let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); let options = p.is_object() || p.is_null(); if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { - return p.clone(); + return p; + } + if !p.is_object() { + p = json!({}); } - let mut p = if p.is_object() { p.clone() } else { json!({}) }; p["textAs"] = json!(TextAs::Outlines.id()); p } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 1d1d434f2d..ab2bd34908 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -553,7 +553,7 @@ fn a_pdf_opened_without_the_dialog_takes_the_pdf_text_preference() { io::open_document(&mut app, "one.pdf", &one, None, &json!({"textAs": "text"})).unwrap(); opened(&mut app); assert_eq!(type_objects(&app), 1, "an open that gives textAs keeps it"); - let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, &serde_json::Value::Null); + let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, serde_json::Value::Null); assert!(p.is_null(), "a .ai file opens as it says: {p}"); // In the dialog too, a .ai file starts from Editable, and its choice is not kept for PDFs. assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(false, None), None, None)); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 87fd9fbd2e..7223cc92fb 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -150,9 +150,10 @@ pub fn opens_as(name: &str) -> Option { /// Open a document through the engine loader with the `document.open` options in `p` → /// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first /// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent -/// files, once the question is answered. A PDF opens with the `pdfTextAs` preference unless `p` -/// gives `textAs` ([`dialogs::import_pdf::with_preferred_text_as`]). +/// files, once the question is answered. PDF font and Text As preferences supply missing options; +/// explicit `embeddedFonts` and `textAs` choices keep their precedence. pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { + let p = app.session.prefs.with_pdf_font_choice(p); let p = &dialogs::import_pdf::with_preferred_text_as(app, name, bytes, p); let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; @@ -680,7 +681,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } - let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, &Value::Null); + let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, Value::Null); return Ok(crate::opening::start_with(app, path, bytes, params)); } let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index d9f334105c..034237e5e6 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -4,6 +4,75 @@ use super::*; use crate::Services; use crate::tests::picks::{cancel_dialog, close_shown, draw_dialogs, open_dialogs, show_question}; +/// #9286: both real open consumers apply the same preference/explicit-option precedence and bind +/// the carried program to rendered text, rather than merely storing the requested option. +#[test] +fn synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides() { + use std::fmt::Write as _; + use vectorcraft_doc::{FILE_FONT_MIME, NodeKind}; + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let mut glyph = FileGlyph { ch: 'x', outline: Default::default(), advance: 600.0 }; + glyph.outline.move_to((0.0, 0.0)); + glyph.outline.line_to((500.0, 0.0)); + glyph.outline.line_to((500.0, 700.0)); + glyph.outline.line_to((0.0, 700.0)); + glyph.outline.close_path(); + let info = FileFontInfo { family: "VectorCraftUIOpenPreference".into(), style: "Regular".into(), ..Default::default() }; + let font_bytes = build_file_font(&info, &[glyph]).unwrap(); + let mut hex = String::with_capacity(font_bytes.len() * 2); + for b in font_bytes { + write!(hex, "{b:02x}").unwrap(); + } + let n = first_extra(1); + let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(100.0, 100.0, "BT /F1 24 Tf 10 40 Td (x) Tj ET") }; + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+VectorCraftUIOpenPreference /FirstChar 120 /LastChar 120 /Widths [600] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>", + n + 1 + ); + let descriptor = format!( + "<< /Type /FontDescriptor /FontName /ABCDEF+VectorCraftUIOpenPreference /Flags 34 /FontBBox [0 -200 500 900] /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 {} 0 R >>", + n + 2 + ); + let program = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1); + let bytes = pdf_with(&[page], &[&font, &descriptor, &program], None); + for background in [false, true] { + for (preference, explicit, expected) in [(false, None, false), (true, None, true), (false, Some(true), true), (true, Some(false), false)] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + app.session.prefs.pdf_import_embedded_fonts = preference; + let mut params = json!({"textAs": "text"}); + if let Some(value) = explicit { + params["embeddedFonts"] = json!(value); + } + if background { + start_with(&mut app, "embedded-preference.pdf", bytes.clone(), params); + open_ready(&mut app); + } else { + crate::io::open_document(&mut app, "embedded-preference.pdf", &bytes, None, ¶ms).unwrap(); + } + let doc = &app.session.doc().unwrap().doc; + let db = vectorcraft_text::FontDb::global(); + let mut text_count = 0; + let mut carries_font = false; + doc.walk(|node| { + if let NodeKind::Text(text) = &node.kind { + assert_eq!(text.plain_text(), "x", "imported text content"); + text_count += 1; + carries_font |= vectorcraft_text::layout(db, text).glyphs.iter().any(|glyph| db.is_file_font(glyph.font_id)); + } + }); + assert_eq!(text_count, 1, "text survives: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!(carries_font, expected, "rendered font: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!( + doc.images.values().any(|blob| blob.mime == FILE_FONT_MIME), + expected, + "owned font program: background={background}, preference={preference}, explicit={explicit:?}" + ); + } + } +} + #[test] fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/docs/development.md b/docs/development.md index 0e528cdab4..e2aed29e62 100644 --- a/docs/development.md +++ b/docs/development.md @@ -363,6 +363,10 @@ The app decides which cursors exist; whoever draws them works from the list. For doesn't run. `cargo xtask ci` runs the same two as its `test` and `doctests` steps. - The test build leaves out the examples (`--lib --bins --tests`); clippy (`--all-targets`) still checks them. +- PDF open consumers compose the embedded-font preference before Text As without cloning the + composed options again; explicit options win in both synchronous and background opens. + `opening::tests::synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides` + exercises both paths with a generated embedded font and checks rendered font ownership (#9286). - Each crate has one integration-test binary: its test files are modules of `tests/it/main.rs`. Run one file's tests with `cargo nextest run -p vectorcraft-svg --test it roundtrip::` (or `cargo test` with the same arguments). A new test file gets a `mod` line in `main.rs`. diff --git a/docs/mcp.md b/docs/mcp.md index d3b5c477f4..6623411778 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -621,7 +621,7 @@ change nothing; an omitted or null `id` keeps the default. Commands that need an `path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and `text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of -`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when +`node.move` and `text.create` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when `group` is left out or null, and reports a missing group only when both are left out. A command that needs a number (`x` of `shape.rectangle`, `pos` of `guide.add`, `index`, `x` and `y` of the `object.mesh.*` and `object.envelope.setMeshPoint` point commands, and the others like them) refuses a value that is not a number with @@ -3122,8 +3122,8 @@ through `$`: 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and - compound paths; a clip group's come from its clipping path; in a document in the back, type + visible bounds with the anchors and direction handles of the shown paths in the item; a clip group or clipping + layer takes in only its clipping path's; in a document in the back, type not measured yet is measured first, as the switch to that document would measure it; a valid `position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance or placed document already has is not applied, and its document stays in the back), `editable` (false for an @@ -3137,9 +3137,12 @@ through `$`: group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws - `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception - is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the - document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Moving a tracing's visible, + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The exceptions + are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, `mask.move(art, + ElementPlacement.PLACEAFTER)` with the object directly above it and `mask.move(group, ElementPlacement.PLACEATEND)` + with its own clip group, which succeed and leave the document unchanged; + `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Any other place for the clipping path, such as + `INSIDE` or `PLACEATBEGINNING` of its own clip group, throws the `node.move` error below and moves nothing. Moving a tracing's visible, unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before @@ -3239,7 +3242,15 @@ through `$`: 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` - and delete nothing. Setting `width` or `height` scales the object along + and delete nothing. `remove()`, the document's `pageItems.removeAll()` and any `textFrames.removeAll()` that + delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step, + so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping + path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they + throw `Only Image Trace can make a tracing` and delete nothing. `textFrames.removeAll()` and the `removeAll()` of a + group's `pageItems`, `groupItems` or `compoundPathItems` throw the same error and delete nothing when they would + leave an image at the bottom of an ordinary group named `Image Trace`. The `removeAll()` of a layer's or group's + `pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described + above. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, @@ -3275,7 +3286,8 @@ through `$`: `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run - `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into + `layer.setProps`, and `opacity` runs `object.setProps`. `opacity` reads rounded to 4 decimals; assigning the number it + reads, or one that stores as the same opacity, runs no command. `move` and `zOrder` run `node.move`; a layer goes into another layer, to the top level of the document, or directly above or below another layer. Every page item has `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` @@ -3284,8 +3296,9 @@ through `$`: `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns - the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing; - read `artboards[index]` afterward), `remove(index)` (runs + the new artboard), `insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not + the index the new artboard got, so an index that appends runs no `artboard.reorder`; returns nothing; read + `artboards[index]` afterward), `remove(index)` (runs `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its @@ -3331,10 +3344,13 @@ through `$`: `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because - artboards were inserted, removed or reordered before it. An index outside the list throws a + artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was + chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active + one. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `GroupItems.createFromFile` throw an error that says they are not available yet. `GroupItems.createFromFile` on a + collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and @@ -3344,7 +3360,9 @@ through `$`: The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel - alignment. + alignment, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the + clipping path of a clip group or clipping layer at its bottom: it refuses to move the clipping path until the mask + is released, and puts a row given index 0 there directly above the clipping path. - `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`, `getIntegerPreference(key)`, `getRealPreference(key)`, `getStringPreference(key)`, the four matching `set…(key, value)` and `removePreference(key)`. The key `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`. @@ -3807,11 +3825,17 @@ through `$`: with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and - `baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. `removeAll()` throws - and deletes nothing when any type object is hidden or locked, is in a hidden or locked layer or group, or is on a - locked artboard (`cannot delete objects on a locked artboard`). A text edit, `createOutline()` or a conversion of - such a type object, and `areaText` or `pathText` given such a path, throw `Cannot edit` with nothing changed. A - `TextFrame` + `baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `Layer` and a + `GroupItem` have `textFrames` with the same members. VectorCraft's own rules for + them: they list the type objects directly in the layer or group, topmost first, and their `add()`, `pointText`, + `areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer. + Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the + drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or + locked layer or group throws an error and changes nothing. `removeAll()` deletes every type object the collection + lists with `edit.clear` in one step; when one is hidden or locked, in a hidden or locked layer or group, or on a + locked artboard (`cannot delete objects on a locked artboard`), it throws an error and deletes nothing. A text edit, + `createOutline()` or a conversion of such a type object, and `areaText` or `pathText` given such a path, throw + `Cannot edit` with nothing changed. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/roadmap.md b/docs/roadmap.md index 0490d34ce7..7d9ac92d30 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -209,7 +209,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; the rest of the script document model (layers, artboards, text lines, gradient stops and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the rest of the script document model (the `pathItems` of layers and groups, text lines, gradient stops and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1c7b7823d9..a40e609223 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1126,7 +1126,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.