diff --git a/Cargo.lock b/Cargo.lock index 74b6189119..064b89e9e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1070,7 +1070,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -1080,6 +1080,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -1096,7 +1097,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "flate2", "serde", diff --git a/Cargo.toml b/Cargo.toml index 2d53acdc39..6d47f057c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,9 +21,9 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a637 # desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.) craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 3c433d3445..95ef265cc9 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -275,23 +275,30 @@ impl Scope { } } +/// Does `scope` draw its members' faces other than plainly: does it have an opacity mask or a +/// blending mode other than Normal? +fn composites(scope: &Scope) -> bool { + scope.mask.is_some() || scope.blend != BlendMode::Normal +} + /// `surfaces`, each with the scopes of the member it was built from, in groups with the opacity -/// masks of those scopes, so each mask applies to the faces of the members it holds. The members' -/// opacity is already in their paint ([`Profile::opacity`]), so these groups are opaque. +/// masks and blending modes of those scopes, so each applies to the faces of the members it holds. +/// The members' opacity is already in their paint ([`Profile::opacity`]), so these groups are +/// opaque. fn masked(id: NodeId, surfaces: Vec<(&[Scope], Arc)>) -> Vec> { let masks: Vec<(Vec, Arc)> = surfaces .into_iter() .map(|(scopes, s)| { - let masks = scopes.iter().filter(|s| s.mask.is_some()).map(|s| Scope { opacity: 1.0, blend: BlendMode::Normal, ..s.clone() }).collect(); + let masks = scopes.iter().filter(|s| composites(s)).map(|s| Scope { opacity: 1.0, ..s.clone() }).collect(); (masks, s) }) .collect(); crate::revolve::scoped(id, masks.iter().map(|(scopes, s)| (scopes.as_slice(), s.clone())).collect(), 0) } -/// Does any of `shapes` sit in a scope with an opacity mask? +/// Does any of `shapes` sit in a scope with an opacity mask or a blending mode other than Normal? fn has_masks(shapes: &[Profile]) -> bool { - shapes.iter().any(|s| s.scopes.iter().any(|s| s.mask.is_some())) + shapes.iter().any(|s| s.scopes.iter().any(composites)) } /// One shape a solid is built from: its outline and fill rule, the fills and strokes that paint @@ -550,8 +557,9 @@ pub(crate) fn reshape_members(n: &Node, before: &[Effect], shapes: &mut [Profile /// each in its own paint. When every one is opaque with normal blending and no colored light makes /// a surface one composite or masks it, their faces are drawn in one back-to-front order (where /// depths tie, as for the caps turned toward the viewer, in the order of the appearance); -/// otherwise each solid is a surface of its own, in that order. A member's opacity mask, or that of -/// a group it is in, masks the surfaces of the members it holds ([`masked`]). +/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and +/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds +/// ([`masked`]). fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs index 2973b7113b..b2f6daf1c6 100644 --- a/crates/effects/src/solids/tests_sources.rs +++ b/crates/effects/src/solids/tests_sources.rs @@ -523,6 +523,52 @@ fn an_opacity_mask_on_a_member_or_a_group_in_a_three_d_group_masks_its_solids() } } +/// The leaf faces of `art` that draw something, each with its visual bounds and whether it is drawn +/// inside a group with blending mode `mode`. +fn faces_in_mode(art: &Node, mode: BlendMode) -> Vec<(Rect, bool)> { + fn walk(n: &Node, inside: bool, mode: BlendMode, out: &mut Vec<(Rect, bool)>) { + let inside = inside || (n.children().is_some() && n.blend == mode); + match n.children() { + Some(children) => children.iter().for_each(|c| walk(c, inside, mode, out)), + None => out.extend(n.visual_bounds().map(|b| (b, inside))), + } + } + let mut out = Vec::new(); + walk(art, false, mode, &mut out); + out +} + +#[test] +fn a_blending_mode_on_a_member_or_a_group_in_a_three_d_group_applies_to_its_solids() { + let d = document(); + let mode = |mut n: Node, mode: BlendMode| { + n.blend = mode; + n + }; + let other = || Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0)); + let member = || rect(1, 100.0, 100.0, 150.0, 200.0, 2.0); + let cases = [ + ("a multiplied member", Node::group(NodeId(90), vec![Arc::new(mode(member(), BlendMode::Multiply)), other()])), + ( + "a member of a multiplied group", + Node::group(NodeId(90), vec![Arc::new(mode(Node::group(NodeId(80), vec![Arc::new(member())]), BlendMode::Multiply)), other()]), + ), + ]; + for (what, g) in cases { + for id in TYPES { + let g = with(g.clone(), id, json!({})); + // The member spans y 100 to 200 and the other member y 600 to 650, and every type keeps + // its faces near those heights (Revolve turns them around a vertical axis): a face whose + // center is above y 400 belongs to the member. + let (mine, others): (Vec<_>, Vec<_>) = + faces_in_mode(&art(&d, &g, id).expect("drawn"), BlendMode::Multiply).into_iter().partition(|(b, _)| b.center().y < 400.0); + assert!(!mine.is_empty() && !others.is_empty(), "{id}: both members draw faces ({} and {})", mine.len(), others.len()); + assert!(mine.iter().all(|(_, m)| *m), "{id}: every face of {what} is drawn in Multiply"); + assert!(others.iter().all(|(_, m)| !m), "{id}: no face of the other member is drawn in Multiply"); + } + } +} + #[test] fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() { let mut d = document(); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 534e0ec89f..b1377d2fef 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1239,7 +1239,7 @@ impl Clipboard { /// filter when pasted back into the document it came from, and elsewhere keeps its own under a /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would /// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else - /// a free letter or digit; the filter's id is always its name. An error when no free name fits. + /// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits. fn filter_links(&self, d: &Document, same_doc: bool) -> Result> { let mut found = BTreeSet::new(); for n in &self.nodes { @@ -1281,12 +1281,18 @@ impl Clipboard { } } // Free names made from the starts of the name, longest first, then free letters and - // digits: the first under which the filter still draws. + // digits, then other single printable ASCII characters: the first under which the + // filter still draws. let mut ends: Vec = name.char_indices().map(|(i, _)| i).skip(1).collect(); ends.push(name.len()); let starts = ends.iter().rev().filter_map(|&end| name.get(..end).map(str::trim_end)).filter(|b| !b.is_empty()); let shorter = starts.map(|b| unique_name(b, |n| taken.contains(n))); - let single = ('a'..='z').chain('0'..='9').map(String::from).filter(|n| !taken.contains(n)); + let single = ('a'..='z') + .chain('0'..='9') + .chain('A'..='Z') + .chain(('!'..='~').filter(|c| !c.is_ascii_alphanumeric())) + .map(String::from) + .filter(|n| !taken.contains(n)); let renamed = shorter.chain(single).find_map(|new| { let drawn = vectorcraft_render::effects::svg_filter::with_id(&xml, &new) .filter(|x| vectorcraft_render::effects::svg_filter::check(x).is_ok_and(|id| id == new))?; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 9b3223829f..1b217e6c2d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -63,6 +63,7 @@ impl Loaded { /// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG /// (what browsers, PDF and SVG viewers show). +#[derive(Clone)] pub struct RasterImage { /// Content key for `Document::images` (identical files share one blob). pub key: String, diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index c73a23d6c3..8a3485c499 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -80,19 +80,28 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { } /// Whose gradient a selected stop belongs to: the active document, its first selected object -/// (None: the default paint), the proxy in front and the Appearance panel's active item. -/// Selecting other art, toggling the proxy or picking another item leaves no stop selected. +/// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in +/// front and the Appearance panel's active item. Selecting other art, picking a part of the +/// instance, toggling the proxy or picking another item leaves no stop selected. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StopOwner { doc: Option, object: Option, + part: bool, fill: bool, item: Option, } impl StopOwner { pub(crate) fn of(s: &Session) -> Self { - Self { doc: s.active, object: s.active().and_then(|d| d.selection.objects.first().copied()), fill: s.fill_active, item: s.appearance_item() } + let st = s.active(); + Self { + doc: s.active, + object: st.and_then(|d| d.selection.objects.first().copied()), + part: st.is_some_and(|d| d.selection.symbol_part.is_some()), + fill: s.fill_active, + item: s.appearance_item(), + } } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 22d61723e9..020b483f3a 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -521,10 +521,25 @@ fn linked_image(bytes: &[u8]) -> Result { /// The file read for a link: the link to it and its image. type FileRead = (LinkInfo, RasterImage); -/// The file at `f` read for a link like `base` (its image decoded). -fn read_image(f: &mut Found, base: &LinkInfo) -> Result { +/// The images read in one operation, by the path of the file and its content hash: groups whose +/// image keys differ but whose file is the same share one decoded image (and its encoded bytes) +/// instead of each keeping a copy. +type ImageReads = BTreeMap; + +/// The file at `f` read for a link like `base` (its image decoded, or the one `reads` holds for +/// the same file content). +fn read_image(f: &mut Found, base: &LinkInfo, reads: &mut ImageReads) -> Result { let bytes = f.read()?; - Ok((f.link(&bytes, base), linked_image(&bytes)?)) + let hash = hash_bytes(&bytes); + let img = match reads.get(&f.path) { + Some((h, img)) if *h == hash => img.clone(), + _ => { + let img = linked_image(&bytes)?; + reads.insert(f.path.clone(), (hash.clone(), img.clone())); + img + } + }; + Ok((f.link_hashed(hash, base), img)) } /// A linked file read for the objects that show it. @@ -536,8 +551,8 @@ enum Read { } /// The file at `f` read for group `g`: its image, or the artboard or page `g` shows. -fn read_for(f: &mut Found, g: &Group, cmd: &str) -> Result { - let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link).map(Read::Image) }; +fn read_for(f: &mut Found, g: &Group, cmd: &str, reads: &mut ImageReads) -> Result { + let Some((bounding, page_box)) = g.document else { return read_image(f, &g.link, reads).map(Read::Image) }; let bytes = f.read()?; let page = g.link.page.unwrap_or(1); let src = super::place::document::source(&f.path, &bytes, Some(&f.path), page, bounding, page_box, cmd)?; @@ -922,6 +937,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps // (the path as it was, the content shown, a placed document?, the link now) of each file found // away from its path or read again. let mut moved: Vec<(String, String, bool, LinkInfo)> = vec![]; + let mut image_reads = ImageReads::new(); for g in groups(d, None) { let row = rows(std::iter::once(&g), base.doc); let shows_preview = match g.document { @@ -934,7 +950,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps (Status::Missing, _) => out.missing.extend(row), (Status::Modified, Some(mut f)) if update || unread => { let force = unread.then_some(Preserve::Bounds); - match read_for(&mut f, &g, "document.open").and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) { + match read_for(&mut f, &g, "document.open", &mut image_reads).and_then(|read| install_read(d, &g.ids, read, force, Some(&g))) { Ok(()) if unread => {} Ok(()) => out.updated.extend(row), Err(_) => out.missing.extend(row), @@ -943,7 +959,7 @@ pub fn resolve(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_eps (Status::Modified, _) => out.modified.extend(row), // A placed document keeps its file's bytes: only lost ones are read again. (Status::Ok, Some(mut f)) if g.document.is_some() => { - let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open")) } else { None }; + let read = if stale(d, &g) { Some(read_for(&mut f, &g, "document.open", &mut image_reads)) } else { None }; match read { Some(Ok(read)) => { if install_read(d, &g.ids, read, Some(Preserve::Bounds), Some(&g)).is_err() { @@ -1196,6 +1212,7 @@ fn update(s: &mut Session, p: &Value) -> Result { fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) -> Result { let st = s.doc()?; let (mut reads, mut missing) = (vec![], vec![]); + let mut image_reads = ImageReads::new(); let asked = ids.is_some() || path.is_some(); for g in groups(&st.doc, ids.as_deref()).into_iter().filter(|g| path.is_none_or(|p| g.document.is_some() && g.link.path == p)) { match probe(&g, LinkBase::of(st)) { @@ -1203,7 +1220,7 @@ fn update_where(s: &mut Session, ids: Option>, path: Option<&str>) - // Unchanged and showing the file: nothing to read unless asked for. (Status::Ok, Some(_)) if !asked && !stale(&st.doc, &g) => {} // Unreadable as an image (or a document) counts as missing. - (_, Some(mut f)) => match read_for(&mut f, &g, "links.update") { + (_, Some(mut f)) => match read_for(&mut f, &g, "links.update", &mut image_reads) { Ok(read) => reads.push((g, read)), Err(_) => missing.extend(ids_json(&g.ids)), }, @@ -1706,13 +1723,14 @@ fn embed(s: &mut Session, p: &Value) -> Result { let ids: Vec = ids.into_iter().filter(|id| matches!(kind(id), Some(NodeKind::Image(_)))).collect(); // Images showing their preview take their file's pixels first. let (mut done, mut reads) = (vec![], vec![]); + let mut image_reads = ImageReads::new(); for g in groups(&st.doc, Some(&ids)) { if !previewing(&st.doc, &g.key) { done.extend(g.ids); continue; } match probe(&g, LinkBase::of(st)) { - (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link) { + (Status::Ok | Status::Modified, Some(mut f)) => match read_image(&mut f, &g.link, &mut image_reads) { Ok(read) => { done.extend(&g.ids); reads.push((g.ids, read)); @@ -1921,3 +1939,26 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { set(&mut shown); Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) })) } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::tests::links::{Folder, RED, png, write}; + + #[test] + fn groups_of_one_file_share_one_decoded_image() { + let dir = Folder::new("shared-read"); + let path = dir.file("pic.png"); + write(&path, &png(40, 20, RED)); + let (mut reads, base) = (ImageReads::new(), LinkInfo::new(path.clone())); + let mut read = || read_image(&mut found_at(path.clone()).unwrap(), &base, &mut reads).unwrap().1; + let (a, b) = (read(), read()); + assert!(Arc::ptr_eq(&a.blob.bytes, &b.blob.bytes), "one retained copy of the bytes"); + // A changed file is decoded again. + write(&path, &png(40, 20, [1, 2, 3])); + let c = read(); + assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); + } +} diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index d583f6fe34..a5b71d538b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -846,6 +846,15 @@ pub(crate) fn sync_prefs(s: &Session) { *last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder))); } +/// The Additional Plug-ins Folder preference was cleared from `old`: when `old` is the folder last +/// loaded, it is forgotten, so setting the preference to it again loads it again. +pub(crate) fn forget_prefs_folder(old: &str) { + let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + if last.as_ref().is_some_and(|(f, _, _)| f == old.trim()) { + *last = None; + } +} + /// Turns Safe Mode on for `--safe-mode`, before the plug-in folder is attached: no plug-in loads or /// runs in this process from then on. pub fn start_in_safe_mode() { diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 783ce0e919..a92b4095a9 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -697,6 +697,9 @@ impl Session { let history_changed = p.history_states != self.prefs.history_states; let tile_edge_changed = p.pattern_tile_edge_color != self.prefs.pattern_tile_edge_color; let fonts_folder_changed = p.fonts_folder != self.prefs.fonts_folder; + if p.plugins_folder.trim().is_empty() && !self.prefs.plugins_folder.trim().is_empty() { + super::plugin::forget_prefs_folder(&self.prefs.plugins_folder); + } let hyphen_exceptions_changed = p.hyphenation_exceptions != self.prefs.hyphenation_exceptions; let corner_radius_changed = p.corner_radius != self.prefs.corner_radius; let lock_guides_changed = p.lock_guides_by_default != self.prefs.lock_guides_by_default; diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index eab2f30675..f4ae97bb14 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -903,6 +903,29 @@ fn gradients_and_patterns_on_a_picked_object_are_taken() { assert_eq!((undo_steps(&s), &s.paint.fill), (undo, &fill), "nothing changes"); } +/// A stop selected on the whole instance's gradient is not selected once a part of its art is +/// picked, so the Gradient tool does not take Delete for it, and is selected again when the whole +/// instance is. +#[test] +fn picking_a_part_leaves_no_gradient_stop_selected() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let g = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}); + s.execute("select.set", &json!({"ids": [inst.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": g})).unwrap(); + s.fill_active = true; + let view = ViewInfo::default(); + s.select_tool("gradient", view).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + assert_eq!(s.selected_stop(), Some(1)); + assert!(s.tool_claims_key(vectorcraft_tools::ToolKey::Delete, view)); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + assert_eq!(s.selected_stop(), None); + assert!(!s.tool_claims_key(vectorcraft_tools::ToolKey::Delete, view)); + s.execute("select.set", &json!({"ids": [inst.0]})).unwrap(); + assert_eq!(s.selected_stop(), Some(1)); +} + #[test] fn opacity_and_blend_on_a_picked_object_go_through_transparency_set() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 04e7b7784e..3c647deb01 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -1315,6 +1315,25 @@ fn plugin_management_commands() { std::fs::remove_dir_all(&dir).ok(); } +/// Clearing the Additional Plug-ins Folder forgets the folder: setting the same folder again +/// installs what is in it, as setting any other folder does. +#[test] +fn plugins_folder_set_again_after_clearing_installs_its_plugins() { + let dir = crate::tests_links::Folder::new("plugin-folder-cleared"); + let id = "test.engine.foldercleared"; + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + std::fs::write(dir.0.join("cleared.wasm"), wat::parse_str(src).unwrap()).unwrap(); + let mut s = session(); + let folder = json!({"key": "pluginsFolder", "value": dir.0.display().to_string()}); + run(&mut s, "prefs.set", folder.clone()); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed from the folder"); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "prefs.set", json!({"key": "pluginsFolder", "value": ""})); + run(&mut s, "prefs.set", folder); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again when the folder is set again"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// #2541: a plug-in installed in a session with a plug-in store is installed again in the next /// session that attaches the store, and Remove Plug-in takes it out of the store. #[test] diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 92f1e49873..10f0ad75ca 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -324,13 +324,13 @@ fn pasted_art_takes_no_name_the_documents_brushes_use() { assert_eq!(names, ["Shift 3"]); } -/// A pasted filter at the size limit with a one-letter name, when every free name it could take is -/// in use, is refused rather than pasted under the name of the document's filter. +/// A pasted filter at the size limit with a one-letter name takes a free capital letter when every +/// lowercase letter and digit is in use. #[test] -fn a_paste_with_no_free_name_for_its_filter_is_refused() { +fn a_renamed_paste_takes_a_free_capital_letter() { let mut s = session(); for n in ('a'..='z').chain('0'..='9') { - run(&mut s, "svgFilter.define", json!({"xml": format!(r#""#)})); + run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)})); } run(&mut s, "svgFilter.define", json!({"xml": r#""#})); let (open, close) = (r#""#); @@ -339,9 +339,74 @@ fn a_paste_with_no_free_name_for_its_filter_is_refused() { r#"{big}"# ); run(&mut s, "clipboard.importSvg", json!({"svg": svg})); - let before = steps(&s); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, "A"); + assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok("A".to_string())); + assert!(pasted[0].1.contains("dx=\"9\""), "its own filter"); +} + +/// A filter named `n`, with the characters a quoted attribute value cannot hold escaped. +fn one_char_filter(n: char) -> String { + let id = match n { + '"' => """.to_string(), + '&' => "&".to_string(), + '<' => "<".to_string(), + c => c.to_string(), + }; + format!(r#""#) +} + +/// A pasted filter at the size limit with a one-letter name takes a free punctuation character when +/// every letter and digit is in use. +#[test] +fn a_renamed_paste_takes_a_free_punctuation_character() { + let mut s = session(); + for n in ('a'..='z').chain('0'..='9').chain('A'..='Z') { + run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)})); + } + let (open, close) = (r#""#); + let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len())); + let svg = format!( + r#"{big}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 1); + assert_eq!(pasted[0].0, "!"); + assert_eq!(vectorcraft_render::effects::svg_filter::check(&pasted[0].1), Ok("!".to_string())); + assert!(pasted[0].1.contains("dx=\"9\""), "its own filter"); +} + +/// A pasted filter at the size limit with a one-letter name, when every free name it could take is +/// in use, is refused rather than pasted under the name of the document's filter. +#[test] +fn a_paste_with_no_free_name_for_its_filter_is_refused() { + let mut s = session(); + for n in ('a'..='z').chain('0'..='9').chain('A'..='Z') { + run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)})); + } + // A document holds at most 64 filters: the other one-character names are taken by effects + // whose filters were deleted. + for n in ('!'..='~').filter(|c| !c.is_ascii_alphanumeric()) { + let a = rect(&mut s, 10.0); + let name = run(&mut s, "svgFilter.define", json!({"xml": one_char_filter(n)}))["name"].as_str().unwrap().to_string(); + assert_eq!(name, n.to_string()); + run(&mut s, "svgFilter.apply", json!({"name": name, "ids": [a.0]})); + run(&mut s, "svgFilter.delete", json!({"name": name})); + } + let (open, close) = (r#""#); + let big = format!("{open}{}{close}", "a".repeat(vectorcraft_doc::SvgFilter::MAX_XML - open.len() - close.len())); + let svg = format!( + r#"{big}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + let (before, effects) = (steps(&s), filter_effects(&s).len()); + assert_eq!(effects, 32); assert!(err(&mut s, "edit.pasteInPlace", json!({})).contains("no free name")); - assert!(filter_effects(&s).is_empty(), "nothing pasted"); + assert_eq!(filter_effects(&s).len(), effects, "nothing pasted"); assert_eq!(steps(&s), before); } diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 25701650c9..8b3fceecf3 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -19,10 +19,12 @@ //! (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the contents (`X=` … `X+`, then //! `(AIDeformArtKey)`) and the kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object). Then the //! distorted art on plain lines, and the plugin's `XP`. While the contents are edited, the group -//! holds the contents and the dictionary the mesh. A top object's outline is the edge of its -//! one-patch mesh. A warp's mesh is a grid of its shape: a warp of type whose own warp doesn't come -//! out as drawn opens as a mesh envelope on that grid where that does. An envelope whose parts don't -//! read, or that doesn't come out as drawn, keeps its drawn art. +//! holds the contents and the dictionary the mesh, which in some files lies away from the drawn art +//! by a move, as if it hadn't followed the envelope: such a mesh or top object whose grid draws its +//! contents as large as the drawn art but elsewhere is tried again moved onto that art. A top +//! object's outline is the edge of its one-patch mesh. A warp's mesh is a grid of its shape: a warp +//! of type whose own warp doesn't come out as drawn opens as a mesh envelope on that grid where that +//! does. An envelope whose parts don't read, or that doesn't come out as drawn, keeps its drawn art. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; @@ -62,6 +64,10 @@ const MAX_GRID: u32 = 50; /// How far, in points over width and height together, a saved size may lie from the contents' /// bounds with their strokes and still count as that box. const SAVED_SIZE_SLACK: f64 = 0.5; +/// How far, in points over width and height together, what an envelope draws may differ in size +/// from its drawn art and still count as that art moved, and how far it must lie from it to count +/// as moved at all ([`moved_onto`]). +const MOVED_SLACK: f64 = 0.5; /// The bits of the options word that are read: Distort Appearance, Distort Pattern Fills, Distort /// Linear Gradients, Anti-Alias (set: off) and Preserve Shape Using (set: Clipping Mask). const KNOWN_BITS: i64 = 0b111 | 1 << 16 | 1 << 17; @@ -183,6 +189,40 @@ fn with_strokes(kind: &NodeKind) -> Option { Some(kind) } +/// The kind of `envelope`, a mesh or a top object in Edit Contents, with its grid moved onto +/// `drawn`, the drawn art the file saves for it, where what it draws is as large as that art (within +/// [`MOVED_SLACK`]) but lies elsewhere (further than that): moved by as far as the drawn art's box +/// lies from the box of what it draws. While the contents are edited, the grid is kept in the +/// envelope's dictionary, and in some files it lies away from the drawn art by a move, the contents +/// with the drawn art, as if the grid hadn't followed the envelope when it moved. `None` outside +/// Edit Contents, for a warp (it maps from its contents' box, which lies with them), and where +/// nothing is drawn. Symbol instances and pattern fills in the contents are measured as they are, +/// not drawn out: where that makes the sizes differ, no move is tried. +pub(super) fn moved_onto(envelope: &Node, drawn: &Node) -> Option { + let NodeKind::Envelope { kind, editing: true, .. } = &envelope.kind else { return None }; + if matches!(**kind, EnvelopeKind::Warp { .. }) { + return None; + } + // What it draws, measured as its drawn art is: the pieces in a group with its own appearance. + let mut drew = envelope.clone(); + drew.kind = NodeKind::Group { children: vectorcraft_render::expand_live(envelope).into_iter().map(Arc::new).collect(), clip: false }; + let (from, to) = (drew.visual_bounds()?, drawn.visual_bounds()?); + let by = to.center() - from.center(); + let resized = (from.width() - to.width()).abs() + (from.height() - to.height()).abs(); + if !(resized <= MOVED_SLACK && by.x.abs() + by.y.abs() > MOVED_SLACK && by.x.is_finite() && by.y.is_finite()) { + return None; + } + let mut moved = envelope.kind.clone(); + if let NodeKind::Envelope { kind, .. } = &mut moved { + match &mut **kind { + EnvelopeKind::Mesh { points, .. } => points.iter_mut().for_each(|p| *p += by), + EnvelopeKind::TopObject { path, .. } => path.transform(Affine::translate(by)), + EnvelopeKind::Warp { .. } => return None, + } + } + Some(moved) +} + /// A warp: its style, bend, distortions and orientation. fn warp(o: &Obj) -> Option { let style = whole(o, "DeformStyle")??; @@ -552,7 +592,8 @@ impl WarpedType { /// for it ([`live_on_saved_grid`]), which opens in its place where it does: its type stays /// editable in that shape, and the warp's style and bend are lost. With Distort Appearance, each /// is also checked mapping from its type's glyphs grown by half their strokes' weight - /// ([`with_strokes`]). Each + /// ([`with_strokes`]). In Edit Contents, a mesh or top object whose grid draws the type + /// elsewhere than its drawn art is checked last moved onto that art ([`moved_onto`]). Each /// check uses one of the import's checks and, for an envelope that shows, adds to what the page /// check allows ([`drawn_alike`]). Elsewhere, and where the type is set in a font that isn't /// available, the drawn art and the hidden type stay. @@ -634,7 +675,17 @@ impl WarpedType { (plain.visible, plain.opacity) = (true, 1.0); let page = self.page.filter(|_| shown.contains(&drawn)); let mut alike = None; - for (i, kind) in kinds.into_iter().enumerate() { + // In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again + // moved onto that art ([`moved_onto`]), after every other way. + let (mut tries, mut moved, mut again, mut i) = (kinds.into_iter(), vec![], false, 0); + loop { + let Some(kind) = tries.next() else { + if again || moved.is_empty() { + break; + } + (tries, again) = (std::mem::take(&mut moved).into_iter(), true); + continue; + }; // A second try is only made while more checks are left than there are envelopes of // type and warped text objects still to come (some of which may need none): one // envelope's tries don't use up the checks of the others. @@ -642,6 +693,7 @@ impl WarpedType { return Err(TypeKept::Budget); } self.checks -= 1; + i += 1; let mut envelope = art.clone(); (envelope.id, envelope.kind) = (id, kind); let shared = Shared { patterns: &doc.patterns, images: &doc.images }; @@ -651,6 +703,9 @@ impl WarpedType { alike = Some(envelope); break; } + if !again && let Some(kind) = moved_onto(&live_one, &plain) { + moved.push(kind); + } } let envelope = alike.ok_or(TypeKept::Differs)?; if doc.node(drawn).is_none() { diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 02f6f8097c..426416b754 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -913,7 +913,18 @@ impl<'a> Reader<'a> { let mut plain = drawn.clone(); (plain.visible, plain.opacity) = (true, 1.0); let page = self.page_in_doc(); - if !crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent) { + let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + // In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked + // again moved onto that art. + if !alike + && self.envelope_checks > 0 + && let Some(kind) = crate::import::ai::envelope::moved_onto(&shown, &plain) + { + self.envelope_checks -= 1; + (envelope.kind, shown.kind) = (kind.clone(), kind); + alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + } + if !alike { self.warn(crate::import::ai::envelope::DRAWN); return; } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 2c219d2b07..c04d06c6ab 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7880,6 +7880,63 @@ fn an_envelope_whose_contents_are_edited_opens_live_in_edit_contents() { assert_eq!(fill(&content[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); } +/// While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files it +/// lies away from the drawn art by a move, the contents with the drawn art. Where the mesh draws the +/// contents as large as the drawn art but elsewhere, the envelope opens live with its mesh moved +/// onto that art; where it draws them at another size, it keeps its drawn art. +#[test] +fn an_envelope_in_edit_contents_whose_mesh_stayed_behind_opens_live_on_its_drawn_art() { + use kurbo::Shape as _; + use vectorcraft_doc::live::EnvelopeKind; + // The top object of `an_envelope_whose_contents_are_edited_opens_live_in_edit_contents`. + let at = |(i, j): (usize, usize)| (40.0 + i as f64 * 120.0, 20.0 + j as f64 * 60.0); + let handle = |p: (usize, usize), q: (usize, usize)| match (p, q) { + ((0, 1), (1, 1)) => (70.0, 95.0), + ((1, 1), (0, 1)) => (130.0, 95.0), + _ => { + let ((x, y), (u, v)) = (at(p), at(q)); + (x + (u - x) / 3.0, y + (v - y) / 3.0) + } + }; + let mesh = mesh_text(1, 1, &at, &handle, None); + let mut bp = kurbo::BezPath::new(); + bp.move_to((40.0, 20.0)); + bp.curve_to((70.0, 5.0), (130.0, 5.0), (160.0, 20.0)); + bp.curve_to((160.0, 40.0), (160.0, 60.0), (160.0, 80.0)); + bp.curve_to((120.0, 80.0), (80.0, 80.0), (40.0, 80.0)); + bp.curve_to((40.0, 60.0), (40.0, 40.0), (40.0, 20.0)); + bp.close_path(); + let shaped = |a: Affine| EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&(a * bp.clone())), corners: None }; + let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)"); + // The contents and the drawn art lie 30 points right and 15 down of where the mesh in the + // dictionary draws them. + let moved = Affine::translate((30.0, 15.0)); + let contents = Rect::new(70.0, 35.0, 190.0, 95.0); + let read_with = |drawn: &EnvelopeKind| { + let block = format!("0 g\n{mesh}"); + let red = format!("{RED}{}f\n", rect_path(contents.x0, 100.0 - contents.y1, contents.x1, 100.0 - contents.y0)); + read_ok(&layer(&envelope_parts(&red, &keys, &block, 3, &drawn_box(drawn, contents, contents)))) + }; + let r = read_with(&shaped(moved)); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + let (content, kind, _, editing, _) = live_envelope(&a[0]); + assert!(editing); + let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") }; + // Moved as far as the drawn art's box lies from the box of what the mesh draws. + let (got, want) = (path.to_bezpath().bounding_box(), (moved * bp.clone()).bounding_box()); + assert!((got.origin() - want.origin()).hypot() < 0.01 && (got.size() - want.size()).to_vec2().hypot() < 1e-6, "{got:?} {want:?}"); + assert_eq!(content.len(), 1, "{content:#?}"); + assert_eq!(content[0].geometric_bounds(), Some(contents)); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + // Drawn art moved and a tenth larger isn't the mesh's art moved: it stays. + let r = read_with(&shaped(moved * Affine::scale_about(1.1, (100.0, 50.0)))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); +} + /// An envelope that doesn't read (a warp style number past the list, a mesh envelope whose shape /// isn't a mesh, one whose plugin never closes it) keeps its drawn art, with one note; the art /// round it is read as ever. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 2b7b421bba..f9983c6e83 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5846,6 +5846,67 @@ fn a_warp_of_type_without_a_saved_grid_keeps_its_drawn_art() { assert_eq!(super::tests::program_warnings(&r.warnings), [crate::import::ai::ENVELOPE_TYPE_DRAWN], "{:?}", r.warnings); } +/// [`type_envelope_on`] while its contents are edited: the text object in the group before its +/// dictionary, and `shape` in its contents' block, where the editing data then saves the mesh. +fn type_envelope_editing(keys: &str, shape: &str, drawn: &str) -> String { + let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; + format!( + "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", + hidden(&format!("u\n{}U\n", text_object(0))), + hidden(&format!("/ArtDictionary :\n{}", keys.replace("0 /Bool (AIDeformEditModeKey)", "1 /Bool (AIDeformEditModeKey)"))), + hidden(&format!("0 g\n{shape}")), + ) +} + +/// While the contents of an envelope of type are edited, its grid is kept in its dictionary, and in +/// some files it lies away from the drawn art by a move, the type with the drawn art. A warp of type +/// whose saved grid draws the type as large as its drawn art but elsewhere opens live as a mesh +/// envelope on that grid moved onto the drawn art (#3179). +#[test] +fn a_warp_of_type_in_edit_contents_whose_grid_stayed_behind_opens_on_its_drawn_art() { + use vectorcraft_doc::live::EnvelopeKind; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + let mut text = made_envelope_type(&doc); + text.visible = true; + // The drawn art is the grid's moved 10 points left and 25 down. + let by = kurbo::Vec2::new(-10.0, 25.0); + let EnvelopeKind::Mesh { rows, cols, points, handles } = rising_kind() else { panic!("a mesh") }; + let want: Vec = points.iter().map(|p| *p + by).collect(); + let kind = EnvelopeKind::Mesh { rows, cols, points: want.clone(), handles }; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(text)], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options, + frame: Box::default(), + }, + ); + let (drawn, page) = drawn_envelope(&shaped); + let art = native_with_text( + &layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_editing(&arc_keys(0.3), &rising_grid(), &drawn))), + &doc, + ); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let mut live = None; + r.document.walk(|n| { + if let NodeKind::Envelope { kind, editing, .. } = &n.kind { + live = Some(((**kind).clone(), *editing)); + } + }); + let Some((EnvelopeKind::Mesh { points, .. }, true)) = live else { panic!("not a mesh envelope in Edit Contents: {live:?}") }; + assert!(points.iter().zip(&want).all(|(p, q)| (*p - *q).hypot() < 0.05), "{points:?}"); +} + /// A warp of type tried again on its saved grid leaves a check for each envelope of type still to /// come: with one check too few for both, the next envelope, whose first try opens it, gets it. #[test] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index f0dd6b44ba..5a4363108a 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -175,6 +175,63 @@ pub enum Expr { /// A parenthesized expression, kept so a rule about the bare form (a label, a directive) can /// tell them apart. Paren(ExprId), + /// An XML literal (`d`), or with `list` an XMLList literal (`<>…`). + XmlLiteral { + parts: Vec, + list: bool, + }, + /// An E4X name (`@a`, `*`, `ns::a`), the key of an [`Expr::Index`] or the operand of + /// [`Expr::XmlScopeName`] and [`Expr::XmlDescendants`]. + XmlName { + attribute: bool, + qualifier: Option, + name: XmlNamePart, + }, + /// An E4X name standing alone (`@a` in a filter): looked up on the nearest XML value in scope. + XmlScopeName(ExprId), + /// `object..name`. + XmlDescendants { + object: ExprId, + name: ExprId, + }, + /// `object.(predicate)`. + XmlFilter { + object: ExprId, + predicate: ExprId, + }, +} + +/// A piece of an XML literal, in source order. +#[derive(Clone, Debug, PartialEq)] +pub enum XmlPart { + /// Markup kept as written. + Text(Vec), + /// `{expression}` in element content: XML values keep their markup, other values are escaped. + Content(ExprId), + /// `{expression}` as an attribute's value. + Attribute(ExprId), + /// `{expression}` as an element or attribute name, its string checked as an XML name. + Name(ExprId), + /// `{expression}` as a run of attributes, its string checked as `name="value"` attributes. + Attributes(ExprId), +} + +/// What stands before `::` in a qualified name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum XmlQualifier { + /// `*::name`: any namespace. + Any, + Expr(ExprId), +} + +/// The name in an E4X name. +#[derive(Clone, Debug, PartialEq)] +pub enum XmlNamePart { + Ident(String), + /// `*`. + Star, + /// `[expression]`. + Computed(ExprId), } #[derive(Clone, Debug, PartialEq)] @@ -218,19 +275,55 @@ pub enum Stmt { Expr(ExprId), Block(Vec), Empty, - If { test: ExprId, consequent: StmtId, alternate: Option }, - DoWhile { body: StmtId, test: ExprId }, - While { test: ExprId, body: StmtId }, - For { init: Option, test: Option, update: Option, body: StmtId }, - ForIn { target: ForInTarget, object: ExprId, body: StmtId }, + If { + test: ExprId, + consequent: StmtId, + alternate: Option, + }, + DoWhile { + body: StmtId, + test: ExprId, + }, + While { + test: ExprId, + body: StmtId, + }, + For { + init: Option, + test: Option, + update: Option, + body: StmtId, + }, + /// `for (… in …)`, or with `each` the E4X `for each (… in …)`, which assigns the values. + ForIn { + target: ForInTarget, + object: ExprId, + body: StmtId, + each: bool, + }, + /// `default xml namespace = expression;`. + DefaultXmlNamespace(ExprId), Continue(Option), Break(Option), Return(Option), - With { object: ExprId, body: StmtId }, - Switch { discriminant: ExprId, cases: Vec }, - Labeled { label: Name, body: StmtId }, + With { + object: ExprId, + body: StmtId, + }, + Switch { + discriminant: ExprId, + cases: Vec, + }, + Labeled { + label: Name, + body: StmtId, + }, Throw(ExprId), - Try { block: Vec, handler: Option, finalizer: Option> }, + Try { + block: Vec, + handler: Option, + finalizer: Option>, + }, Debugger, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index dfb2cf9f7c..f7c21a8d8e 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -132,7 +132,11 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { crate::string_builtins::install(interp)?; crate::number_builtins::install(interp)?; crate::regexp_builtins::install(interp)?; - crate::date_builtins::install(interp) + crate::date_builtins::install(interp)?; + if interp.options.e4x { + crate::xml_builtins::install(interp)?; + } + Ok(()) } // ---- helpers for the built-ins ---- @@ -219,7 +223,7 @@ const UNITS_PER_FUEL: usize = 16; /// against the longest string the heap limit allows, and has its bytes reserved before it is /// added. The buffer's bytes count toward the heap until `finish` or until the native call that /// made the builder returns. Everything the caller still needs must be reachable from the roots. -struct Builder { +pub(crate) struct Builder { units: Vec, /// Code units already reserved and charged to the heap. charged: usize, @@ -228,7 +232,7 @@ struct Builder { } impl Builder { - fn new() -> Self { + pub(crate) fn new() -> Self { Builder { units: Vec::new(), charged: 0, unpaid: 0 } } @@ -260,7 +264,7 @@ impl Builder { Ok(()) } - fn push_units(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult<()> { + pub(crate) fn push_units(&mut self, interp: &mut Interp, units: &[u16]) -> JsResult<()> { self.make_room(interp, units.len())?; self.units.extend_from_slice(units); Ok(()) @@ -268,7 +272,7 @@ impl Builder { /// Appends `units` `count` times. Nothing is written for an empty `units`, however large /// `count` is. - fn push_repeated(&mut self, interp: &mut Interp, units: &[u16], count: u64) -> JsResult<()> { + pub(crate) fn push_repeated(&mut self, interp: &mut Interp, units: &[u16], count: u64) -> JsResult<()> { if units.is_empty() || count == 0 { return Ok(()); } @@ -280,14 +284,14 @@ impl Builder { Ok(()) } - fn push_str(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> { + pub(crate) fn push_str(&mut self, interp: &mut Interp, s: &str) -> JsResult<()> { let units: Vec = s.encode_utf16().collect(); self.push_units(interp, &units) } /// The string built, whose bytes were charged as it grew. From here on the heap counts them /// as the string's. - fn finish(self, interp: &mut Interp) -> Value { + pub(crate) fn finish(self, interp: &mut Interp) -> Value { interp.held_bytes = interp.held_bytes.saturating_sub(2 * self.charged); Value::String(Str::from_units(self.units)) } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 9681d01681..3092530d46 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -145,6 +145,35 @@ pub(crate) enum Op { /// Pushes the completion value, which a `finally` block in script and eval code keeps and /// sets back with `SetCompletion` when it ends normally. GetCompletion, + /// `[qualifier] name` → an E4X name object. + XmlMakeName { + attribute: bool, + qualified: bool, + }, + /// `object name` → the descendants that match. + XmlDescendants, + /// `value` → the string an embedded expression puts in a literal (0 content, 1 attribute + /// value, 2 name, 3 run of attributes). + XmlEscape(u8), + /// The `parts` strings → the XML or XMLList they spell. + XmlLiteral { + parts: u32, + list: bool, + }, + /// `name` → the value of the name on the nearest XML value in scope. + XmlScopeGet, + /// `object` → the filter's state. + XmlFilterStart, + /// `state` → `state item`, or jumps with `state` when the items are used up. + XmlFilterNext(u32), + /// `state value` → `state`, the current item kept when the value is truthy. + XmlFilterTest, + /// `state` → the XMLList of the items kept. + XmlFilterEnd, + /// `iterator name` → `iterator value`: the value under the name a `for each` got. + ForEachValue, + /// `value` → nothing: sets the default XML namespace of the running code. + SetDefaultNamespace, } /// What code is: a function body, a script, or eval code. @@ -274,7 +303,13 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { let table = finally_tables.get(t as usize).ok_or_else(|| format!("finally table {t} out of range"))?; Effect { pops: 2, next: Some(0), jumps: table.iter().map(|&target| (target, 1)).collect() } } - Op::ForInNext(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, + Op::ForInNext(t) | Op::XmlFilterNext(t) => Effect { pops: 1, next: Some(2), jumps: vec![(t, 1)] }, + Op::XmlMakeName { qualified, .. } => e(1 + u32::from(qualified), 1), + Op::XmlDescendants | Op::XmlFilterTest => e(2, 1), + Op::XmlEscape(_) | Op::XmlScopeGet | Op::XmlFilterStart | Op::XmlFilterEnd => e(1, 1), + Op::XmlLiteral { parts, .. } => e(parts, 1), + Op::ForEachValue => e(2, 2), + Op::SetDefaultNamespace => e(1, 0), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 34e64814b6..071e99a60e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -18,7 +18,7 @@ use std::rc::Rc; use crate::ast::{ AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LogicalOp, PropertyValue, Stmt, StmtId, UnaryOp, UpdateOp, - VarDecl, + VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; use crate::bytecode::{Code, CodeKind, Handler, Op, Source, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; @@ -276,7 +276,14 @@ impl<'a> FnCompiler<'a> { } work.extend(block.iter().rev()); } - Stmt::Expr(_) | Stmt::Empty | Stmt::Continue(_) | Stmt::Break(_) | Stmt::Return(_) | Stmt::Throw(_) | Stmt::Debugger => {} + Stmt::Expr(_) + | Stmt::Empty + | Stmt::Continue(_) + | Stmt::Break(_) + | Stmt::Return(_) + | Stmt::Throw(_) + | Stmt::Debugger + | Stmt::DefaultXmlNamespace(_) => {} } } Ok(out) @@ -348,6 +355,11 @@ impl<'a> FnCompiler<'a> { Ok(()) } Stmt::Try { block, handler, finalizer } => self.try_stmt(block, handler.as_ref(), finalizer.as_deref()), + Stmt::DefaultXmlNamespace(e) => { + self.expr(*e)?; + self.emit(Op::SetDefaultNamespace); + Ok(()) + } } } @@ -467,14 +479,14 @@ impl<'a> FnCompiler<'a> { } self.jump(Op::Jump, head); } - Some(Stmt::ForIn { target, object, body }) => return self.for_in(target, *object, *body, labels), + Some(Stmt::ForIn { target, object, body, each }) => return self.for_in(target, *object, *body, labels, *each), _ => return internal("not a loop"), } self.bind(brk); Ok(()) } - fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec) -> CResult<()> { + fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec, each: bool) -> CResult<()> { if let ForInTarget::Var(d) = target { self.var_decls(std::slice::from_ref(d))?; } @@ -485,6 +497,9 @@ impl<'a> FnCompiler<'a> { let brk = self.new_label(); self.bind(head); self.jump(Op::ForInNext, brk); + if each { + self.emit(Op::ForEachValue); + } match target { ForInTarget::Var(d) => { let n = self.var_name(&d.name.name); @@ -827,10 +842,83 @@ impl<'a> FnCompiler<'a> { } } Expr::Paren(inner) => self.expr(*inner)?, + Expr::XmlLiteral { parts, list } => self.xml_literal(parts, *list)?, + Expr::XmlName { attribute, qualifier, name } => self.xml_name(*attribute, *qualifier, name)?, + Expr::XmlScopeName(name) => { + self.expr(*name)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::XmlScopeGet); + } + Expr::XmlDescendants { .. } | Expr::XmlFilter { .. } => self.chain(id)?, } Ok(()) } + fn xml_literal(&mut self, parts: &[XmlPart], list: bool) -> CResult<()> { + for part in parts { + match part { + XmlPart::Text(units) => { + let i = self.string(units); + self.emit(Op::String(i)); + } + XmlPart::Content(e) | XmlPart::Attribute(e) | XmlPart::Name(e) | XmlPart::Attributes(e) => { + self.expr(*e)?; + self.emit(Op::XmlEscape(match part { + XmlPart::Content(_) => 0, + XmlPart::Attribute(_) => 1, + XmlPart::Name(_) => 2, + _ => 3, + })); + } + } + } + self.emit(Op::XmlLiteral { parts: len_u32(parts.len()), list }); + Ok(()) + } + + fn xml_name(&mut self, attribute: bool, qualifier: Option, name: &XmlNamePart) -> CResult<()> { + match qualifier { + Some(XmlQualifier::Any) => self.emit(Op::Null), + Some(XmlQualifier::Expr(e)) => self.expr(e)?, + None => {} + } + match name { + XmlNamePart::Ident(n) => { + let i = self.string(&n.encode_utf16().collect::>()); + self.emit(Op::String(i)); + } + XmlNamePart::Star => { + let i = self.string(&[u16::from(b'*')]); + self.emit(Op::String(i)); + } + XmlNamePart::Computed(e) => self.expr(*e)?, + } + self.emit(Op::XmlMakeName { attribute, qualified: qualifier.is_some() }); + Ok(()) + } + + /// `object.(predicate)` with the object already on the stack: each item is tested with itself + /// as the innermost scope, in list order. + fn xml_filter(&mut self, predicate: ExprId) -> CResult<()> { + self.emit(Op::XmlFilterStart); + let head = self.new_label(); + let done = self.new_label(); + self.bind(head); + let depth = self.depth; + self.jump(Op::XmlFilterNext, done); + self.emit(Op::PushWith); + self.env_depth += 1; + self.expr(predicate)?; + self.emit(Op::PopEnv); + self.env_depth -= 1; + self.emit(Op::XmlFilterTest); + self.jump(Op::Jump, head); + self.bind(done); + self.depth = depth; + self.emit(Op::XmlFilterEnd); + Ok(()) + } + fn args(&mut self, args: &[ExprId]) -> CResult<()> { for a in args { self.expr(*a)?; @@ -869,7 +957,9 @@ impl<'a> FnCompiler<'a> { let mut cur = id; loop { match self.ast.expr(cur) { - Some(Expr::Member { object, .. } | Expr::Index { object, .. }) => { + Some( + Expr::Member { object, .. } | Expr::Index { object, .. } | Expr::XmlDescendants { object, .. } | Expr::XmlFilter { object, .. }, + ) => { suffixes.push(cur); cur = self.ast.unparenthesized(*object); } @@ -910,6 +1000,15 @@ impl<'a> FnCompiler<'a> { self.at(span.start); self.emit(if next_is_call { Op::GetIndexThis } else { Op::GetIndex }); } + Some(Expr::XmlDescendants { name, .. }) => { + self.expr(*name)?; + self.at(span.start); + self.emit(Op::XmlDescendants); + } + Some(Expr::XmlFilter { predicate, .. }) => { + self.at(span.start); + self.xml_filter(*predicate)?; + } Some(Expr::Call { args, .. }) => { let innermost = j + 1 == count; let has_this = if innermost { @@ -1163,9 +1262,15 @@ impl<'a> FnCompiler<'a> { for &(i, label) in &self.patches { let Some(target) = resolve(&self.labels, label) else { return internal("jump to an unplaced label") }; match self.ops.get_mut(i) { - Some(Op::Jump(t) | Op::JumpIfFalse(t) | Op::JumpIfTrue(t) | Op::JumpIfFalseKeep(t) | Op::JumpIfTrueKeep(t) | Op::ForInNext(t)) => { - *t = target - } + Some( + Op::Jump(t) + | Op::JumpIfFalse(t) + | Op::JumpIfTrue(t) + | Op::JumpIfFalseKeep(t) + | Op::JumpIfTrueKeep(t) + | Op::ForInNext(t) + | Op::XmlFilterNext(t), + ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 0dbe949889..dea53c557f 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -228,12 +228,84 @@ pub(crate) enum Class { Math, /// The `JSON` object (section 15.12). Json, + /// An XML value (ECMA-357 section 9.1). + Xml(Box), + /// An XMLList value (ECMA-357 section 9.2). + XmlList(Box), + Namespace(Box), + /// A QName; `attribute` marks an attribute name (ECMA-357 sections 13.3 and 9.3), and + /// `reference` a name made by E4X syntax, which only an XML value can be accessed with. + QName { + name: Box, + attribute: bool, + reference: bool, + }, + /// A `.( )` filter in progress. + XmlFilter(Box), +} + +/// What an XML value is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum XmlKind { + Element, + Attribute, + Text, + Comment, + Pi, +} + +/// A qualified name. `uri` is `None` for a name that matches any namespace. +#[derive(Clone, Debug)] +pub(crate) struct XmlName { + pub(crate) uri: Option, + pub(crate) local: Key, + pub(crate) prefix: Option, +} + +/// A namespace. `prefix` is `None` when it is undefined. +#[derive(Clone, Debug)] +pub(crate) struct XmlNs { + pub(crate) prefix: Option, + pub(crate) uri: Key, +} + +/// An XML value: a node of a tree, linked by object index. +#[derive(Clone)] +pub(crate) struct XmlNode { + pub(crate) kind: XmlKind, + pub(crate) name: Option, + pub(crate) parent: Option, + pub(crate) value: Str, + pub(crate) attrs: Vec, + pub(crate) children: Vec, + pub(crate) ns: Vec, +} + +/// An XMLList value: its items, and the object and name a write to an empty list targets. +#[derive(Clone)] +pub(crate) struct XmlListData { + pub(crate) items: Vec, + pub(crate) target: Option, + pub(crate) target_name: Option<(XmlName, bool)>, +} + +/// The state of a `.( )` filter: the items to test, the next one's position and those kept. +#[derive(Clone)] +pub(crate) struct XmlFilterState { + pub(crate) input: Vec, + pub(crate) pos: usize, + pub(crate) kept: Vec, } impl Class { /// The `[[Class]]` name `Object.prototype.toString` reports. pub(crate) fn name(&self) -> &'static str { match self { + Class::Xml(_) => "XML", + Class::XmlList(_) => "XMLList", + Class::Namespace(_) => "Namespace", + Class::QName { .. } => "QName", + Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", Class::Ordinary | Class::ForIn(_) => "Object", @@ -311,6 +383,14 @@ pub(crate) const ENV_BYTES: usize = 64; pub(crate) const ROPE_BYTES: usize = 48; /// The estimated bytes of each argument a bound function holds. pub(crate) const BOUND_ARG_BYTES: usize = 24; +/// The estimated bytes of an XML node without its names and text. +pub(crate) const XML_NODE_BYTES: usize = 160; +/// The estimated bytes of an XML list without its items. +pub(crate) const XML_LIST_BYTES: usize = 96; +/// The estimated bytes of a reference from an XML node or list to another. +pub(crate) const XML_REF_BYTES: usize = 8; +/// The estimated bytes of a namespace an XML node holds. +pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -572,11 +652,45 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.object.iter().map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); } + Class::Xml(node) => { + work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); + strings.add(&node.value); + if let Some(name) = &node.name { + add_name(name, strings); + } + for ns in &node.ns { + add_ns(ns, strings); + } + extra = XML_NODE_BYTES + XML_REF_BYTES * (node.attrs.len() + node.children.len()) + XML_NS_BYTES * node.ns.len(); + } + Class::XmlList(list) => { + work.extend(list.target.iter().chain(&list.items).map(|o| o.0)); + if let Some((name, _)) = &list.target_name { + add_name(name, strings); + } + extra = XML_LIST_BYTES + XML_REF_BYTES * list.items.len(); + } + Class::Namespace(ns) => add_ns(ns, strings), + Class::QName { name, .. } => add_name(name, strings), + Class::XmlFilter(state) => { + work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); + extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra } +fn add_name(name: &XmlName, strings: &mut StringSizes) { + strings.add_key(&name.local); + name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k)); +} + +fn add_ns(ns: &XmlNs, strings: &mut StringSizes) { + strings.add_key(&ns.uri); + ns.prefix.iter().for_each(|k| strings.add_key(k)); +} + fn trace_env(e: &Env, work: &mut Vec, strings: &mut StringSizes) -> usize { match e { Env::Decl { bindings, outer } => { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index be5760e8f9..ed30993523 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -72,6 +72,12 @@ pub(crate) struct Intrinsics { pub(crate) error_protos: [ObjId; 7], pub(crate) eval: ObjId, pub(crate) throw_type_error: ObjId, + /// The `XML` constructor, which holds the XML settings. + pub(crate) xml_ctor: ObjId, + pub(crate) xml_proto: ObjId, + pub(crate) xml_list_proto: ObjId, + pub(crate) namespace_proto: ObjId, + pub(crate) qname_proto: ObjId, } impl Intrinsics { @@ -89,6 +95,11 @@ impl Intrinsics { error_protos: [o; 7], eval: o, throw_type_error: o, + xml_ctor: o, + xml_proto: o, + xml_list_proto: o, + namespace_proto: o, + qname_proto: o, } } @@ -117,6 +128,11 @@ impl Intrinsics { self.date_proto, self.eval, self.throw_type_error, + self.xml_ctor, + self.xml_proto, + self.xml_list_proto, + self.namespace_proto, + self.qname_proto, ]; v.extend(self.error_protos); v @@ -128,8 +144,8 @@ pub(crate) struct Frame { pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. base: usize, - env: EnvId, - var_env: EnvId, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. env_depth: u32, this: Value, @@ -186,6 +202,8 @@ pub(crate) struct Interp { pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. pub(crate) held: Rc, + /// The global code's default XML namespace URI (ECMA-357 section 12.1). + pub(crate) xml_default_uri: Key, /// Set by the host to end the current slice of a resumable run at the next safe point. pub(crate) pause: Rc>, /// The outermost loop of a resumable run is running ([`crate::Realm::advance`]). @@ -407,6 +425,7 @@ impl Interp { install_error: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), + xml_default_uri: Rc::from(Vec::new()), pause: Rc::default(), in_slice: false, can_wait: Rc::default(), @@ -463,11 +482,11 @@ impl Interp { Ok(()) } - fn frame(&self) -> JsResult<&Frame> { + pub(crate) fn frame(&self) -> JsResult<&Frame> { self.frames.last().ok_or_else(|| Abrupt::Internal("no frame".into())) } - fn frame_mut(&mut self) -> JsResult<&mut Frame> { + pub(crate) fn frame_mut(&mut self) -> JsResult<&mut Frame> { self.frames.last_mut().ok_or_else(|| Abrupt::Internal("no frame".into())) } @@ -475,7 +494,7 @@ impl Interp { self.frames.last().map_or(0, |f| f.base) } - fn pop(&mut self) -> JsResult { + pub(crate) fn pop(&mut self) -> JsResult { if self.stack.len() <= self.base() { return internal("operand stack underflow"); } @@ -483,7 +502,7 @@ impl Interp { } /// The value `n` places below the top (0 is the top). - fn peek(&self, n: usize) -> JsResult { + pub(crate) fn peek(&self, n: usize) -> JsResult { let len = self.stack.len(); match len.checked_sub(n + 1).filter(|&i| i >= self.base()) { Some(i) => self.stack.get(i).cloned().ok_or_else(|| Abrupt::Internal("operand stack underflow".into())), @@ -503,7 +522,7 @@ impl Interp { } /// Replaces the top `n` values with `v`. - fn replace(&mut self, n: usize, v: Value) -> JsResult<()> { + pub(crate) fn replace(&mut self, n: usize, v: Value) -> JsResult<()> { self.drop_n(n)?; self.push(v) } @@ -744,7 +763,7 @@ impl Interp { Ok(None) } - fn jump_to(&mut self, target: u32) -> JsResult<()> { + pub(crate) fn jump_to(&mut self, target: u32) -> JsResult<()> { self.frame_mut()?.pc = target as usize; Ok(()) } @@ -851,6 +870,17 @@ impl Interp { let v = self.frame()?.completion.clone(); self.push(v) } + Op::XmlMakeName { attribute, qualified } => self.op_xml_make_name(attribute, qualified), + Op::XmlDescendants => self.op_xml_descendants(), + Op::XmlEscape(kind) => self.op_xml_escape(kind), + Op::XmlLiteral { parts, list } => self.op_xml_literal(parts, list), + Op::XmlScopeGet => self.op_xml_scope_get(), + Op::XmlFilterStart => self.op_xml_filter_start(), + Op::XmlFilterNext(t) => self.op_xml_filter_next(t), + Op::XmlFilterTest => self.op_xml_filter_test(), + Op::XmlFilterEnd => self.op_xml_filter_end(), + Op::ForEachValue => self.op_for_each_value(), + Op::SetDefaultNamespace => self.op_set_default_namespace(), Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), } } @@ -927,7 +957,7 @@ impl Interp { // ---- variables ---- - fn resolve(&self, name: &[u16]) -> JsResult { + fn resolve(&mut self, name: &[u16]) -> JsResult { let mut cur = Some(self.frame()?.env); while let Some(e) = cur { match self.heap.env(e) { @@ -937,11 +967,11 @@ impl Interp { } cur = *outer; } - Some(Env::Obj { object, with_this, outer }) => { - if self.has_property(*object, name)? { - return Ok(Resolved::Obj { object: *object, with_this: *with_this }); + Some(&Env::Obj { object, with_this, outer }) => { + if self.scope_has(object, name)? { + return Ok(Resolved::Obj { object, with_this }); } - cur = *outer; + cur = outer; } None => return internal("environment out of range"), } @@ -971,7 +1001,7 @@ impl Interp { match r { Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)), Resolved::Obj { object, with_this } => { - let v = self.get_from(object, name, &Value::Object(object))?; + let v = self.get_value(&Value::Object(object), name)?; Ok((v, if with_this { Value::Object(object) } else { Value::Undefined })) } Resolved::Unresolved => Err(self.not_defined(name)), @@ -998,6 +1028,9 @@ impl Interp { _ => Ok(()), } } + Resolved::Obj { object, .. } if self.options.e4x && self.is_xml(&Value::Object(object)) => { + self.put_value(&Value::Object(object), name.clone(), v) + } Resolved::Obj { object, .. } => { let throw = self.strict_writes(); self.put(object, name.clone(), v, throw) @@ -1012,6 +1045,13 @@ impl Interp { fn op_get_var(&mut self, n: u32, with_this: bool) -> JsResult<()> { let name = self.name(n)?; + if with_this + && self.options.e4x + && let Some((f, this)) = self.xml_scope_method(&name)? + { + self.push(f)?; + return self.push(this); + } let (v, this) = self.get_var(&name)?; self.push(v)?; if with_this { self.push(this) } else { Ok(()) } @@ -1188,6 +1228,9 @@ impl Interp { /// `base[k]` for any value (GetValue, section 8.7.1). pub(crate) fn get_value(&mut self, base: &Value, k: &[u16]) -> JsResult { + if self.options.e4x && self.is_xml(base) { + return self.xml_get(base, &Value::String(Str::from_units(k.to_vec()))); + } if let Value::String(s) = base { if is(k, "length") { return Ok(Value::Number(s.len() as f64)); @@ -1534,6 +1577,9 @@ impl Interp { /// PutValue on a property reference (section 8.7.2), whose base may be a primitive. fn put_value(&mut self, base: &Value, k: Key, v: Value) -> JsResult<()> { + if self.options.e4x && self.is_xml(base) { + return self.xml_put(base, &Value::String(Str::from_rc(k)), &v); + } let strict = self.strict(); match base { Value::Object(o) => { @@ -1562,6 +1608,11 @@ impl Interp { fn op_get_member(&mut self, n: u32, with_this: bool) -> JsResult<()> { let name = self.name(n)?; let base = self.peek(0)?; + if with_this && self.options.e4x && self.is_xml(&base) { + let (f, this) = self.xml_method(&base, &name)?; + self.replace(1, f)?; + return self.push(this); + } let v = self.get_value(&base, &name)?; self.replace(1, v)?; if with_this { self.push(base) } else { Ok(()) } @@ -1590,6 +1641,9 @@ impl Interp { fn op_to_key(&mut self) -> JsResult<()> { let k = self.peek(0)?; let base = self.peek(1)?; + if self.is_xml_access(&base, &k) { + return Ok(()); + } self.check_coercible(&base, &[])?; let name = self.to_key(&k)?; self.replace(1, Value::String(Str::from_rc(name))) @@ -1598,6 +1652,16 @@ impl Interp { fn op_get_index(&mut self, with_this: bool) -> JsResult<()> { let k = self.peek(0)?; let base = self.peek(1)?; + if self.is_xml_access(&base, &k) { + if with_this { + let name = self.xml_method_key(&k)?; + let (f, this) = self.xml_method(&base, &name)?; + self.replace(2, f)?; + return self.push(this); + } + let v = self.xml_get(&base, &k)?; + return self.replace(2, v); + } self.check_coercible(&base, &[])?; let name = self.to_key(&k)?; let v = self.get_value(&base, &name)?; @@ -1609,6 +1673,10 @@ impl Interp { let v = self.peek(0)?; let k = self.peek(1)?; let base = self.peek(2)?; + if self.is_xml_access(&base, &k) { + self.xml_put(&base, &k, &v)?; + return self.replace(3, v); + } let name = self.to_key(&k)?; self.put_value(&base, name, v.clone())?; self.replace(3, v) @@ -1617,6 +1685,10 @@ impl Interp { fn op_delete_member(&mut self, n: u32) -> JsResult<()> { let name = self.name(n)?; let base = self.peek(0)?; + if self.options.e4x && self.is_xml(&base) { + let r = self.xml_delete(&base, &Value::String(Str::from_rc(name)))?; + return self.replace(1, Value::Bool(r)); + } let o = self.to_object(&base)?; let strict = self.strict(); let r = self.delete(o, &name, strict)?; @@ -1626,6 +1698,10 @@ impl Interp { fn op_delete_index(&mut self) -> JsResult<()> { let k = self.peek(0)?; let base = self.peek(1)?; + if self.is_xml_access(&base, &k) { + let r = self.xml_delete(&base, &k)?; + return self.replace(2, Value::Bool(r)); + } self.check_coercible(&base, &[])?; let name = self.to_key(&k)?; let o = self.to_object(&base)?; @@ -1652,6 +1728,13 @@ impl Interp { fn op_inc_index(&mut self, prefix: bool, dec: bool) -> JsResult<()> { let k = self.peek(0)?; let base = self.peek(1)?; + if self.is_xml_access(&base, &k) { + let v = self.xml_get(&base, &k)?; + let old = self.to_number(&v)?; + let new = if dec { old - 1.0 } else { old + 1.0 }; + self.xml_put(&base, &k, &Value::Number(new))?; + return self.replace(2, Value::Number(if prefix { new } else { old })); + } self.check_coercible(&base, &[])?; let name = self.to_key(&k)?; let r = self.inc_property(&base, name, prefix, dec)?; @@ -1817,6 +1900,9 @@ impl Interp { /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. fn enumerable_keys(&mut self, id: ObjId) -> JsResult> { + if self.options.e4x && self.is_xml(&Value::Object(id)) { + return self.xml_enumerate(id); + } let mut seen = std::collections::HashSet::new(); let mut out = Vec::new(); let mut cur = Some(id); @@ -1883,7 +1969,7 @@ impl Interp { state.pos += 1; let object = state.object; if let Some(o) = object - && self.has_property(o, &k)? + && self.scope_has(o, &k)? { return self.push(Value::String(Str::from_rc(k))); } @@ -2392,6 +2478,7 @@ impl Interp { Value::Bool(_) => "boolean", Value::Number(_) => "number", Value::String(_) => "string", + Value::Object(_) if self.options.e4x && self.is_xml(v) => "xml", Value::Object(_) if self.is_callable(v) => "function", Value::Object(_) => "object", } @@ -2553,6 +2640,9 @@ impl Interp { BinaryOp::StrictNotEq => Ok(Value::Bool(!strict_eq(a, b))), BinaryOp::Instanceof => self.instance_of(a, b).map(Value::Bool), BinaryOp::In => { + if self.options.e4x && self.is_xml(b) { + return self.xml_has(b, a).map(Value::Bool); + } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_key(a)?; self.has_property(*o, &k).map(Value::Bool) @@ -2565,6 +2655,9 @@ impl Interp { if let (Value::Number(x), Value::Number(y)) = (a, b) { return Ok(Value::Number(x + y)); } + if self.options.e4x && self.is_xml(a) && self.is_xml(b) { + return self.xml_concat(a, b); + } let pa = self.to_primitive(a, Hint::Default)?; let pb = self.to_primitive(b, Hint::Default)?; if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) { @@ -2597,7 +2690,12 @@ impl Interp { } /// The abstract equality comparison (section 11.9.3). - fn loose_eq(&mut self, a: &Value, b: &Value) -> JsResult { + pub(crate) fn loose_eq(&mut self, a: &Value, b: &Value) -> JsResult { + if self.options.e4x + && let Some(r) = self.xml_loose_eq(a, b)? + { + return Ok(r); + } let (mut x, mut y) = (a.clone(), b.clone()); loop { match (&x, &y) { diff --git a/crates/js/src/lexer.rs b/crates/js/src/lexer.rs index 9a6ce8766d..a2a7153dc1 100644 --- a/crates/js/src/lexer.rs +++ b/crates/js/src/lexer.rs @@ -47,13 +47,30 @@ pub struct Lexer<'s> { preprocessor_lines: bool, /// The deepest nesting of groups a regular expression literal may have. max_depth: usize, + /// Read the E4X punctuators `..`, `::` and `@`. + e4x: bool, } impl<'s> Lexer<'s> { /// A lexer of `src`. `preprocessor_lines` turns on the reading of preprocessor lines; /// `max_depth` limits how deeply a regular expression literal's groups may nest. pub fn new(src: &'s [u16], preprocessor_lines: bool, max_depth: usize) -> Self { - Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth } + Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false } + } + + /// The same lexer, reading the E4X punctuators when `e4x` is true. + pub fn with_e4x(mut self, e4x: bool) -> Self { + self.e4x = e4x; + self + } + + /// Moves to source offset `pos`, at the given line and column (both from 1), after the parser + /// has read an XML literal up to there. + pub(crate) fn seek(&mut self, pos: usize, line: u32, column: u32) { + self.pos = pos; + self.line = line; + self.line_start = pos.saturating_sub(column.saturating_sub(1) as usize); + self.blank_line = false; } /// The code unit at `pos`, as a code point value. @@ -578,6 +595,9 @@ impl<'s> Lexer<'s> { fn punct(&mut self) -> Option { let rest = &self.src[self.pos..]; for (spelling, punct) in Punct::ALL { + if !self.e4x && matches!(punct, Punct::DotDot | Punct::ColonColon | Punct::At) { + continue; + } let bytes = spelling.as_bytes(); if rest.len() >= bytes.len() && rest.iter().zip(bytes).all(|(&u, &b)| u == u16::from(b)) { self.pos += bytes.len(); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index bfb5d5c0cb..a8478aa65a 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -37,6 +37,13 @@ //! by [`Limits`]: instructions run (fuel), heap bytes, frames, nested host calls, and an //! [`Interrupt`] flag another thread can set. A run that reaches a limit ends with //! [`RunErrorKind::Limit`], which a script's `try` cannot catch. +//! +//! With [`Options::e4x`], the parser also reads E4X (ECMA-357, second edition, December 2005): +//! XML and XMLList literals, the `.@`, `..`, `::` and `.( )` operators, `for each … in` and +//! `default xml namespace`; the realm then provides `XML`, `XMLList`, `Namespace`, `QName`, +//! `isXMLName` and `setDefaultXMLNamespace`. Without the option, the language and the built-ins are +//! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and +//! serializing them use no native recursion and take fuel for each node. #![forbid(unsafe_code)] pub mod ast; @@ -60,10 +67,12 @@ mod regexp_vm; mod string_builtins; mod token; mod value; +mod xml; +mod xml_builtins; pub use ast::{ AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property, - PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, + PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; @@ -85,11 +94,13 @@ pub struct Options { pub max_depth: usize, /// The most UTF-16 code units a source may hold. pub max_source_units: usize, + /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. + pub e4x: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20 } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } } } @@ -197,3 +208,5 @@ mod interp_tests; mod tests; #[cfg(test)] mod text_tests; +#[cfg(test)] +mod xml_tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index d56b756174..3c2ab3ed30 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -7,6 +7,8 @@ //! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long //! runs of them do not nest at all. +mod xml; + use std::collections::{HashMap, HashSet}; use crate::LineTable; @@ -69,11 +71,13 @@ pub(crate) struct Parser<'s> { /// The next statement stands in a statement list, where a label's body may be a function /// declaration. Read and cleared as each statement starts. in_list: bool, + /// Read E4X syntax. + e4x: bool, } impl<'s> Parser<'s> { pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result { - let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth); + let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x); let placeholder = Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false }; let mut parser = Self { @@ -90,6 +94,7 @@ impl<'s> Parser<'s> { tokens: keep_tokens.then(Vec::new), function_allowed: false, in_list: false, + e4x: options.e4x, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -391,6 +396,7 @@ impl<'s> Parser<'s> { self.semicolon()?; Ok(self.ast.push_stmt(Stmt::Debugger, self.span_from(start))) } + Keyword::Default if self.at_default_xml_namespace() => self.parse_default_xml_namespace(start), _ => { let expr = self.parse_expression(false)?; self.semicolon()?; @@ -488,7 +494,14 @@ impl<'s> Parser<'s> { fn parse_for(&mut self, start: Span) -> Result { self.bump()?; + let each = self.e4x && self.tok.ident() == Some("each"); + if each { + self.bump()?; + } self.expect(Punct::LParen)?; + if each { + return self.parse_for_each(start); + } let init = if self.at(Punct::Semicolon) { None } else if self.at_keyword(Keyword::Var) { @@ -501,14 +514,14 @@ impl<'s> Parser<'s> { if self.ctx.strict && decl.init.is_some() { return Err(self.error_at_token(&self.tok, "a for-in variable cannot have an initializer in strict mode code")); } - return self.parse_for_in(ForInTarget::Var(decl), start); + return self.parse_for_in(ForInTarget::Var(decl), start, false); } Some(ForInit::Var(decls)) } else { let expr = self.parse_expression(true)?; if self.at_keyword(Keyword::In) { self.check_target(expr, "invalid left-hand side in for-in loop")?; - return self.parse_for_in(ForInTarget::Expr(expr), start); + return self.parse_for_in(ForInTarget::Expr(expr), start, false); } Some(ForInit::Expr(expr)) }; @@ -522,12 +535,27 @@ impl<'s> Parser<'s> { } /// The rest of `for (target in object) body`, from `in`. - fn parse_for_in(&mut self, target: ForInTarget, start: Span) -> Result { + fn parse_for_in(&mut self, target: ForInTarget, start: Span, each: bool) -> Result { self.expect_keyword(Keyword::In)?; let object = self.parse_expression(false)?; self.expect(Punct::RParen)?; let body = self.parse_loop_body()?; - Ok(self.ast.push_stmt(Stmt::ForIn { target, object, body }, self.span_from(start))) + Ok(self.ast.push_stmt(Stmt::ForIn { target, object, body, each }, self.span_from(start))) + } + + /// `for each (target in object) body`, from the target (ECMA-357 section 12.3). + fn parse_for_each(&mut self, start: Span) -> Result { + if self.at_keyword(Keyword::Var) { + self.bump()?; + let mut decls = self.parse_var_decls(true)?; + let (Some(decl), true) = (decls.pop(), decls.is_empty()) else { + return Err(self.error_at_token(&self.tok, "for each takes one variable")); + }; + return self.parse_for_in(ForInTarget::Var(decl), start, true); + } + let expr = self.parse_expression(true)?; + self.check_target(expr, "invalid left-hand side in for each loop")?; + self.parse_for_in(ForInTarget::Expr(expr), start, true) } /// `break` or `continue`, with an optional label on the same line, which must name a label @@ -608,7 +636,7 @@ impl<'s> Parser<'s> { let test = if self.at_keyword(Keyword::Case) { self.bump()?; Some(self.parse_expression(false)?) - } else if self.at_keyword(Keyword::Default) { + } else if self.at_keyword(Keyword::Default) && !self.at_default_xml_namespace() { if has_default { return Err(self.error_at_token(&self.tok, "more than one default clause in switch statement")); } @@ -620,7 +648,10 @@ impl<'s> Parser<'s> { }; self.expect(Punct::Colon)?; let mut body = Vec::new(); - while !(self.at_keyword(Keyword::Case) || self.at_keyword(Keyword::Default) || self.at(Punct::RBrace)) { + while !(self.at_keyword(Keyword::Case) + || (self.at_keyword(Keyword::Default) && !self.at_default_xml_namespace()) + || self.at(Punct::RBrace)) + { if self.tok.kind == TokenKind::Eof { return Err(self.unexpected()); } @@ -953,8 +984,13 @@ impl<'s> Parser<'s> { let mut expr = self.parse_primary()?; loop { match &self.tok.kind { + TokenKind::Punct(Punct::DotDot) => expr = self.parse_xml_descendants(expr)?, TokenKind::Punct(Punct::Dot) => { self.bump()?; + if self.e4x && self.at_e4x_member() { + expr = self.parse_xml_member(expr)?; + continue; + } let Some(name) = self.tok.identifier_name().map(str::to_string) else { return Err(self.error_at_token(&self.tok, format!("expected a property name but found {}", describe(&self.tok)))); }; @@ -1050,10 +1086,16 @@ impl<'s> Parser<'s> { self.expect(Punct::RParen)?; return Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start))); } + TokenKind::Punct(Punct::Lt) if self.e4x => return self.parse_xml_literal(), + TokenKind::Punct(Punct::At | Punct::Star) if self.e4x => return self.parse_xml_scope_name(), _ => return Err(self.unexpected()), }; let token = self.bump()?; - Ok(self.ast.push_expr(expr, token.span)) + let id = self.ast.push_expr(expr, token.span); + if self.e4x && self.at(Punct::ColonColon) && matches!(token.kind, TokenKind::Ident(_)) { + return self.parse_xml_qualified_primary(id); + } + Ok(id) } fn parse_function_expression(&mut self) -> Result { @@ -1232,5 +1274,6 @@ fn describe(token: &Token) -> String { TokenKind::String(_) => "string".into(), TokenKind::RegExp { .. } => "regular expression".into(), TokenKind::Directive(_) => "preprocessor line".into(), + TokenKind::XmlLiteral => "XML literal".into(), } } diff --git a/crates/js/src/parser/xml.rs b/crates/js/src/parser/xml.rs new file mode 100644 index 0000000000..e91691a58e --- /dev/null +++ b/crates/js/src/parser/xml.rs @@ -0,0 +1,439 @@ +//! E4X syntax (ECMA-357 sections 11.1 and 12.1): literals, names and the operators on them. +//! +//! A literal is read by scanning the source units with an explicit stack of open tags, so tag +//! nesting uses no native recursion and is held to [`crate::Options::max_depth`]. Only an embedded +//! `{expression}` re-enters the expression parser, and that recursion is counted as any other. + +use super::{Parser, Result, describe}; +use crate::ast::{Expr, ExprId, Stmt, StmtId, XmlNamePart, XmlPart, XmlQualifier}; +use crate::error::TOO_DEEP; +use crate::token::{Keyword, Punct, Span, TokenKind}; +use crate::xml::{is_name_start, is_xml_space, scan_name, scan_reference}; + +const LT: u16 = b'<' as u16; +const GT: u16 = b'>' as u16; +const SLASH: u16 = b'/' as u16; +const AMP: u16 = b'&' as u16; +const LBRACE: u16 = b'{' as u16; +const EQ: u16 = b'=' as u16; +const DQUOTE: u16 = b'"' as u16; +const SQUOTE: u16 = b'\'' as u16; + +/// A literal being read: the markup since the last embedded expression, and the finished parts. +#[derive(Default)] +struct Scan { + text: Vec, + parts: Vec, +} + +impl Scan { + fn flush(&mut self) { + if !self.text.is_empty() { + self.parts.push(XmlPart::Text(std::mem::take(&mut self.text))); + } + } +} + +impl Parser<'_> { + pub(super) fn at_default_xml_namespace(&self) -> bool { + self.e4x && self.peek().is_some_and(|t| t.ident() == Some("xml")) + } + + /// `default xml namespace = expression;`, from `default`. + pub(super) fn parse_default_xml_namespace(&mut self, start: Span) -> Result { + self.expect_keyword(Keyword::Default)?; + self.bump()?; + if self.tok.ident() != Some("namespace") { + return Err(self.error_at_token(&self.tok, format!("expected 'namespace' but found {}", describe(&self.tok)))); + } + self.bump()?; + self.expect(Punct::Eq)?; + let value = self.parse_expression(false)?; + self.semicolon()?; + Ok(self.ast.push_stmt(Stmt::DefaultXmlNamespace(value), self.span_from(start))) + } + + /// After a `.`: the next token starts an E4X name or a filter rather than a property name. + pub(super) fn at_e4x_member(&self) -> bool { + match &self.tok.kind { + TokenKind::Punct(Punct::At | Punct::Star | Punct::LParen) => true, + _ => self.tok.identifier_name().is_some() && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon)), + } + } + + /// `object.@name`, `object.*`, `object.ns::name` or `object.(predicate)`, from the token after + /// the `.`. + pub(super) fn parse_xml_member(&mut self, object: ExprId) -> Result { + let start = self.ast.expr_span(object); + if self.at(Punct::LParen) { + self.bump()?; + let predicate = self.parse_expression(false)?; + self.expect(Punct::RParen)?; + return Ok(self.ast.push_expr(Expr::XmlFilter { object, predicate }, self.span_from(start))); + } + let index = self.parse_xml_name()?; + Ok(self.ast.push_expr(Expr::Index { object, index }, self.span_from(start))) + } + + /// `object..name`, from the `..`. + pub(super) fn parse_xml_descendants(&mut self, object: ExprId) -> Result { + let start = self.ast.expr_span(object); + self.bump()?; + let name = self.parse_xml_name()?; + Ok(self.ast.push_expr(Expr::XmlDescendants { object, name }, self.span_from(start))) + } + + /// `@name`, `*` or `@*` standing alone as a primary expression. + pub(super) fn parse_xml_scope_name(&mut self) -> Result { + let start = self.tok.span; + let name = self.parse_xml_name()?; + Ok(self.ast.push_expr(Expr::XmlScopeName(name), self.span_from(start))) + } + + /// `qualifier::name` as a primary expression, from the `::`; `qualifier` is already read. + pub(super) fn parse_xml_qualified_primary(&mut self, qualifier: ExprId) -> Result { + let start = self.ast.expr_span(qualifier); + self.bump()?; + let name = self.parse_xml_name_part()?; + let qualifier = Some(XmlQualifier::Expr(qualifier)); + let id = self.ast.push_expr(Expr::XmlName { attribute: false, qualifier, name }, self.span_from(start)); + Ok(self.ast.push_expr(Expr::XmlScopeName(id), self.span_from(start))) + } + + /// An E4X name: `@`, then `*`, a name or `[expression]`, with an optional `qualifier::`. + fn parse_xml_name(&mut self) -> Result { + let start = self.tok.span; + let attribute = self.eat(Punct::At)?; + let first_is_star = self.at(Punct::Star); + let qualifier_ident = self.tok.identifier_name().map(str::to_string).filter(|_| matches!(self.tok.kind, TokenKind::Ident(_))); + let first = self.parse_xml_name_part()?; + let (qualifier, name) = if self.at(Punct::ColonColon) { + let qualifier = if first_is_star { + XmlQualifier::Any + } else if let Some(name) = qualifier_ident { + let span = self.span_from(start); + XmlQualifier::Expr(self.ast.push_expr(Expr::Ident(name), span)) + } else { + return Err(self.error_at_token(&self.tok, "expected a namespace name before '::'")); + }; + self.bump()?; + (Some(qualifier), self.parse_xml_name_part()?) + } else { + (None, first) + }; + Ok(self.ast.push_expr(Expr::XmlName { attribute, qualifier, name }, self.span_from(start))) + } + + fn parse_xml_name_part(&mut self) -> Result { + if self.eat(Punct::Star)? { + return Ok(XmlNamePart::Star); + } + if self.eat(Punct::LBracket)? { + let e = self.parse_expression(false)?; + self.expect(Punct::RBracket)?; + return Ok(XmlNamePart::Computed(e)); + } + let Some(name) = self.tok.identifier_name().map(str::to_string) else { + return Err(self.error_at_token(&self.tok, format!("expected an XML name but found {}", describe(&self.tok)))); + }; + self.bump()?; + Ok(XmlNamePart::Ident(name)) + } + + /// An XML or XMLList literal, from its `<` (the current token). + pub(super) fn parse_xml_literal(&mut self) -> Result { + let start = self.tok.span; + let token_slot = self.tokens.as_ref().map(Vec::len); + if let Some(tokens) = &mut self.tokens { + tokens.push(self.tok.clone()); + } + let mut pos = start.start as usize; + let list = self.unit(pos + 1) == Some(GT); + if list { + pos += 2; + } + let mut scan = Scan::default(); + // The name of each open element; `None` when it is computed. + let mut open: Vec>> = Vec::new(); + loop { + if !list && open.is_empty() && !scan.text.is_empty() | !scan.parts.is_empty() { + break; + } + let Some(c) = self.unit(pos) else { return Err(self.xml_error(pos, "unterminated XML literal")) }; + if c == LT { + if self.unit(pos + 1) == Some(SLASH) { + if open.is_empty() { + if list && self.unit(pos + 2) == Some(GT) { + pos += 3; + break; + } + return Err(self.xml_error(pos, "a closing tag has no matching open tag")); + } + pos = self.xml_close_tag(pos, &mut open, &mut scan)?; + } else if self.starts_with(pos, ""); + } + XmlKind::Pi => { + let target = self.xml_node(x)?.name.as_ref().map(|n| n.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); + out.push_str(self, ""); + } + XmlKind::Element => {} + } + let ns_mark = scope.len(); + let node = self.xml_node(x)?; + let declared = node.ns.clone(); + let attrs = node.attrs.clone(); + let name = node.name.clone().ok_or_else(|| Abrupt::Internal("element without a name".into()))?; + self.xml_take_fuel(declared.len().saturating_mul(scope.len() + 1))?; + let mut unnamed = Vec::new(); + for ns in declared { + if ns.prefix.is_none() { + unnamed.push(ns); + } else if !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) { + self.xml_charge(XML_NS_BYTES)?; + scope.push(ns); + } + } + for ns in unnamed { + if !scope.iter().any(|a| a.uri == ns.uri) { + let prefix = fresh_prefix(scope); + self.xml_charge(XML_NS_BYTES)?; + scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri }); + } + } + let prefix = self.out_prefix(&name, scope, false)?; + let mut attr_prefixes = Vec::new(); + for &a in &attrs { + self.use_fuel()?; + let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?; + attr_prefixes.push(self.out_prefix(&an, scope, true)?); + } + out.push_units(self, &[LT])?; + self.write_name(out, &prefix, &name.local)?; + for (&a, attr_prefix) in attrs.iter().zip(&attr_prefixes) { + let an = self.xml_node(a)?; + let local = an.name.as_ref().map(|q| q.local.clone()).unwrap_or_else(|| Rc::from(Vec::new())); + let value = an.value.flat(); + out.push_units(self, &[SPACE])?; + self.write_name(out, attr_prefix, &local)?; + out.push_units(self, &[EQ, DQUOTE])?; + self.write_escaped(out, &value, true)?; + out.push_units(self, &[DQUOTE])?; + } + for at in ns_mark..scope.len() { + let Some(ns) = scope.get(at).cloned() else { break }; + let ns_prefix = ns.prefix.unwrap_or_else(|| Rc::from(Vec::new())); + out.push_str(self, " xmlns")?; + if !ns_prefix.is_empty() { + out.push_units(self, &[COLON])?; + out.push_units(self, &ns_prefix)?; + } + out.push_units(self, &[EQ, DQUOTE])?; + self.write_escaped(out, &ns.uri, true)?; + out.push_units(self, &[DQUOTE])?; + } + let count = self.children_len(x)?; + if count == 0 { + scope.truncate(ns_mark); + return out.push_str(self, "/>"); + } + out.push_units(self, &[GT])?; + let first_is_text = match self.child_at(x, 0)? { + Some(c) => self.xml_kind(c)? == XmlKind::Text, + None => false, + }; + let pretty_children = pretty && (count > 1 || !first_is_text); + let child_indent = if pretty_children { indent.saturating_add(u64::from(settings.indent)) } else { 0 }; + stack.push(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local }); + Ok(()) + } + + fn write_node(&mut self, out: &mut Builder, root: ObjId, indent: u64, settings: &Settings, pretty: bool) -> JsResult<()> { + let mut scope: Vec = Vec::new(); + let mut stack: Vec = Vec::new(); + self.write_enter(out, root, indent, settings, pretty, &mut scope, &mut stack)?; + while let Some(frame) = stack.last_mut() { + let (node, next, child_indent, pretty_children) = (frame.node, frame.next, frame.child_indent, frame.pretty_children); + frame.next += 1; + match self.child_at(node, next)? { + Some(child) => { + if pretty_children { + out.push_units(self, &[LF])?; + } + self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope, &mut stack)?; + } + None => { + let Some(frame) = stack.pop() else { break }; + if frame.pretty_children { + out.push_units(self, &[LF])?; + out.push_repeated(self, &[SPACE], frame.indent)?; + } + out.push_units(self, &[LT, SLASH])?; + self.write_name(out, &frame.prefix, &frame.local)?; + out.push_units(self, &[GT])?; + scope.truncate(frame.ns_mark); + } + } + } + Ok(()) + } + + /// ToXMLString (ECMA-357 section 10.2). `pretty` overrides the setting when it is given. + pub(crate) fn xml_string_of(&mut self, v: &Value, pretty: Option) -> JsResult { + let settings = self.xml_settings()?; + let pretty = pretty.unwrap_or(settings.pretty); + let mut out = Builder::new(); + match self.classify(v) { + Xv::Node(n) => self.write_node(&mut out, n, 0, &settings, pretty)?, + Xv::List(l) => { + for i in 0..self.list_len(l)? { + self.use_fuel()?; + let Some(item) = self.list_at(l, i)? else { break }; + if i > 0 && pretty { + out.push_units(self, &[LF])?; + } + self.write_node(&mut out, item, 0, &settings, pretty)?; + } + } + Xv::Other => return Err(self.not_xml()), + } + let Value::String(s) = out.finish(self) else { return Err(Abrupt::Internal("not a string".into())) }; + Ok(s) + } + + // ---- the parser ---- + + fn syntax(&mut self, message: &str) -> Abrupt { + self.throw(ErrorType::Syntax, message) + } + + fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec, attribute: bool) -> JsResult<()> { + self.xml_text_fuel(to.saturating_sub(from))?; + let mut pos = from; + while pos < to { + let Some(&c) = src.get(pos) else { break }; + if c == AMP { + let Some((after, ch)) = scan_reference(src, pos).filter(|(after, _)| *after <= to) else { + return Err(self.syntax("invalid XML character or entity reference")); + }; + push_char(out, ch); + pos = after; + continue; + } + if pos + 1 < to && starts_pair(c, src.get(pos + 1).copied()) { + out.extend_from_slice(src.get(pos..pos + 2).unwrap_or_default()); + pos += 2; + continue; + } + if !is_xml_char(u32::from(c)) { + return Err(self.syntax("invalid character in XML text")); + } + pos += 1; + match (c, attribute) { + (CR, _) => { + if src.get(pos) == Some(&LF) { + pos += 1; + } + out.push(if attribute { SPACE } else { LF }); + } + (TAB | LF, true) => out.push(SPACE), + _ => out.push(c), + } + } + Ok(()) + } + + fn find_from(src: &[u16], from: usize, needle: &[u16]) -> Option { + src.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|i| from + i) + } + + fn read_name(&mut self, src: &[u16], pos: usize) -> JsResult { + scan_name(src, pos).ok_or_else(|| self.syntax("invalid XML name")) + } + + fn check_units(&mut self, src: &[u16], from: usize, to: usize) -> JsResult<()> { + if valid_xml_units(src.get(from..to).unwrap_or_default()) { + return Ok(()); + } + Err(self.syntax("invalid character in XML text")) + } + + /// Splits `prefix:local`. + fn split_name<'a>(&mut self, raw: &'a [u16]) -> JsResult<(Option<&'a [u16]>, &'a [u16])> { + let Some(colon) = raw.iter().position(|&c| c == COLON) else { return Ok((None, raw)) }; + let (prefix, rest) = raw.split_at(colon); + let local = rest.get(1..).unwrap_or_default(); + if !is_ncname(prefix) || !is_ncname(local) { + return Err(self.syntax("invalid XML qualified name")); + } + Ok((Some(prefix), local)) + } + + fn resolve_prefix(&mut self, prefix: &[u16], own: &[XmlNs], open: &[ObjId]) -> JsResult> { + if prefix == key("xml").as_ref() { + return Ok(Some(key(XML_URI))); + } + self.xml_take_fuel(own.len() + open.len() + 1)?; + if let Some(ns) = prefix_in_scope(own, prefix) { + return Ok(Some(ns.uri.clone())); + } + for &e in open.iter().rev() { + let node = self.xml_node(e)?; + let len = node.ns.len(); + if let Some(ns) = prefix_in_scope(&node.ns, prefix) { + return Ok(Some(ns.uri.clone())); + } + self.xml_take_fuel(len / UNITS_PER_FUEL)?; + } + Ok(None) + } + + fn place_parsed(&mut self, node: ObjId, open: &[ObjId], roots: &mut Vec) -> JsResult<()> { + if let Some(&top) = open.last() { + self.xml_charge_link(node)?; + self.xml_node_mut(top)?.children.push(node); + self.xml_node_mut(node)?.parent = Some(top); + } else { + self.xml_keep(node); + self.xml_charge(XML_REF_BYTES)?; + roots.push(node); + } + Ok(()) + } + + fn flush_text(&mut self, text: &mut Vec, ignore_whitespace: bool, open: &[ObjId], roots: &mut Vec) -> JsResult<()> { + if text.is_empty() { + return Ok(()); + } + if ignore_whitespace && text.iter().all(|&c| is_xml_space(c)) { + text.clear(); + return Ok(()); + } + let t = self.new_text_node(Str::from_units(std::mem::take(text)), None)?; + self.place_parsed(t, open, roots) + } + + fn parse_open_tag( + &mut self, + src: &[u16], + pos: usize, + open: &mut Vec, + names: &mut Vec<(usize, usize)>, + roots: &mut Vec, + ) -> JsResult { + if open.len() >= self.options.max_depth { + return Err(self.syntax(TOO_DEEP)); + } + let name_start = pos + 1; + let name_end = self.read_name(src, name_start)?; + let raw_name = src.get(name_start..name_end).unwrap_or_default(); + let (elem_prefix, elem_local) = self.split_name(raw_name)?; + let mut at = name_end; + let mut raw_attrs: Vec<(usize, usize, Vec)> = Vec::new(); + let closes = loop { + let before = at; + while src.get(at).copied().is_some_and(is_xml_space) { + at += 1; + } + match src.get(at).copied() { + None => return Err(self.syntax("unterminated XML tag")), + Some(SLASH) if src.get(at + 1) == Some(>) => { + at += 2; + break true; + } + Some(GT) => { + at += 1; + break false; + } + Some(_) if at == before => return Err(self.syntax("expected white space before an attribute")), + Some(_) => { + self.use_fuel()?; + let end = self.read_name(src, at)?; + let mut p = end; + while src.get(p).copied().is_some_and(is_xml_space) { + p += 1; + } + if src.get(p) != Some(&EQ) { + return Err(self.syntax("expected '=' after an attribute name")); + } + p += 1; + while src.get(p).copied().is_some_and(is_xml_space) { + p += 1; + } + let quote = match src.get(p).copied() { + Some(q @ (DQUOTE | SQUOTE)) => q, + _ => return Err(self.syntax("expected a quoted attribute value")), + }; + let value_start = p + 1; + let Some(value_end) = Self::find_from(src, value_start, &[quote]) else { + return Err(self.syntax("unterminated attribute value")); + }; + if src.get(value_start..value_end).is_some_and(|v| v.contains(<)) { + return Err(self.syntax("'<' cannot appear in an attribute value")); + } + let mut value = Vec::new(); + self.decode_into(src, value_start, value_end, &mut value, true)?; + raw_attrs.push((at, end, value)); + at = value_end + 1; + } + } + }; + self.xml_charge(XML_NS_BYTES.saturating_mul(raw_attrs.len()))?; + let mut ns: Vec = Vec::new(); + let mut seen_decl: HashSet> = HashSet::new(); + for (start, end, value) in &raw_attrs { + let raw = src.get(*start..*end).unwrap_or_default(); + if raw == key("xmlns").as_ref() { + if !ns_binding_allowed(&[], value) { + return Err(self.syntax(RESERVED_NS_BINDING)); + } + if !seen_decl.insert(Vec::new()) { + return Err(self.syntax("a namespace is declared twice")); + } + ns.push(XmlNs { prefix: Some(Rc::from(Vec::new())), uri: Rc::from(value.as_slice()) }); + } else if let (Some(p), local) = self.split_name(raw)? + && p == key("xmlns").as_ref() + { + if value.is_empty() { + return Err(self.syntax("a namespace prefix cannot be declared with an empty URI")); + } + if !ns_binding_allowed(local, value) { + return Err(self.syntax(RESERVED_NS_BINDING)); + } + if !seen_decl.insert(local.to_vec()) { + return Err(self.syntax("a namespace is declared twice")); + } + ns.push(XmlNs { prefix: Some(Rc::from(local)), uri: Rc::from(value.as_slice()) }); + } + } + let uri = match elem_prefix { + Some(p) => match self.resolve_prefix(p, &ns, open)? { + Some(u) => u, + None => return Err(self.syntax("an XML name uses an undeclared namespace prefix")), + }, + None => match self.resolve_prefix(&[], &ns, open)? { + Some(u) => u, + None => self.xml_default_uri()?, + }, + }; + let name = XmlName { uri: Some(uri), local: Rc::from(elem_local), prefix: Some(Rc::from(elem_prefix.unwrap_or_default())) }; + let element = self.new_xml_node(XmlNode { + kind: XmlKind::Element, + name: Some(name), + parent: None, + value: Str::from(""), + attrs: Vec::new(), + children: Vec::new(), + ns, + })?; + self.place_parsed(element, open, roots)?; + let mut unique: HashSet<(Key, Vec)> = HashSet::new(); + for (start, end, value) in raw_attrs { + self.use_fuel()?; + let raw = src.get(start..end).unwrap_or_default(); + let (prefix, local) = self.split_name(raw)?; + if raw == key("xmlns").as_ref() || prefix.is_some_and(|p| p == key("xmlns").as_ref()) { + continue; + } + let (auri, stored_prefix): (Key, Key) = match prefix { + Some(p) => { + let own = self.xml_node(element)?.ns.clone(); + match self.resolve_prefix(p, &own, open)? { + Some(u) => (u, Rc::from(p)), + None => return Err(self.syntax("an XML name uses an undeclared namespace prefix")), + } + } + None => (Rc::from(Vec::new()), Rc::from(Vec::new())), + }; + if !unique.insert((auri.clone(), local.to_vec())) { + return Err(self.type_error("an XML element has two attributes with the same name")); + } + let a = self.new_xml_node(XmlNode { + kind: XmlKind::Attribute, + name: Some(XmlName { uri: Some(auri), local: Rc::from(local), prefix: Some(stored_prefix) }), + parent: Some(element), + value: Str::from_units(value), + attrs: Vec::new(), + children: Vec::new(), + ns: Vec::new(), + })?; + self.xml_charge_link(a)?; + self.xml_node_mut(element)?.attrs.push(a); + } + if !closes { + open.push(element); + names.push((name_start, name_end)); + } + Ok(at) + } + + fn parse_close_tag(&mut self, src: &[u16], pos: usize, open: &mut Vec, names: &mut Vec<(usize, usize)>) -> JsResult { + let name_start = pos + 2; + let name_end = self.read_name(src, name_start)?; + let mut at = name_end; + while src.get(at).copied().is_some_and(is_xml_space) { + at += 1; + } + if src.get(at) != Some(>) { + return Err(self.syntax("expected '>' at the end of a closing tag")); + } + let Some((open_start, open_end)) = names.pop() else { + return Err(self.syntax("a closing tag has no matching open tag")); + }; + if src.get(open_start..open_end) != src.get(name_start..name_end) { + return Err(self.syntax("the closing tag does not match the open tag")); + } + open.pop(); + Ok(at + 1) + } + + /// Parses XML text into nodes, kept reachable through the temporary roots until the caller's + /// scope ends. + pub(crate) fn xml_parse(&mut self, source: &[u16]) -> JsResult> { + let mut held = HeldBytes::new(self); + held.add(self, string_bytes(source.len()).saturating_mul(2))?; + let settings = self.xml_settings()?; + let mut src = source; + let mut offset_start = 0; + while src.get(offset_start).copied().is_some_and(is_xml_space) { + offset_start += 1; + } + if src.get(offset_start..).is_some_and(|r| r.starts_with(&parser_units("")) else { + return Err(self.syntax("unterminated XML declaration")); + }; + src = src.get(end + 2..).unwrap_or_default(); + } + let mut pos = 0; + let mut roots = Vec::new(); + let mut open: Vec = Vec::new(); + let mut names: Vec<(usize, usize)> = Vec::new(); + let mut text: Vec = Vec::new(); + while let Some(&c) = src.get(pos) { + self.use_fuel()?; + if c != LT { + let end = Self::find_from(src, pos, &[LT]).unwrap_or(src.len()); + let section_end = parser_units("]]>"); + if src.get(pos..end).is_some_and(|run| run.windows(3).any(|w| w == section_end)) { + return Err(self.syntax("']]>' cannot appear in XML text")); + } + self.decode_into(src, pos, end, &mut text, false)?; + pos = end; + continue; + } + let rest = src.get(pos..).unwrap_or_default(); + if rest.starts_with(&parser_units("")) else { + return Err(self.syntax("unterminated CDATA section")); + }; + self.xml_text_fuel(end - pos)?; + self.check_units(src, pos + 9, end)?; + text.extend_from_slice(src.get(pos + 9..end).unwrap_or_default()); + pos = end + 3; + continue; + } + self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?; + if rest.starts_with(&parser_units("&y]]>');"; + truth(&format!("{src} t.children().length() === 5")); + truth(&format!("{src} t.children()[0].nodeKind() === 'text' && t.children()[0].toString() === 'x'")); + truth(&format!("{src} t.children()[1].nodeKind() === 'comment' && t.comments().length() === 1")); + truth(&format!("{src} t.children()[2].nodeKind() === 'processing-instruction' && t.children()[2].name().localName === 'pi'")); + truth(&format!("{src} t.children()[3].nodeKind() === 'element'")); + truth(&format!("{src} t.children()[4].toString() === '&y'")); + truth(&format!("{src} t.@p == '1' && t.@q == '<' && t.attributes().length() === 2 && t.@p.nodeKind() === 'attribute'")); +} + +#[test] +fn serialization_matches_the_fixed_markup() { + assert_eq!(string("(1).toXMLString()"), "\n 1\n \n"); + assert_eq!(string("XML.prettyPrinting = false; (1).toXMLString()"), "1"); + assert_eq!(string("XML.prettyIndent = 4; ().toXMLString()"), "\n \n"); + assert_eq!(string("(<&>).toXMLString()"), "<&>"); + assert_eq!(string("().toXMLString()"), "\n \n"); + assert_eq!(string("(<>).toXMLString()"), "\n"); +} + +#[test] +fn embedded_expressions_are_escaped_by_position() { + assert_eq!(string("var v = '<&>'; ({v}).toXMLString()"), "<&>"); + assert_eq!(string("var v = 'a\"<'; ().toXMLString()"), ""); + assert_eq!(string("var n = 'tag'; (<{n} x=\"1\">t).toXMLString()"), "t"); + assert_eq!(string("var c = 1; ({c}).toXMLString()"), "\n 1\n"); + assert_eq!(string("var a = 'p=\"1\"'; ().toXMLString()"), ""); + truth("var i = 0; var x = {i++}{i++}; x == '01' && i === 2"); + truth("var o = {t: 1}; ({o.t ? 'y' : 'n'}) == 'y'"); + truth("({'}'}) == '}'"); + truth("({1 < 2}) == 'true'"); +} + +#[test] +fn a_computed_tag_name_cannot_add_markup() { + for src in [ + r#"(<{'a x="1"'}/>)"#, + "(<{'a>)", + "(t)", + "(<{''}/>)", + "(<{'1a'}/>)", + "()", + r#"()"#, + ] { + assert_eq!(thrown_name(src), "SyntaxError", "{src}"); + } +} + +#[test] +fn a_computed_name_may_be_any_xml_name() { + assert_eq!(string("(<{'a.b-c'}/>).toXMLString()"), ""); + assert_eq!(string("(<{'tag'}>t).toXMLString()"), "t"); + assert_eq!(string("var n = 'n:b'; (<{n}/>).toXMLString()"), "\n \n"); +} + +#[test] +fn a_computed_attribute_name_matches_the_standard_example() { + let vars = "var tagname = 'name', attributename = 'id', attributevalue = 5, content = 'Fred';"; + let literal = "<{tagname} {attributename}={attributevalue}>{content}"; + assert_eq!(string(&format!("{vars} ({literal}).toXMLString()")), "Fred"); + assert_eq!(string(r#"var a = 'id'; ().toXMLString()"#), ""); +} + +#[test] +fn a_computed_attribute_run_cannot_add_markup() { + for src in [ + r#"()"#, + r#"(<>)"#, + "()", + "()", + r#"()"#, + r#"()"#, + ] { + assert_eq!(thrown_name(src), "SyntaxError", "{src}"); + } +} + +#[test] +fn a_computed_attribute_run_may_hold_any_attributes() { + truth( + r#"var a = " a=\"1\"\n b = '>' "; var x = ; x.@a == '1' && x.@b == '>' && x.attributes().length() === 2 && x.children().length() === 0"#, + ); + assert_eq!(string("().toXMLString()"), ""); + assert_eq!(string("().toXMLString()"), ""); +} + +// ---- selectors and updates ---- + +#[test] +fn selectors_return_the_documented_lists() { + let s = |rest: &str| truth(&format!("{BOOKS} {rest}")); + s("xml.book.length() === 4 && xml.book[0].author == 'Farmer'"); + s("xml.book[0].@category == 'COOKING' && xml.book.@category.length() === 4"); + s("xml.book[1].@category.toString() === 'CHILDREN'"); + s("xml.*.length() === 4 && xml.book[0].*.length() === 3"); + s("xml.book[0].@*.length() === 1"); + s("xml.nothing.length() === 0 && xml.@nothing.length() === 0"); + s("xml..title.length() === 4 && xml..title == xml.descendants('title')"); + s("xml..@lang.length() === 4 && xml..@category.length() === 4"); + s("xml.book.(@category == 'CHILDREN').length() === 2"); + s("xml.book.(year > 1899).title.length() === 2"); + s("xml.book.(author == 'Baum').title == 'Oz'"); + s("xml.*::book.length() === 4"); + s("var n = null; xml.n::book.length() === 4"); + s("xml['book'].length() === 4 && xml.book[0]['author'] == 'Farmer' && xml.book[0]['@category'] == 'COOKING'"); + s("var k = 'category'; xml.book[0].@[k] == 'COOKING'"); +} + +#[test] +fn the_top_sample_has_three_children_two_elements_and_seven_descendants() { + truth(&format!("{TOP} x.children().length() === 3")); + truth(&format!("{TOP} x.elements().length() === 2")); + truth(&format!("{TOP} x.descendants().length() === 7")); +} + +#[test] +fn a_filter_tests_each_item_once_in_order() { + truth( + "var seen = []; var l = <>123; var r = l.(seen.push(toString()), true); seen.join() === '1,2,3' && r.length() === 3", + ); + truth("().(false).length() === 0"); + assert_eq!(thrown_name("({}).(1)"), "TypeError"); + assert_eq!(thrown_name("var o = {}; o.@a"), "TypeError"); + assert_eq!(thrown_name("var o = {}; o..a"), "TypeError"); +} + +#[test] +fn assignment_and_delete_update_the_tree() { + let s = |rest: &str| truth(&format!("{BOOKS} {rest}")); + s( + "xml.book[2].author = 'Dodgeson'; xml.book[2].author.length() === 1 && xml.book[2].author == 'Dodgeson' && xml.book[2].*[1].localName() === 'author'", + ); + s("xml.book[2].author[0] = 'First'; xml.book[2].author.length() === 3 && xml.book[2].author[0] == 'First'"); + s("xml.book[1].year = 1901; xml.book[1].year == '1901'"); + s("xml.book[1].rating = '*****'; xml.book[1].*[3].localName() === 'rating' && xml.book[1].rating == '*****'"); + s("xml.book[1].@category = 'FANTASY'; xml.book[1].@category == 'FANTASY'"); + s("xml.book[1].@added = 'y'; xml.book[1].@added == 'y' && xml.book[1].attributes().length() === 2"); + s("delete xml.book[2].author; xml.book[2].author.length() === 0"); + s("delete xml.book[2].author[1]; xml.book[2].author.length() === 2 && xml.book[2].author[1] == 'C'"); + s("delete xml.book[2].@category; xml.book[2].@category.length() === 0"); + s("xml.book[0] = ; xml.book.length() === 4 && xml.book[0].@id == 'new' && xml.book[0].parent() === xml"); + assert_eq!(thrown_name("var x = ; x[0] = 1"), "TypeError"); + assert_eq!(thrown_name("var x = ; delete x[0]"), "TypeError"); + truth("var x = ; x.b.c = 'd'; x.b.c == 'd'"); + truth("var x = ; x.b += 'v'; x.b == 'v'"); + truth("var x = 1; x.n++; x.n == '2'"); + truth("var x = ; x.@t++; x.@t == '2'"); +} + +#[test] +fn operators_follow_the_standard() { + truth("var l = + ; typeof l === 'xml' && l.length() === 2"); + truth("var l = <> + ; l.length() === 2"); + truth("typeof === 'xml' && typeof <> === 'xml' && typeof new Namespace() === 'object'"); + truth("1 == 1 && !(1 == 2)"); + truth(" == "); + truth("1 == '1' && '1' == 1 && 1 == 1"); + truth("!(01 == 1) && true == true && null == null && undefined == undefined && !(x == null)"); + truth("<> == <> && !(<> == <>)"); + truth("new XMLList() == undefined"); + truth("new Namespace('p', 'u') == new Namespace('q', 'u') && new QName('u', 'a') == new QName('u', 'a')"); + truth("var s = ''; for (var i in <>) s += i; s === '01'"); + truth("var s = ''; for each (var v in <>12) s += v; s === '12'"); + truth("var s = ''; for each (var v in [3, 4]) s += v; s === '34'"); + truth("var s = ''; for each (var v in 7) s += v; s === '7'"); + truth("var x = 5; x.length == '5' && x.length() === 1"); + truth("var x = abc; x.charAt(1) === 'b'"); + truth("var l = <>abc; l.toUpperCase() === 'ABC'"); + assert_eq!(thrown_name("().noSuchMethod()"), "TypeError"); + assert_eq!(thrown_name("(<>).nodeKind()"), "TypeError"); + truth("with (1) { b == '1' }"); +} + +#[test] +fn the_default_namespace_is_scoped_to_the_function() { + truth( + "var ns = new Namespace('u'); default xml namespace = ns; var x = ; x.name().uri === 'u' && x.b.length() === 1 && x.b.name().uri === 'u'", + ); + truth("default xml namespace = 'u'; ().@p.name().uri === ''"); + truth( + "function f() { default xml namespace = 'u'; return ().name().uri; } \ + f() === 'u' && ().name().uri === ''", + ); + truth("function f() { default xml namespace = 'u'; return function () { return ().name().uri; }; } f()() === 'u'"); + truth("setDefaultXMLNamespace(new Namespace('p', 'v')); ().name().uri === 'v' && new QName('b').uri === 'v'"); + truth("default xml namespace = 'u'; new QName('a').uri === 'u' && new QName('*').uri === null"); + truth("var x = ; x.b.length() === 0"); + truth("var x = ; var n = new Namespace('u'); x.n::b.length() === 1"); + truth( + "var soap = new Namespace('http://schemas.xmlsoap.org/soap/envelope/'); default xml namespace = soap; \ + var m = ; \ + m.@soap::encodingStyle == 'e' && m.Body.length() === 1", + ); +} + +// ---- built-ins ---- + +#[test] +fn the_constructors_keep_identity_or_copy_as_specified() { + truth("XML().nodeKind() === 'text' && XML(null) == '' && XML(undefined) == ''"); + truth("var x = ; XML(x) === x && new XML(x) !== x && new XML(x) == x"); + truth("var l = <>; XML(l) === l[0]"); + assert_eq!(thrown_name("XML(<>)"), "TypeError"); + assert_eq!(thrown_name("XML('')"), "SyntaxError"); + assert_eq!(thrown_name("XML('')"), "SyntaxError"); + truth("XMLList().length() === 0 && XMLList('').length() === 2"); + truth("var l = <>; XMLList(l) === l && new XMLList(l) !== l && new XMLList(l)[0] === l[0]"); + truth("var n = new Namespace('p', 'u'); Namespace(n) === n && new Namespace(n) !== n && new Namespace(n).prefix === 'p'"); + truth("var n = new Namespace(); n.prefix === '' && n.uri === '' && n.toString() === ''"); + truth("var n = new Namespace('u'); n.prefix === undefined && n.uri === 'u'"); + truth("new Namespace('1bad', 'u').prefix === undefined"); + assert_eq!(thrown_name("new Namespace('p', '')"), "TypeError"); + truth("var q = new QName('u', 'a'); QName(q) === q && new QName(q) !== q && q.uri === 'u' && q.localName === 'a'"); + truth("var q = new QName(new Namespace('p', 'u'), 'a'); q.uri === 'u' && q.toString() === 'u::a'"); + truth("new QName('*').toString() === '*::*' && new QName(null, 'a').uri === null && new QName().localName === ''"); + truth("isXMLName('abc') && isXMLName('a-b') && !isXMLName('a.b') && !isXMLName('$a') && !isXMLName('1a') && !isXMLName('')"); + truth("().localName() === 'a.b'"); +} + +#[test] +fn the_settings_are_per_realm_and_restore() { + truth( + "var d = XML.defaultSettings(); !d.ignoreComments && !d.ignoreProcessingInstructions && d.ignoreWhitespace && d.prettyPrinting && d.prettyIndent === 2", + ); + truth("var s = XML.settings(); XML.prettyIndent = 7; XML.settings().prettyIndent === 7 && (XML.setSettings(s), XML.prettyIndent === 2)"); + truth("XML.prettyIndent = 7; XML.setSettings(); XML.prettyIndent === 2"); + truth("XML.setSettings({ignoreWhitespace: false, prettyIndent: 'bad'}); !XML.ignoreWhitespace && XML.prettyIndent === 2"); + truth("(new XML('')).children().length() === 2"); + truth("XML.ignoreComments = true; XML.ignoreProcessingInstructions = true; (new XML('')).children().length() === 0"); + truth("XML.ignoreWhitespace = false; (new XML(' ')).children().length() === 3"); + truth("(new XML(' ')).children().length() === 1"); + truth("(new XML(' t ')).toString() === ' t '"); + let mut first = realm(); + first.run("XML.prettyIndent = 9").unwrap(); + assert_eq!(realm().run("XML.prettyIndent"), Ok(JsValue::Number(2.0))); +} + +#[test] +fn the_xml_methods_behave_as_specified() { + truth("var x = ; x.appendChild() === x && x.*[1].localName() === 'c' && x.c.parent() === x"); + truth("var x = ; x.appendChild('t'); x.text() == 't'"); + truth("var x = ; x.prependChild(); x.*[0].localName() === 'c'"); + truth("var x = ; x.insertChildAfter(x.b[0], ); x.*[1].localName() === 'c'"); + truth("var x = ; x.insertChildBefore(x.d[0], ); x.*[1].localName() === 'c'"); + truth("var x = ; x.insertChildAfter(null, ); x.*[0].localName() === 'c'"); + truth("var x = ; x.insertChildBefore(null, ); x.*[1].localName() === 'c'"); + truth("var x = ; x.insertChildAfter(, ) === undefined && x.*.length() === 1"); + truth("var x = ; x.c[0].childIndex() === 1 && x.childIndex() === -1"); + truth("var x = ; x.attribute('p') == '1' && x.attributes().length() === 1"); + truth("var x = t; x.child('b').length() === 1 && x.child(1) == 't' && x.child(9).length() === 0"); + truth("var x = ; x.copy() !== x && x.copy() == x && x.copy().parent() === null && x.b.copy().parent() === undefined"); + truth("var c = ().b[0].copy(); c.parent() === null"); + truth("var x = ; x.contains()"); + truth("var x = ; x.hasOwnProperty('b') && !x.hasOwnProperty('c') && x.hasComplexContent() && !x.hasSimpleContent()"); + truth("var x = t; !x.hasComplexContent() && x.hasSimpleContent() && x.length() === 1"); + truth( + "var x = ; x.b[0].inScopeNamespaces().length === 1 && x.namespaceDeclarations()[0].prefix === 'p' && x.b[0].namespaceDeclarations().length === 0", + ); + truth("var x = ; x.namespace('p').uri === 'u' && x.namespace('q') === undefined && x.namespace().uri === ''"); + truth("var x = ; x.addNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'"); + truth("var x = ; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p') === undefined"); + truth("var x = ; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'"); + truth("var x = ; x.name().localName === 'a' && x.localName() === 'a'"); + truth("(t).*[0].name() === null && (t).*[0].localName() === null"); + truth("var x = 1; x.b[0].appendChild('2'); x.b[0].*.length() === 2 && (x.normalize(), x.b[0].*.length() === 1) && x.b == '12'"); + truth("var x = ; x.b[0].parent() === x && x.parent() === null"); + truth("var x = ; x.processingInstructions().length() === 2 && x.processingInstructions('r').length() === 1"); + truth("var x = ; x.propertyIsEnumerable(0) && !x.propertyIsEnumerable(1)"); + truth("var x = ; x.replace('b', ); x.*.length() === 2 && x.*[0].localName() === 'z' && x.*[1].localName() === 'c'"); + truth("var x = ; x.replace(0, 't'); x.* == 't'"); + truth("var x = ; x.replace('nothing', ) === x && x.b.length() === 1"); + truth("var x = ; x.setChildren( + ) === x && x.*.length() === 2 && x.c.length() === 1"); + truth("var x = ; x.setLocalName('b'); x.localName() === 'b'"); + truth("var x = ; x.setName('b'); x.localName() === 'b'"); + truth("var x = ; x.setNamespace(new Namespace('p', 'u')); x.name().uri === 'u' && x.toXMLString() === ''"); + assert_eq!(thrown_name("().setLocalName('1 x')"), "TypeError"); + assert_eq!(thrown_name("().setName('a b')"), "TypeError"); + assert_eq!(string("(1).toString()"), "1"); + assert_eq!(string("().toString()"), "\n \n"); + truth("var x = ; x.valueOf() === x"); + truth("().xpath === undefined || ().xpath.length() === 0"); + truth("var x = ; x.b.attributes !== undefined"); +} + +#[test] +fn the_xml_list_methods_work_item_by_item() { + let l = "var l = <>s;"; + truth(&format!("{l} l.length() === 2 && l.attribute('p').length() === 2 && l.attributes().length() === 2")); + truth(&format!("{l} l.child('x').length() === 1 && l.children().length() === 4 && l.child(0).length() === 2")); + truth(&format!("{l} l.comments().length() === 1 && l.elements().length() === 2 && l.text() == 's'")); + truth(&format!("{l} l.descendants().length() === 4")); + truth(&format!("{l} l.contains(s) && !l.contains()")); + truth(&format!("{l} l.copy()[0] !== l[0] && l.copy() == l")); + truth(&format!("{l} l.hasOwnProperty(0) && !l.hasOwnProperty(5) && l.propertyIsEnumerable(1) && !l.propertyIsEnumerable(2)")); + truth(&format!("{l} l.hasComplexContent() && !l.hasSimpleContent()")); + truth(&format!("{l} l.parent() === undefined && l.valueOf() === l")); + truth("var x = ; x.*.parent() === x"); + truth("new XMLList().hasSimpleContent() && !new XMLList().hasComplexContent() && new XMLList().parent() === undefined"); + truth("var l = <>12; l.normalize() === l && l.toString() === '1\\n2'"); + truth("var r = 1; var l = r.a; l[0] = 2; r.a == '2' && l[0] == '2'"); + truth("var r = 1; r.a[1] = 'n'; r.a.length() === 2 && r.a[1] == 'n' && r.*[1].parent() === r"); + truth("var r = 1; var list = r.b; list.c = 'v'; r.b.c == 'v'"); + truth("var r = ; r.a.@t[0] = '2'; r.a.@t == '2'"); + truth("var r = 1; r.a[0] = <>

; r.*.length() === 3 && r.*[0].localName() === 'p'"); +} + +#[test] +fn inserting_a_node_moves_it_out_of_its_old_parent() { + truth("var b = ; var a = ; var c = b.c[0]; a.appendChild(c); b.c.length() === 0 && a.c.length() === 1 && c.parent() === a"); + truth("var a = ; a.appendChild(a.b[0]); a.*.length() === 2 && a.*[0].localName() === 'c'"); + truth("var b = ; var a = ; var c = b.c[0]; a.appendChild(c); c.appendChild(b); a..*.length() === 2 && b.parent() === c"); +} + +#[test] +fn namespaces_survive_serialization() { + assert_eq!(string("var x = ; x.toXMLString()"), "\n \n"); + assert_eq!(string("var x = ; x.toXMLString()"), ""); + truth("var x = ; var y = new XML(x.toXMLString()); x == y && y.*[0].name().uri === 'u'"); + truth( + "var q = new QName(new Namespace('u'), 'a'); var x = new XML(''); x.appendChild(); x.*[0].setName(q); (new XML(x.toXMLString())).*[0].name().uri === 'u'", + ); + truth( + "var x = ; x.@[new QName('u', 'b')] = '1'; var y = new XML(x.toXMLString()); y.attributes()[0].name().uri === 'u' && y.attributes()[0] == '1'", + ); +} + +const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; +const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; + +#[test] +fn markup_cannot_declare_a_reserved_namespace_binding() { + let declarations = [ + "xmlns:xml='wrong'".to_string(), + "xmlns:xmlns='u'".to_string(), + format!("xmlns:xmlns='{XMLNS_NS}'"), + format!("xmlns:p='{XML_NS}'"), + format!("xmlns:p='{XMLNS_NS}'"), + format!("xmlns='{XML_NS}'"), + format!("xmlns='{XMLNS_NS}'"), + ]; + for declaration in declarations { + assert_eq!(thrown_name(&format!("")), "SyntaxError", "{declaration}"); + assert_eq!(thrown_name(&format!("new XML(\"\")")), "SyntaxError", "{declaration}"); + } + assert_eq!(string(&format!("().toXMLString()")), format!("")); + assert_eq!(string("().toXMLString()"), ""); +} + +#[test] +fn add_namespace_rejects_a_reserved_binding_and_keeps_the_element() { + for (prefix, uri) in [("xmlns", "u"), ("xmlns", XMLNS_NS), ("xml", "u"), ("p", XML_NS), ("p", XMLNS_NS)] { + let src = + format!("var x = ; var name = 'none'; try {{ x.addNamespace(new Namespace('{prefix}', '{uri}')); }} catch (e) {{ name = e.name; }}"); + assert_eq!(string(&format!("{src} name")), "TypeError", "{prefix} {uri}"); + assert_eq!(string(&format!("{src} x.toXMLString()")), "", "{prefix} {uri}"); + } + assert_eq!( + string(&format!("var x = ; x.addNamespace(new Namespace('xml', '{XML_NS}')); x.toXMLString()")), + format!("") + ); +} + +#[test] +fn names_cannot_write_a_reserved_namespace_binding() { + for setter in [ + "setNamespace(new Namespace('xmlns', 'u'))", + "setName(new QName(new Namespace('xml', 'u'), 'b'))", + "setNamespace(new Namespace('p', 'http://www.w3.org/2000/xmlns/'))", + "setNamespace('http://www.w3.org/2000/xmlns/')", + ] { + let src = format!("var x = ; var name = 'none'; try {{ x.{setter}; }} catch (e) {{ name = e.name; }}"); + assert_eq!(string(&format!("{src} name")), "TypeError", "{setter}"); + assert_eq!(string(&format!("{src} x.toXMLString()")), "", "{setter}"); + } + let q = |prefix: &str| format!("new QName(new Namespace('{prefix}', 'u'), 'b')"); + assert_eq!(string(&format!("var x = ; x[{}] = '1'; x.toXMLString()", q("xmlns"))), "\n 1\n"); + assert_eq!(string(&format!("var x = ; x.@[{}] = '1'; x.toXMLString()", q("xml"))), ""); +} + +#[test] +fn an_attribute_cannot_be_renamed_xmlns() { + for setter in ["setName('xmlns')", "setLocalName('xmlns')"] { + let src = format!("var x = ; var name = 'none'; try {{ x.@b[0].{setter}; }} catch (e) {{ name = e.name; }}"); + assert_eq!(string(&format!("{src} name")), "TypeError", "{setter}"); + assert_eq!(string(&format!("{src} x.toXMLString()")), "", "{setter}"); + } +} + +#[test] +fn new_nodes_cannot_take_a_reserved_name() { + let q = format!("new QName('{XMLNS_NS}', 'b')"); + for update in ["x.@xmlns = 'u'".to_string(), format!("x[{q}] = '1'"), format!("x.@[{q}] = '1'"), format!("x[{q}][0] = '1'")] { + let src = format!("var x = ; var name = 'none'; try {{ {update}; }} catch (e) {{ name = e.name; }}"); + assert_eq!(string(&format!("{src} name")), "TypeError", "{update}"); + assert_eq!(string(&format!("{src} x.toXMLString()")), "", "{update}"); + } +} + +#[test] +fn the_xmlns_uri_cannot_be_the_default_namespace() { + assert_eq!(thrown_name(&format!("default xml namespace = '{XMLNS_NS}'")), "TypeError"); + assert_eq!(thrown_name(&format!("setDefaultXMLNamespace('{XMLNS_NS}')")), "TypeError"); +} + +#[test] +fn the_garbage_collector_keeps_trees_and_lists_alive() { + let mut r = realm(); + r.run("var x = text; var l = x.b; var ns = new Namespace('p', 'u'); var q = new QName('u', 'n');").unwrap(); + r.collect_garbage(); + assert_eq!(r.run("x.b.@t == '1' && l[0] == 'text' && l[0].parent() === x && ns.uri === 'u' && q.localName === 'n'"), Ok(JsValue::Bool(true))); + r.run("x = l = ns = q = null;").unwrap(); + let live = r.collect_garbage(); + assert!(live < 100_000, "{live}"); +} + +// ---- hostile input ---- + +#[test] +fn malformed_literals_are_located_syntax_errors() { + let cases = [ + "var a = ", + "", + "", + "", + "", + "", + "&bad;", + "�", + "{1", + "{", + "<1x/>", + "", + "", + ",<", + "", + "", + "<>", + "", + ]; + for src in cases { + let e = parse(src, &e4x()).expect_err(src); + assert!(e.line >= 1 && e.column >= 1, "{src}: {e:?}"); + } + let e = parse("var a =\n ;", &e4x()).unwrap_err(); + assert_eq!(e.line, 2); +} + +#[test] +fn bad_xml_text_is_a_catchable_syntax_error() { + for s in [ + "", + "", + "&nope;", + "", + "", + "", + "", + "]]>", + "", + ] { + assert_eq!(thrown_name(&format!("new XML({s:?})")), "SyntaxError", "{s}"); + } + assert_eq!(thrown_name("new XML('')"), "TypeError"); +} + +#[test] +fn unpaired_surrogates_are_rejected_in_xml_text() { + let lone = "String.fromCharCode(0xD800)"; + let low = "String.fromCharCode(0xDC00)"; + for value in [ + format!("'' + {lone} + ''"), + format!("'' + {low} + ''"), + format!("''"), + format!("''"), + format!("''"), + format!("''"), + format!("'<' + {lone} + '/>'"), + ] { + assert_eq!(thrown_name(&format!("new XML({value})")), "SyntaxError", "{value}"); + } + assert_eq!(thrown_name(&format!("().setLocalName({lone})")), "TypeError"); + let e = parse("var a = <\u{FFFD}/>;", &e4x()).unwrap_err(); + assert_eq!((e.line, e.column), (1, 10)); + truth("var p = String.fromCharCode(0xD83D, 0xDE00); var x = new XML('' + p + ''); x == p && x.@b == p"); + truth("var p = String.fromCharCode(0xD83D, 0xDE00); new XML('<' + p + '/>').localName() === p"); +} + +#[test] +fn collections_during_parsing_and_copying_keep_new_nodes() { + let src = "for (var i = 0; i < 200; i++) { \ + var x = new XML('t'); var c = x.copy(); \ + if (c.@p != '1' || c.b.@r != '3' || c.*.length() !== 3 || x.@q != '2') throw new Error('lost'); \ + } 'done'"; + for spare in (16_000..20_000).step_by(37) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + assert_eq!(r.run(src), Ok(JsValue::String("done".into())), "{spare}"); + } +} + +#[test] +fn collections_during_updates_and_queries_keep_new_values() { + let src = "for (var i = 0; i < 60; i++) { \ + var x = new XML('t'); var c = x.copy(); \ + var l = <>{x.b}{'t'}; \ + c.appendChild(); c.prependChild('s'); c.insertChildAfter(c.b[0], ); c.insertChildBefore(c.b[0], 'n'); \ + c.replace(0, 1); c.n.o = 'v'; c.@t = 'w'; c.z[0] = ; c.g.h = 'deep'; \ + var f = x.*.(nodeKind() === 'element'); var d = x..*; var j = x + c; var m = x.b + ; \ + var ns = new Namespace('p', 'u'); var qn = new QName(ns, 'a'); c.addNamespace(ns); c.setNamespace(ns); c.setName(qn); \ + var scope = c.inScopeNamespaces(); var decl = c.namespaceDeclarations(); c.normalize(); \ + var text = c.toXMLString(); var again = new XML(text); var children = c.children(); var el = c.elements(); var attrs = c.attributes(); \ + var filled = new XMLList(l); var copied = l.copy(); c.setChildren(); \ + if (x.@p != '1' || x.*.length() !== 3 || f.length() !== 1 || j.length() !== 2 || m.length() !== 2) throw new Error('lost'); \ + if (l.length() !== 3 || copied.length() !== 3 || c.*.length() !== 1 || scope.length < 1 || d.length() !== 3) throw new Error('lost'); \ + } 'done'"; + let mut first_error = None; + let mut completed = 0; + for spare in (40_000..56_000).step_by(211) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + let got = r.run(src); + if got == Ok(JsValue::String("done".into())) { + completed += 1; + } else if !matches!(&got, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)) { + first_error = Some(format!("{spare}: {got:?}")); + break; + } + } + assert_eq!(first_error, None); + assert!(completed > 0); +} + +#[test] +fn a_scope_name_skips_a_list_without_that_name() { + truth("var outer = ; var inner = <>; with (outer) with (inner) { @id == '1' }"); + truth("var outer = ; var inner = <>; with (outer) with (inner) { @id == '2' }"); +} + +#[test] +fn a_bracket_key_converts_to_a_string_before_it_names_a_child() { + truth("var x = 1; x[true] == '1' && (true in x) && !(false in x)"); + truth("var x = 1; x[null] == '1' && x[undefined].length() === 0 && x[1.5].length() === 0 && x[-1].length() === 0"); + truth("var x = ; x[false] = 'v'; x['false'] == 'v' && (delete x[false], x.*.length() === 0)"); + assert_eq!(thrown_name("().attribute(true)"), "TypeError"); + assert_eq!(thrown_name("().descendants(null)"), "TypeError"); +} + +fn kind_of(limits: Limits, src: &str) -> RunErrorKind { + match limited(limits).run(src) { + Ok(v) => panic!("{} completed with {v:?}", &src[..src.len().min(80)]), + Err(e) => e.kind, + } +} + +fn on_small_stack(f: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::Builder::new().stack_size(512 << 10).spawn(f).unwrap().join().unwrap() +} + +#[test] +fn deep_trees_end_in_errors_on_a_small_stack() { + on_small_stack(|| { + let tags = 100_000; + let literal = format!("{}{}", "".repeat(tags), "".repeat(tags)); + let e = parse(&literal, &e4x()).unwrap_err(); + assert_eq!(e.message, crate::TOO_DEEP); + let text = format!("new XML('{literal}')"); + assert_eq!(limited(Limits::default()).run(&text).map_err(|e| e.message.contains(crate::TOO_DEEP)), Err(true)); + let chain = "var x = ; for (var i = 0; i < 100000; i++) { var y = ; y.appendChild(x); x = y; }"; + assert_eq!(kind_of(Limits::default(), chain), RunErrorKind::Limit(LimitKind::Heap)); + let within = "var x = ; for (var i = 0; i < 150; i++) { var y = ; y.appendChild(x); x = y; } \ + var c = x.copy(); [c == x, x.descendants().length(), x.toXMLString().length > 0, (x.normalize(), 1)].join()"; + assert_eq!(limited(Limits::default()).run(within), Ok(JsValue::String("true,150,true,1".into()))); + }); +} + +#[test] +fn cyclic_insertion_throws_and_leaves_the_tree_alone() { + for src in [ + "x.appendChild(x)", + "x.b[0].appendChild(x)", + "x.b[0].c[0].appendChild(x.b[0])", + "x.b[0].prependChild(x)", + "x.b[0].insertChildAfter(null, x)", + "x.b[0].insertChildBefore(null, x)", + ] { + let setup = "var x = ; var before = x.toXMLString();"; + let script = format!("{setup} var n; try {{ {src}; n = 'none' }} catch (e) {{ n = e.name }} x.toXMLString() === before ? n : 'changed'"); + assert_eq!(string(&script), "TypeError", "{src}"); + } +} + +#[test] +fn replace_inserts_a_copy_so_an_ancestor_can_be_the_value() { + truth("var x = ; x.b[0].replace(0, x); x.b.a.b.c.length() === 1 && x.b.a[0] !== x && x.descendants().length() === 4"); +} + +const TIGHT: Limits = Limits { fuel: 200_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 }; + +#[test] +fn big_values_end_with_the_heap_limit() { + let attrs = format!("var x = new XML('');", (0..50_000).map(|i| format!("a{i}=\"1\"")).collect::>().join(" ")); + assert_eq!(kind_of(Limits { fuel: 10_000_000, ..TIGHT }, &attrs), RunErrorKind::Limit(LimitKind::Heap)); + let wide = "var l = <>; for (;;) { l = l + l; }"; + assert_eq!(kind_of(Limits { fuel: 10_000_000, ..TIGHT }, wide), RunErrorKind::Limit(LimitKind::Heap)); + let giant = "var s = 'x'; for (var i = 0; i < 40; i++) s += s; new XML('' + s + '')"; + assert_eq!(kind_of(Limits { fuel: 10_000_000, ..TIGHT }, giant), RunErrorKind::Limit(LimitKind::Heap)); + let escaped = "var s = '<'; for (var i = 0; i < 17; i++) s += s; ({s}).toXMLString().length"; + assert_eq!(kind_of(Limits { fuel: 10_000_000, ..TIGHT }, escaped), RunErrorKind::Limit(LimitKind::Heap)); +} + +#[test] +fn catastrophic_queries_end_with_the_fuel_limit() { + let build = "var x = ; for (var i = 0; i < 2000; i++) x.appendChild();"; + let limits = Limits { fuel: 1_500_000, heap_bytes: 64 << 20, frames: 200, reentry: 8 }; + let filter = format!("{build} for (;;) x.a.(true);"); + assert_eq!(kind_of(limits.clone(), &filter), RunErrorKind::Limit(LimitKind::Fuel)); + let descendants = format!("{build} for (;;) x..a;"); + assert_eq!(kind_of(limits.clone(), &descendants), RunErrorKind::Limit(LimitKind::Fuel)); + let serialize = format!("{build} for (;;) x.toXMLString();"); + assert_eq!(kind_of(limits, &serialize), RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn limits_cannot_be_caught_by_the_script() { + assert_eq!(kind_of(TIGHT, "try { for (;;) ().toXMLString(); } catch (e) { 1 }"), RunErrorKind::Limit(LimitKind::Fuel)); +} + +/// Collects garbage and sets the heap limit to the live size plus the argument, so a script can +/// run out of heap at a chosen charge. A negative argument puts the heap over its limit, which +/// also happens when a lowered limit meets a larger heap. +fn squeeze( + i: &mut crate::interp::Interp, + _: crate::value::Value, + args: &[crate::value::Value], + _: bool, +) -> crate::interp::JsResult { + i.collect_garbage(); + if let Some(crate::value::Value::Number(spare)) = args.first() { + i.limits.heap_bytes = (i.heap.bytes as f64 + *spare) as usize; + } + Ok(crate::value::Value::Undefined) +} + +/// Runs `setup`, then the action for each step from 0 until one completes, and after each stop +/// asserts that `check` is true with the limits lifted. Returns how many runs stopped at `kind`. +fn stops_with_the_tree_intact(setup: &str, action: impl Fn(usize) -> String, check: &str, kind: LimitKind, limit: impl Fn(usize) -> Limits) -> usize { + let mut r = realm(); + let interp = r.interp(); + let global = interp.global; + assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); + let mut stops = 0; + for step in 0..200_000 { + r.set_limits(Limits::default()); + r.run(setup).unwrap(); + r.set_limits(limit(step)); + let action = action(step); + let got = r.run(&action); + r.set_limits(Limits::default()); + assert_eq!(r.run(check), Ok(JsValue::Bool(true)), "{action}: {got:?}"); + match got { + Ok(_) => return stops, + Err(e) if e.kind == RunErrorKind::Limit(kind) => stops += 1, + Err(_) => {} + } + } + panic!("{check} never completed"); +} + +/// Runs `action`, whose `SPARE` is replaced by a call that leaves each number of bytes free in +/// turn, from 512 too few. Actions put it after the steps whose allocations a collection could +/// free: an argument is evaluated after the callee is looked up. +fn heap_stops(setup: &str, action: &str, check: &str) -> usize { + let action = |spare: usize| action.replace("SPARE", &format!("squeeze({})", spare as i64 - 512)); + stops_with_the_tree_intact(setup, action, check, LimitKind::Heap, |_| Limits::default()) +} + +fn fuel_stops(setup: &str, action: &str, check: &str) -> usize { + stops_with_the_tree_intact(setup, |_| action.to_string(), check, LimitKind::Fuel, |fuel| Limits { fuel: fuel as u64, ..Limits::default() }) +} + +const MOVE_SETUP: &str = "var o = ; var t = ; var n = o.b[0];"; +const MOVE_CHECK: &str = + "o.b.length() + t.b.length() === 1 && (o.b.length() === 0 || o.b[0].parent() === o) && (t.b.length() === 0 || t.b[0].parent() === t)"; + +#[test] +fn a_heap_limit_during_a_move_leaves_the_node_in_its_old_parent() { + for action in + ["t.appendChild((SPARE, n))", "t.prependChild((SPARE, n))", "t.insertChildAfter(null, (SPARE, n))", "t.insertChildBefore(null, (SPARE, n))"] + { + assert!(heap_stops(MOVE_SETUP, action, MOVE_CHECK) > 0, "{action}"); + } +} + +#[test] +fn a_fuel_limit_during_a_move_leaves_the_node_in_its_old_parent() { + for action in ["t.appendChild(n)", "t.prependChild(n)"] { + assert!(fuel_stops(MOVE_SETUP, action, MOVE_CHECK) > 0, "{action}"); + } + let replaced = "var l = t.*; l[0] = o.b[0]"; + let setup = "var o = ; var t = ;"; + assert!(fuel_stops(setup, replaced, MOVE_CHECK) > 0); +} + +#[test] +fn a_heap_limit_on_replace_past_the_end_leaves_no_child_without_a_parent() { + let check = "var n = x.*.length(); if (n === 0) { true } else { \ + var v = x.*[n - 1]; var name; try { v.appendChild(x); name = 'none' } catch (e) { name = e.name } v.parent() === x && name === 'TypeError' }"; + let action = "x.replace({ toString: function () { SPARE; return '5'; } }, v)"; + assert!(heap_stops("var x = ; var v = ;", action, check) > 0); +} + +#[test] +fn limits_during_deletes_and_puts_keep_the_other_nodes() { + let setup = "var x = old;"; + let others = "x.c.length() === 1 && x.@q == '2'"; + for action in ["delete x.b", "delete x.@p", "x.@p = 'v'", "x.@n = 'v'", "x.b = 'v'"] { + assert!(fuel_stops(setup, action, others) > 0, "{action}"); + } + let held = format!("{others} && x.b.length() === 1 && (x.b == 'old' || x.b == 'v') && x.b.*[0].parent() === x.b[0]"); + assert!(fuel_stops(setup, "x.b = 'v'", &held) > 0); + assert!(heap_stops(setup, "x.b = (SPARE, 'v')", &held) > 0); +} + +/// True when the markup of `tree` is `before` or `after`, ignoring white space. +fn tree_is(tree: &str, before: &str, after: &str) -> String { + format!("(function () {{ var s = {tree}.toXMLString().replace(/\\s/g, ''); return s === '{before}' || s === '{after}'; }})()") +} + +#[test] +fn a_limit_while_a_list_replaces_a_child_leaves_the_children() { + let setup = "var x = ; var v = <>

;"; + let replaced = tree_is("x", "", "

"); + for action in ["x.replace(0, v)", "x.b = v"] { + assert!(fuel_stops(setup, action, &replaced) > 0, "{action}"); + } + let spare = "x.replace({ toString: function () { SPARE; return '0'; } }, v)"; + assert!(heap_stops(setup, spare, &replaced) > 0); + let set = tree_is("x", "", "

"); + assert!(fuel_stops(setup, "x.setChildren(v)", &set) > 0); +} + +#[test] +fn a_limit_while_a_list_is_inserted_leaves_the_children() { + let setup = "var o =

; var x = ; var v = o.*;"; + let check = |after: &str| { + format!("{} && (o.*.length() === 0 ? x.*.length() === 3 : o.*.length() === 2 && x.*.length() === 1)", tree_is("x", "", after)) + }; + for (action, after) in [ + ("x.appendChild(v)", "

"), + ("x.prependChild(v)", "

"), + ("x.insertChildAfter(null, v)", "

"), + ("x.insertChildBefore(null, v)", "

"), + ] { + assert!(fuel_stops(setup, action, &check(after)) > 0, "{action}"); + } + assert!(heap_stops(setup, "x.appendChild((SPARE, v))", &check("

")) > 0); +} + +#[test] +fn a_heap_limit_on_a_list_put_at_an_index_keeps_the_list_and_tree_in_step() { + let setup = "var x = ; var l = x.*; var v = <>

;"; + let check = "var s = x.toXMLString().replace(/\\s/g, ''); \ + (s === '' && l.length() === 2 && l[0].name() == 'b') \ + || (s === '

' && l.length() === 3 && l[0].name() == 'p')"; + assert!(heap_stops(setup, "l[(SPARE, 0)] = v", check) > 0); +} + +#[test] +fn an_index_put_of_an_earlier_sibling_keeps_that_node_in_the_list() { + let setup = "var x = ; var l = x.*;"; + truth(&format!("{setup} l[2] = x.b; l[2] === x.b[0] && l[3] === x.e[0]")); + truth(&format!("{setup} l[2] = x.b[0]; l[2] === x.b[0] && l[3] === x.e[0]")); +} + +/// A realm whose trees may be 32 levels deep, and a script line making `deep`, a tree of 32 levels +/// that cannot go under any element. +fn shallow_with_deep_value() -> (Realm, &'static str) { + let deep = "var s = ''; var e = ''; for (var i = 0; i < 32; i++) { s += ''; e += ''; } var deep = new XML(s + e);"; + (Realm::with_options(Options { max_depth: 32, ..e4x() }, Limits::default()), deep) +} + +#[test] +fn a_too_deep_value_leaves_every_match_in_place() { + for action in ["x.replace('b', deep)", "x.b = deep"] { + let (mut r, deep) = shallow_with_deep_value(); + r.run(deep).unwrap(); + r.run("var x = ;").unwrap(); + assert_eq!(r.run(action).map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Heap)), "{action}"); + assert_eq!(r.run("x.b.length() === 2 && x.*.length() === 3"), Ok(JsValue::Bool(true)), "{action}"); + } +} + +#[test] +fn a_limit_while_matches_are_replaced_keeps_every_match() { + let setup = "var x = ; var n = ; var l = <>

;"; + let two = ""; + for (action, after) in [ + ("x.replace('b', n)", ""), + ("x.replace('b', l)", "

"), + ("x.b = n", ""), + ("x.b = l", "

"), + ("x.b = 'v'", "v"), + ] { + assert!(fuel_stops(setup, action, &tree_is("x", two, after)) > 0, "{action}"); + } + let by_name = "x.replace({ toString: function () { SPARE; return 'b'; } }, n)"; + assert!(heap_stops(setup, by_name, &tree_is("x", two, "")) > 0); + assert!(heap_stops(setup, "x.b = (SPARE, 'v')", &tree_is("x", two, "v")) > 0); +} + +#[test] +fn matches_are_replaced_in_document_order() { + truth("var x = 123; x.replace('b', ); x.*.length() === 3 && x.*[0].name() == 'n' && x.d.length() === 1"); + truth("var x = 12; var old = x.b[1]; x.b = 'v'; x.b.length() === 1 && x.b == 'v' && old.parent() === null"); + truth("var x = ; x.b = 'v'; x.b == 'v' && x.*.length() === 2 && x.b[0].parent() === x"); +} + +#[test] +fn an_attribute_put_among_children_goes_in_as_text_and_stays_on_its_owner() { + let setup = "var y = ; var x = ;"; + let check = "x.b.length() === 0 && x.children().length() === 1 && x.children()[0].nodeKind() === 'text' && x.toString() === 'v' \ + && y.@p.length() === 1 && y.@p.parent() === y && y.@p[0].parent() === y"; + for edit in ["x.replace(0, y.@p)", "x.replace(0, y.@p[0])", "x.b = y.@p", "x.setChildren(y.@p)", "x.*[0] = y.@p"] { + truth(&format!("{setup} {edit}; {check}")); + } + let owner = "y.@p.length() === 1 && y.@p.parent() === y && y.@p[0].parent() === y"; + for (edit, k) in [ + ("x.prependChild(y.@p)", "0"), + ("x.prependChild(y.@p[0])", "0"), + ("x.appendChild(y.@p)", "1"), + ("x.appendChild(y.@p[0])", "1"), + ("x.insertChildAfter(x.b[0], y.@p)", "1"), + ("x.insertChildBefore(x.b[0], y.@p[0])", "0"), + ] { + truth(&format!( + "{setup} {edit}; x.children().length() === 2 && x.children()[{k}].nodeKind() === 'text' && x.children()[{k}] == 'v' && {owner}" + )); + } +} + +#[test] +fn a_list_assigned_attributes_holds_the_text_nodes_in_the_tree() { + truth( + "var y = ; var x = ; var l = x.*; l[0] = y.@*; \ + l.length() === 2 && l[0].nodeKind() === 'text' && l[0].parent() === x && l[1].nodeKind() === 'text' && l[1].parent() === x \ + && x.toString() === 'vw' && y.@*.length() === 2", + ); +} + +#[test] +fn an_attribute_list_goes_in_as_text_at_the_depth_limit() { + let open = "".repeat(7); + let close = "".repeat(7); + let src = format!( + "var x = new XML('{open}{close}'); var c = x; while (c.a.length()) c = c.a[0]; \ + var y = ; c.prependChild(y.@p); c.toString() === 'v'" + ); + let mut realm = Realm::with_options(Options { max_depth: 8, ..e4x() }, Limits::default()); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + +#[test] +fn a_limit_during_normalize_does_not_repeat_text() { + let setup = "var x = ; x.appendChild('p'); x.appendChild('q'); x.appendChild('r');"; + let check = "x.toString() === 'pqr'"; + assert!(fuel_stops(setup, "x.normalize()", check) > 0); +} + +/// Runs `action` as [`heap_stops`] does, and asserts that every run completes or stops at the heap +/// limit and that `check` is true after it. Returns how many runs stopped. +fn heap_stops_only(setup: &str, action: &str, check: &str) -> usize { + let mut r = realm(); + let interp = r.interp(); + let global = interp.global; + assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); + let mut stops = 0; + for spare in 0..100_000i64 { + r.set_limits(Limits::default()); + r.run(setup).unwrap(); + let action = action.replace("SPARE", &format!("squeeze({})", spare - 512)); + let got = r.run(&action); + r.set_limits(Limits::default()); + assert_eq!(r.run(check), Ok(JsValue::Bool(true)), "{action}: {got:?}"); + match got { + Ok(_) => return stops, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stops += 1, + Err(e) => panic!("{action}: {e:?}"), + } + } + panic!("{action} never completed"); +} + +#[test] +fn collections_while_a_list_is_copied_keep_every_copy() { + let setup = "var x = ; var v = + ; var w = undefined;"; + let set = tree_is("x", "", ""); + for action in ["x.setChildren((SPARE, v))", "x.* = (SPARE, v)"] { + assert!(heap_stops_only(setup, action, &set) > 0, "{action}"); + } + let copied = "w === undefined || (w.length() === 2 && w[0].name() == 'c' && w[1].name() == 'd' && w[0] !== v[0])"; + assert!(heap_stops_only(setup, "w = (SPARE, v).copy()", copied) > 0); +} + +#[test] +fn a_limit_during_path_assignment_leaves_no_new_element() { + let setup = "var x = ; var v = ;"; + for (target, value, after) in [ + ("x.a.b.c", "v", ""), + ("x.a.b", "'text'", "text"), + ("x.a.@p", "'text'", ""), + ("x.a.b[0]", "'text'", "text"), + ] { + let check = tree_is("x", "", after); + assert!(fuel_stops(setup, &format!("{target} = {value}"), &check) > 0, "{target}"); + assert!(heap_stops_only(setup, &format!("{target} = (SPARE, {value})"), &check) > 0, "{target}"); + } +} + +#[test] +fn comparing_xml_values_is_charged_to_the_heap() { + let setup = "var x = t; var y = x.copy();"; + assert!(heap_stops_only(setup, "(SPARE, x == y)", "x == y && y.@q == '2'") > 0); +} + +/// Runs `setup` with no limit, then `action` in the same realm, and returns how `action` ended. +fn after_setup(setup: &str, action: &str) -> Result { + let mut r = realm(); + let interp = r.interp(); + let global = interp.global; + assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok()); + r.run(setup).unwrap(); + r.run(action).map_err(|e| e.kind) +} + +#[test] +fn namespace_declarations_and_qname_strings_are_charged_to_the_heap() { + let heap = Err(RunErrorKind::Limit(LimitKind::Heap)); + let distinct = "var x = ; var a = []; for (var i = 0; i < 400; i++) a.push(new Namespace('p' + i, 'u' + i));"; + for method in ["addNamespace", "setNamespace"] { + let action = format!("squeeze(4096); for (var i = 0; i < 400; i++) x.{method}(a[i]); 1"); + assert_eq!(after_setup(distinct, &action), heap, "{method}"); + } + let same = "var x = ; var n = new Namespace('p', 'u');"; + let action = "squeeze(4096); for (var i = 0; i < 400; i++) x.addNamespace(n); 1"; + assert_eq!(after_setup(same, action), Ok(JsValue::Number(1.0))); + let long = "var s = 'x'; for (var i = 0; i < 12; i++) s += s; var q = new QName('u', s);"; + let action = "squeeze(12000); var t1 = q.toString(); var t2 = q.toString(); 1"; + assert_eq!(after_setup(long, action), heap); +} + +#[test] +fn an_interrupt_stops_serialization() { + let mut r = realm(); + r.run("var x = ; for (var i = 0; i < 500; i++) x.appendChild();").unwrap(); + let interrupt = r.interrupt(); + r.define_function("stop", move |_| { + interrupt.set(); + Ok(JsValue::Undefined) + }); + assert_eq!(r.run("stop(); x.toXMLString()").map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Interrupted))); +} + +// ---- generated input ---- + +const PIECES: &[&str] = &[ + "<", + ">", + "/", + "", + "", + "", + "", + "", + "<>", + "", + "{", + "}", + "{1}", + "'", + "\"", + "&", + "&", + "A", + "&bad;", + "", + "", + "", + "@", + "::", + "..", + ".(", + ")", + "*", + "/x/", + " ", + "\n", + "a", + "1", + "=", + "ns", + ":", + "xmlns", + "x.@a", + "x..y", + "default xml namespace", +]; + +fn tree_markup(shape: &[u8]) -> String { + let mut out = String::new(); + let mut open: Vec = Vec::new(); + out.push_str(""); + for (i, &b) in shape.iter().enumerate() { + match b % 6 { + 0 if open.len() < 20 => { + out.push_str(&format!("")); + open.push(i); + } + 1 => { + if let Some(e) = open.pop() { + out.push_str(&format!("")); + } + } + 2 => out.push_str(&format!("")), + 3 => out.push_str(&format!("t{b}&")), + 4 => out.push_str(&format!("")), + _ => out.push_str(&format!("")), + } + } + while let Some(e) = open.pop() { + out.push_str(&format!("")); + } + out.push_str(""); + out +} + +const TAG_PIECES: [&str; 11] = ["a", "b", " ", "=", "\"", "'", "<", "/", "<", "a=\"1\"", ">; v.children().length() === 0 && v.attributes().length() === 0"), + format!("var v = ; v.children().length() === 0 && v.name().localName === 'x'"), + format!("(<>).length() === 1"), + format!("var v = ; v.children().length() === 1"), + ] { + let mut r = limited(Limits { fuel: 200_000, heap_bytes: 4 << 20, frames: 200, reentry: 8 }); + match r.run(&src) { + Ok(v) => prop_assert_eq!(v, JsValue::Bool(true), "{}", src), + Err(e) => prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}"), + } + } + } + + #[test] + fn source_mixes_parse_or_give_a_located_error(parts in proptest::collection::vec(0..PIECES.len(), 0..40)) { + let src: String = parts.iter().map(|&i| PIECES[i]).collect(); + if let Err(e) = parse(&src, &e4x()) { + prop_assert!(e.line >= 1 && e.column >= 1, "{src:?}: {e:?}"); + } + } + + #[test] + fn random_programs_never_reach_an_internal_error(parts in proptest::collection::vec(0..PIECES.len(), 0..40)) { + let src: String = format!("var x = ; {}", parts.iter().map(|&i| PIECES[i]).collect::()); + let mut r = limited(Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 }); + if let Err(e) = r.run(&src) { + prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}"); + } + } + + #[test] + fn xml_text_parses_or_throws(parts in proptest::collection::vec(0..PIECES.len(), 0..40)) { + let text: String = parts.iter().map(|&i| PIECES[i]).collect(); + let quoted = format!("{text:?}"); + let mut r = limited(Limits { fuel: 200_000, heap_bytes: 4 << 20, frames: 200, reentry: 8 }); + if let Err(e) = r.run(&format!("new XML({quoted})")) { + prop_assert!(e.kind == RunErrorKind::Thrown, "{quoted}: {e:?}"); + } + } + + #[test] + fn serialized_trees_parse_to_an_equal_tree(shape in proptest::collection::vec(any::(), 0..80)) { + let markup = tree_markup(&shape); + let quoted = format!("{markup:?}"); + let plain = format!("XML.prettyPrinting = false; XML.ignoreWhitespace = false; var x = new XML({quoted}); var y = new XML(x.toXMLString()); x.normalize(); y.normalize(); x == y"); + prop_assert_eq!(limited(Limits::default()).run(&plain), Ok(JsValue::Bool(true)), "{}", markup); + let pretty = format!("var x = new XML({quoted}); var y = new XML(x.toXMLString()); x.toXMLString() === y.toXMLString()"); + prop_assert_eq!(limited(Limits::default()).run(&pretty), Ok(JsValue::Bool(true)), "{}", markup); + } + + #[test] + fn insert_sequences_stay_acyclic(steps in proptest::collection::vec((0usize..8, 0usize..8), 0..40)) { + let mut src = String::from("var n = []; for (var i = 0; i < 8; i++) n.push(new XML('')); var bad = 0;"); + for (a, b) in steps { + src.push_str(&format!("try {{ n[{a}].appendChild(n[{b}]); }} catch (e) {{ if (e.name !== 'TypeError') bad++; }}")); + } + src.push_str("var ok = bad === 0; for (var j = 0; j < 8; j++) { ok = ok && n[j].toXMLString().length > 0 && n[j].descendants().length() < 8; } ok"); + let got = limited(Limits::default()).run(&src); + prop_assert_eq!(got, Ok(JsValue::Bool(true)), "{}", src); + } +} diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 32735d9a02..00e914ddba 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -129,10 +129,17 @@ impl Headless { fn exec(&mut self, id: &str, params: &Value) -> Result { // A key the command's description doesn't name is an error, not a default (#1442). match HOST_COMMANDS.iter().find(|c| c.0 == id) { - Some((_, _, doc)) => vectorcraft_engine::check_keys(id, doc, params), - None => self.session.check_params(id, params), + Some((_, _, doc)) => vectorcraft_engine::check_keys(id, doc, params).map_err(|e| e.to_string())?, + None if vectorcraft_engine::find_command(id).is_some() => { + self.session.check_params(id, params).map_err(|e| e.to_string())?; + } + None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => { + return Err(format!( + "`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`" + )); + } + None => self.session.check_params(id, params).map_err(|e| e.to_string())?, } - .map_err(|e| e.to_string())?; match id { "file.open" => self.open(params), "file.save" => self.save(params), @@ -146,9 +153,30 @@ impl Headless { fn commands(&self) -> Value { let mut v: Vec = self.session.commands().into_iter().map(|c| serde_json::to_value(c).unwrap_or_default()).collect(); + let mut seen: std::collections::HashSet = v.iter().filter_map(|c| c.get("id").and_then(Value::as_str).map(str::to_owned)).collect(); for (id, label, params) in HOST_COMMANDS { + if !seen.insert((*id).to_owned()) { + continue; + } v.push(json!({"id": id, "label": label, "menu": [], "shortcut": null, "params": params, "enabled": true, "host": true})); } + // Desktop menu commands (`UI_COMMANDS`): listed for discovery with `ui: true`. Running one + // that only the desktop app implements still needs `--connect` (see `exec`). + for (id, label, shortcut, params) in crate::ui_catalog::UI_COMMANDS { + if !seen.insert((*id).to_owned()) { + continue; + } + let sc = if shortcut.is_empty() { Value::Null } else { json!(shortcut) }; + v.push(json!({ + "id": id, + "label": label, + "menu": [], + "shortcut": sc, + "params": params, + "enabled": true, + "ui": true, + })); + } Value::Array(v) } diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 785746a38f..d2f1145361 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -22,6 +22,7 @@ mod prompts; mod resources; mod server; mod tools; +mod ui_catalog; pub use backend::{Backend, Remote}; pub use headless::Headless; diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 8ad74c6ba4..7741d9228f 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -365,6 +365,110 @@ Method: Live effects are kept on export (geometry baked; shadows, glows and blur become SVG filters), and text stays text unless you pass outlineText.", }, + PromptDef { + name: "check-spelling", + title: "Check spelling", + description: "Run text.spelling.check on the selection or document, then apply suggestions or dictionary changes.", + arguments: &[ + PromptArg { + name: "scope", + description: "What to check", + required: false, + default: "the selection, or every story when nothing is selected", + values: Values::Fixed(&[ + "the selection, or every story when nothing is selected", + "the active story only", + "every story in the document", + ]), + }, + PromptArg { + name: "action", + description: "What to do with each unknown word", + required: false, + default: "list suggestions and ask before changing", + values: Values::Fixed(&[ + "list suggestions and ask before changing", + "apply the first suggestion for each word", + "add unknown words to the custom dictionary", + "ignore all for this document", + ]), + }, + ], + text: "\ +Check spelling in VectorCraft for {scope}, then {action}. + +Method: +1. inspect_document to see the selection and type objects. +2. run_command text.spelling.check (and text.spelling.suggest for each unknown word). Offsets are + byte ranges for text.editRange / text.spelling.changeWord. +3. For a fix, text.spelling.changeWord; for the custom dictionary, text.spelling.addWord / + removeWord / dictionary; for this document only, text.spelling.ignoreAll. +4. Prefer those commands over inventing replacements. screenshot if the layout may reflow. + +Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.", + }, + PromptDef { + name: "variables-bind", + title: "Bind variables", + description: "Define text, visibility or image variables, bind them to art, and load or save a variable library.", + arguments: &[ + PromptArg { + name: "kind", + description: "Which variable kinds to set up", + required: false, + default: "text", + values: Values::Fixed(&["text", "visibility", "image", "graph", "mixed"]), + }, + PromptArg { + name: "source", + description: "Where the data comes from", + required: false, + default: "define variables on the selection by hand", + values: Values::Fixed(&["define variables on the selection by hand", "import a CSV or TSV data set", "load a variable library XML"]), + }, + ], + text: "\ +Set up {kind} variables in VectorCraft from {source}. + +Method: +1. inspect_document and variable.list (or the Variables panel commands) to see what exists. +2. variable.define / variable.bind for text, visibility, image or graph bindings; one text + variable per type object. +3. For CSV/TSV, dataset.import; for a library file, variable.loadLibrary / variable.saveLibrary. +4. Switch data sets with dataset.apply and verify with inspect_document / screenshot. +5. Prefer run_command over inventing panel clicks. Undo covers each binding step.", + }, + PromptDef { + name: "path-tools", + title: "Path Tools add-on", + description: "Use addon.pathtools.* commands (and addon.path.* live effects) to edit path geometry.", + arguments: &[PromptArg { + name: "task", + description: "What to do to the selection", + required: true, + default: "", + values: Values::Fixed(&[ + "extend open ends", + "close paths", + "add anchors along curves", + "simplify anchors", + "split at anchors", + "expand dashes to geometry", + "create a parametric shape", + ]), + }], + text: "\ +Perform this Path Tools task in VectorCraft: {task}. + +Method: +1. command_list with filter \"addon.pathtools\" for the command ids (extend, close, addPoints, + simplify, crossings, shape.create, …). Those are commands. +2. Live Path Effects keep the effect ids addon.path.* (dashes, addAnchors, extend, close, + smooth, retract, reverse, simplify, split). Apply them with apply_effect / effect.apply; + they are not command ids. +3. inspect_document the selection, run the command or effect, then screenshot. +4. Expand Appearance (effect.expandAppearance) only when the brief needs baked geometry.", + }, ]; /// The message body as a client should receive it. diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index dba3ed9def..d7de8dd7fb 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -209,9 +209,77 @@ fn tool_schemas_are_valid() { "export", "undo", "redo", + "command_list", + "command_run", + "command_batch", + "doc_inspect", + "render_preview", + "ui_inspect", + "ui_screenshot", + "type_text", + "answer_dialog", + "add_text", + "apply_effect", + "pathfinder", + "transform", + "create_graph", + "text_wrap", ] { assert!(names.contains(want), "missing tool {want}"); } + assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools"); +} + +/// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460). +#[test] +fn headless_command_list_includes_post_022_engine_commands() { + let mut s = server(); + rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})); + s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); + let want = [ + "actionSet.read", + "engine.apiReference", + "script.run", + "script.stop", + "text.spelling.check", + "document.move", + "document.compare", + "edit.newDocumentFromState", + ]; + for (n, id) in want.iter().enumerate() { + let r = call(&mut s, 10 + n as u64, "command_list", json!({"filter": id, "brief": true})); + assert_eq!(r["isError"], false, "{id}: {r}"); + let list: Value = serde_json::from_str(&text_of(&r)).unwrap(); + assert!(list.as_array().unwrap().iter().any(|c| c["id"] == *id), "missing {id} in {list}"); + } +} + +/// Headless `command_list` lists desktop UI commands with `ui: true` (#6460). +#[test] +fn headless_command_list_includes_ui_commands() { + let mut s = server(); + rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})); + s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); + let want = [ + "addon.arrange.zoomSelection", + "file.newDialog", + "view.fitArtboard", + "view.rotateReset", + "app.quit", + "window.arrange.tile", + "align.horizontalLeft", + "ui.action.play", + ]; + for (n, id) in want.iter().enumerate() { + let r = call(&mut s, 20 + n as u64, "command_list", json!({"filter": id, "brief": true})); + assert_eq!(r["isError"], false, "{id}: {r}"); + let list: Value = serde_json::from_str(&text_of(&r)).unwrap(); + let entry = list.as_array().unwrap().iter().find(|c| c["id"] == *id).unwrap_or_else(|| panic!("missing {id} in {list}")); + assert_eq!(entry["ui"], true, "{entry}"); + } + let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}})); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("--connect"), "{r}"); } // ---------- headless end-to-end ---------- diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 27d92394ff..2480f4ad69 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -98,7 +98,7 @@ pub fn tool_definitions() -> Vec { tool( "command_list", "List commands", - "Discover command ids, labels, parameter descriptions and enabled state. A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}.", + "Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id headless needs --connect). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.", obj( json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}), &[], @@ -156,7 +156,7 @@ pub fn tool_definitions() -> Vec { tool( "list_commands", "List commands", - "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Every editing action is a command; run any of them with run_command. Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only.", + "List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id run headless needs --connect). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.", obj( json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}), &[], diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs new file mode 100644 index 0000000000..e15244580d --- /dev/null +++ b/crates/mcp/src/ui_catalog.rs @@ -0,0 +1,1672 @@ +//! Desktop UI command catalogue for headless MCP discovery (`ui: true`). +//! Generated from `crates/ui-egui/src/menus/ui_commands.rs` by `cargo xtask ui-commands`. +//! Do not edit by hand; re-run the xtask when that table changes. + +/// `(id, label, shortcut, params doc)` — same shape as the desktop `UI_COMMANDS` table. +pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ + ("addon.pathtools.cornerTool", "Corner Tool", "", "{} choose the Corner Tool and show the Anchor Inspector panel with its radius and kind"), + ( + "addon.pathtools.sharedEdgeTool", + "Shared Edge Merge Tool", + "", + "{} choose the Shared Edge Merge Tool and show the Anchor Inspector panel with its brush, coincidence and Keep Shared Points Together", + ), + ( + "addon.arrange.zoomSelection", + "Zoom to Selection", + "", + "{} zoom and centre the active view so the selection's visual bounds fill the window, with a margin (as view.fitArtboard fits the artboard); off with nothing selected", + ), + ( + "app.language", + "Interface Language", + "", + "{lang: auto|} the interface language, persisted as the `interfaceLanguage` preference (`auto` follows the system locale; codes: prefs.list › interfaceLanguage, e.g. en, ja, cs, es, zh-hant)", + ), + ( + "file.open", + "Open…", + "Cmd+O", + "{path?, params?} → with a path, document.open's result {index, title, format, warnings, …} (null when a dialog asks first or a library loads); `params` are the parameters of the importer plug-in that opens the file", + ), + ( + "file.openWith", + "Open With", + "", + "{importer: \"plugin.\" (an importer plug-in's format id, see document.formats), path?} File › Open With: open the file with that importer (document.open's importer), also a file whose extension a built-in format reads; without a path pick one of the files with the extensions it lists (the web opens File › Open's picker, and the file opens as File › Open opens it) → with a path, document.open's result; a picked file is read off the UI thread on the desktop, {background: true, status}, and opens once the importer returns (file.cancelOpen stops it) | null while the picker is open", + ), + ( + "file.save", + "Save", + "Cmd+S", + "{path?, format?, options?, svg?: {…SVG options}} = document.save, written through the app (a document saved as SVG, PDF or .ai, or opened from one Save can write back, saves as that again, with the same options); with no path known (never saved, converted) the Save As panel asks first", + ), + ( + "file.place", + "Place…", + "Cmd+Shift+P", + "{path? | paths?} no file: pick files, then the Place dialog (Link, Template, Replace); paths: that dialog for them; path (or name+dataBase64, …file.place params): file.place, centred in the view (a PDF with several pages or a password and no page opens the Place PDF dialog first)", + ), + ("file.openRecent1", "Open Recent File 1", "", "{}"), + ("file.openRecent2", "Open Recent File 2", "", "{}"), + ("file.openRecent3", "Open Recent File 3", "", "{}"), + ("file.openRecent4", "Open Recent File 4", "", "{}"), + ("file.openRecent5", "Open Recent File 5", "", "{}"), + ("file.openRecent6", "Open Recent File 6", "", "{}"), + ("file.openRecent7", "Open Recent File 7", "", "{}"), + ("file.openRecent8", "Open Recent File 8", "", "{}"), + ("file.openRecent9", "Open Recent File 9", "", "{}"), + ("file.openRecent10", "Open Recent File 10", "", "{}"), + ("view.goto1", "Saved View 1", "", "{} go to the 1. saved view"), + ("view.goto2", "Saved View 2", "", "{} go to the 2. saved view"), + ("view.goto3", "Saved View 3", "", "{} go to the 3. saved view"), + ("view.goto4", "Saved View 4", "", "{} go to the 4. saved view"), + ("view.goto5", "Saved View 5", "", "{} go to the 5. saved view"), + ("view.goto6", "Saved View 6", "", "{} go to the 6. saved view"), + ("view.goto7", "Saved View 7", "", "{} go to the 7. saved view"), + ("view.goto8", "Saved View 8", "", "{} go to the 8. saved view"), + ("view.goto9", "Saved View 9", "", "{} go to the 9. saved view"), + ("view.goto10", "Saved View 10", "", "{} go to the 10. saved view"), + ("view.goto11", "Saved View 11", "", "{} go to the 11. saved view"), + ("view.goto12", "Saved View 12", "", "{} go to the 12. saved view"), + ("view.goto13", "Saved View 13", "", "{} go to the 13. saved view"), + ("view.goto14", "Saved View 14", "", "{} go to the 14. saved view"), + ("view.goto15", "Saved View 15", "", "{} go to the 15. saved view"), + ("view.goto16", "Saved View 16", "", "{} go to the 16. saved view"), + ("view.goto17", "Saved View 17", "", "{} go to the 17. saved view"), + ("view.goto18", "Saved View 18", "", "{} go to the 18. saved view"), + ("view.goto19", "Saved View 19", "", "{} go to the 19. saved view"), + ("view.goto20", "Saved View 20", "", "{} go to the 20. saved view"), + ("view.goto21", "Saved View 21", "", "{} go to the 21. saved view"), + ("view.goto22", "Saved View 22", "", "{} go to the 22. saved view"), + ("view.goto23", "Saved View 23", "", "{} go to the 23. saved view"), + ("view.goto24", "Saved View 24", "", "{} go to the 24. saved view"), + ("view.goto25", "Saved View 25", "", "{} go to the 25. saved view"), + ("select.recall1", "Saved Selection 1", "", "{} select the 1. saved selection"), + ("select.recall2", "Saved Selection 2", "", "{} select the 2. saved selection"), + ("select.recall3", "Saved Selection 3", "", "{} select the 3. saved selection"), + ("select.recall4", "Saved Selection 4", "", "{} select the 4. saved selection"), + ("select.recall5", "Saved Selection 5", "", "{} select the 5. saved selection"), + ("select.recall6", "Saved Selection 6", "", "{} select the 6. saved selection"), + ("select.recall7", "Saved Selection 7", "", "{} select the 7. saved selection"), + ("select.recall8", "Saved Selection 8", "", "{} select the 8. saved selection"), + ("select.recall9", "Saved Selection 9", "", "{} select the 9. saved selection"), + ("select.recall10", "Saved Selection 10", "", "{} select the 10. saved selection"), + ("select.recall11", "Saved Selection 11", "", "{} select the 11. saved selection"), + ("select.recall12", "Saved Selection 12", "", "{} select the 12. saved selection"), + ("select.recall13", "Saved Selection 13", "", "{} select the 13. saved selection"), + ("select.recall14", "Saved Selection 14", "", "{} select the 14. saved selection"), + ("select.recall15", "Saved Selection 15", "", "{} select the 15. saved selection"), + ("select.recall16", "Saved Selection 16", "", "{} select the 16. saved selection"), + ("select.recall17", "Saved Selection 17", "", "{} select the 17. saved selection"), + ("select.recall18", "Saved Selection 18", "", "{} select the 18. saved selection"), + ("select.recall19", "Saved Selection 19", "", "{} select the 19. saved selection"), + ("select.recall20", "Saved Selection 20", "", "{} select the 20. saved selection"), + ("select.recall21", "Saved Selection 21", "", "{} select the 21. saved selection"), + ("select.recall22", "Saved Selection 22", "", "{} select the 22. saved selection"), + ("select.recall23", "Saved Selection 23", "", "{} select the 23. saved selection"), + ("select.recall24", "Saved Selection 24", "", "{} select the 24. saved selection"), + ("select.recall25", "Saved Selection 25", "", "{} select the 25. saved selection"), + ("type.recentFont1", "Recent Font 1", "", "{} apply the 1. most recently used font"), + ("type.recentFont2", "Recent Font 2", "", "{} apply the 2. most recently used font"), + ("type.recentFont3", "Recent Font 3", "", "{} apply the 3. most recently used font"), + ("type.recentFont4", "Recent Font 4", "", "{} apply the 4. most recently used font"), + ("type.recentFont5", "Recent Font 5", "", "{} apply the 5. most recently used font"), + ("type.recentFont6", "Recent Font 6", "", "{} apply the 6. most recently used font"), + ("type.recentFont7", "Recent Font 7", "", "{} apply the 7. most recently used font"), + ("type.recentFont8", "Recent Font 8", "", "{} apply the 8. most recently used font"), + ("type.recentFont9", "Recent Font 9", "", "{} apply the 9. most recently used font"), + ("type.recentFont10", "Recent Font 10", "", "{} apply the 10. most recently used font"), + ("type.recentFont11", "Recent Font 11", "", "{} apply the 11. most recently used font"), + ("type.recentFont12", "Recent Font 12", "", "{} apply the 12. most recently used font"), + ("type.recentFont13", "Recent Font 13", "", "{} apply the 13. most recently used font"), + ("type.recentFont14", "Recent Font 14", "", "{} apply the 14. most recently used font"), + ("type.recentFont15", "Recent Font 15", "", "{} apply the 15. most recently used font"), + ("file.clearRecent", "Clear Recent Files", "", "{}"), + ("type.findFont", "Find Font…", "", "{} open the Find Font dialog (engine: text.fonts / text.replaceFont / select.font)"), + ( + "ui.missingFontsDialog", + "Missing Fonts Dialog", + "", + "{folder?} open Missing Fonts (dialog `missingFonts`) for the fonts the active document uses that aren't available (text.missingFonts); with folder, it looks for their files there at once (text.findFontFiles). An error when no font is missing. Opening a document whose fonts are missing shows it after the missing linked file questions (dialog `missingLinks`). Disabled on the web", + ), + ( + "ui.findFontsInFolder", + "Find Fonts in Folder…", + "", + "{folder?} Type › Find Font's Find in Folder…: asks for a folder (or takes folder), then opens Missing Fonts looking there for the files of the fonts the active document misses (text.findFontFiles). Disabled where there is no folder picker (the web)", + ), + ("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first; under an automation read root, only the files inside it"), + ( + "file.export.svg", + "Export As SVG…", + "", + "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", + ), + ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.exportForScreens", + "Export for Screens…", + "Cmd+Alt+E", + "{} opens the dialog (on the document's last settings; while the Artboard tool is in use, with the artboards it has selected chosen); with params = document.exportForScreens (no folder on the web: downloads the files or the zip; openLocation: shows the first file in the file manager; a folder on the desktop with Background Export on: the files are written in the background → {background: true, status})", + ), + ("file.documentSetup", "Document Setup…", "Cmd+Alt+P", "{}"), + ("file.newDialog", "New…", "Cmd+N", "{} opens the New Document dialog"), + ( + "file.newWithoutDialog", + "New Without Dialog", + "Cmd+Alt+N", + "{} makes a document with the settings the New Document dialog opens on (the first Recent entry, else the Print category's Letter), named after the next untitled document, without opening the dialog → {index, previewMode}", + ), + ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), + ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), + ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "edit.autoSpellCheck", + "Auto Spell Check", + "", + "{} toggle a red underline under the words of the document's type its dictionaries don't know (text.spelling.check lists them), kept up to date as the type changes; type with effects isn't underlined → whether Auto Spell Check is on", + ), + ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), + ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), + ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), + ("shortcuts.reset", "Reset Keyboard Shortcuts", "", "{}"), + ( + "shortcuts.preset", + "Keyboard Shortcut Set", + "", + "{name: \"VectorCraft Defaults\" | \"Classic Defaults\"} (names of earlier versions are accepted)", + ), + ("shortcuts.export", "Export Keyboard Shortcuts…", "", "{path?}"), + ( + "shortcuts.exportText", + "Export Keyboard Shortcuts as Text…", + "", + "{path?} save the current set's tools and menu commands with their shortcuts as a UTF-8 text file (Keyboard Shortcuts › Export Text…): the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none; without `path`, pick a file", + ), + ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), + ( + "ui.shortcutImportDialog", + "Import Shortcut Set…", + "", + "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", + ), + ("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"), + ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), + ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), + ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), + ("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"), + ( + "view.snapToGlyph", + "Snap to Glyph", + "", + "{} toggle: drawing snaps to live-text glyph bounds, and on a single line of type to its baseline, x-height, character widths and glyph anchor points", + ), + ( + "view.preciseCursors", + "Use Precise Cursors", + "", + "{} toggle General › Use Precise Cursors: the drawing tools' pointers become a crosshair → true when on", + ), + ( + "imageTrace.preview", + "Image Trace Preview", + "", + "{on?: bool} turn the Image Trace panel's Preview on (true), off (false) or toggle it (omitted), as its checkbox does: on, setting changes trace the selected Image Trace object at once; off, they wait for Trace; returns the new state", + ), + ("view.textThreads", "Hide Text Threads", "Cmd+Shift+Y", "{} toggle the thread lines between threaded text frames"), + ("view.gradientAnnotator", "Hide Gradient Annotator", "Cmd+Alt+G", "{} toggle the Gradient tool's annotator"), + ( + "view.livePaintGaps", + "Show Live Paint Gaps", + "", + "{} toggle drawing the gaps of the selected Live Paint groups (those livePaint.info lists) in each group's Gap Preview Color while edges show → true when on", + ), + ("type.hiddenCharacters", "Show Hidden Characters", "Cmd+Alt+I", "{} toggle markers for spaces, paragraph ends and story ends"), + ("type.alignLeft", "Align left", "Cmd+Shift+L", "{} align the selected type's paragraphs (or those the Type tool's selection touches) left"), + ( + "type.alignCenter", + "Align center", + "Cmd+Shift+C", + "{} align the selected type's paragraphs (or those the Type tool's selection touches) centred", + ), + ("type.alignRight", "Align right", "Cmd+Shift+R", "{} align the selected type's paragraphs (or those the Type tool's selection touches) right"), + ("type.justifyLeft", "Justify with last line aligned left", "Cmd+Shift+J", "{} justify the selected type's paragraphs, last line aligned left"), + ("type.justifyAll", "Justify all lines", "Cmd+Shift+F", "{} justify every line of the selected type's paragraphs"), + ( + "type.applyBullets", + "Apply Bullets", + "", + "{bullet?: \"dot\"|\"dash\"|\"circle\"|\"square\"|\"none\"} Type › Bullets and Numbering › Apply Bullets: the selected type's paragraphs (or those the Type tool's selection touches) become a bulleted list with that bullet (text.setFormat {bullet}); without it, a list keeps its bullet and other paragraphs take the dot (text.setFormat {list: \"bullet\"}); \"none\" turns the list off", + ), + ( + "type.applyNumbers", + "Apply Numbers", + "", + "{number?: \"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\"|\"none\"} Type › Bullets and Numbering › Apply Numbers: the selected type's paragraphs (or those the Type tool's selection touches) become a numbered list in that number style (text.setFormat {number}); without it, a numbered list keeps its style and other paragraphs are numbered 1, 2, 3 (text.setFormat {list: \"number\"}); \"none\" turns the list off", + ), + ( + "ui.bulletsAndNumbering", + "Bullets and Numbering…", + "", + "{tab?: \"bullets\"|\"numbers\"} open Bullets and Numbering (More Options in the Paragraph panel's Bullets and Numbered List presets) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, on that tab (without it, Numbers when the paragraphs are a numbered list, else Bullets) (dialog `bulletsAndNumbering`: tab (bullets|numbers), list (none|bullet|number: the kind of the preset picked), bullet (dot|dash|circle|square), number (arabic|upperLetters|lowerLetters|upperRoman|lowerRoman|twoDigits|threeDigits), listAlign (left|right), listLevel (1..9; 1 for paragraphs in no list), leftIndent, firstLineIndent (pt)): the type shows the dialog's values while it is open, OK runs text.setFormat with the values that changed (and the indents it shows when a preset puts the paragraphs in a list), as one undo step, and Cancel puts the type back; a preset picked for paragraphs in no list whose indents are 0 fills in 18 and -18 pt; an error with no type selected or an unknown tab", + ), + ( + "type.convertListToText", + "Convert to Text", + "", + "{} Type › Bullets and Numbering › Convert to Text: the bullets and numbers of the selected type's list paragraphs (or of those the Type tool's selection touches) become characters of the text, followed by a tab, and the lists are turned off (text.convertListToText); the Type tool's anchor and caret move past the characters inserted at or before them, into the frame the caret's character moved to in threaded type", + ), + ( + "align.horizontalLeft", + "Horizontal Align Left", + "", + "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.horizontalCenter", + "Horizontal Align Center", + "", + "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.horizontalRight", + "Horizontal Align Right", + "", + "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.horizontalVerticalCenter", + "Horizontal & Vertical Align Center", + "", + "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.verticalTop", + "Vertical Align Top", + "", + "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.verticalCenter", + "Vertical Align Center", + "", + "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.verticalBottom", + "Vertical Align Bottom", + "", + "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + ), + ( + "align.distributeVerticalTop", + "Vertical Distribute Top", + "", + "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeVerticalCenter", + "Vertical Distribute Center", + "", + "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeVerticalBottom", + "Vertical Distribute Bottom", + "", + "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeHorizontalLeft", + "Horizontal Distribute Left", + "", + "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeHorizontalCenter", + "Horizontal Distribute Center", + "", + "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeHorizontalRight", + "Horizontal Distribute Right", + "", + "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeVerticalSpace", + "Vertical Distribute Space", + "", + "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "align.distributeHorizontalSpace", + "Horizontal Distribute Space", + "", + "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + ), + ( + "type.bold", + "Bold", + "", + "{} the selected type (or the Type tool's selection) in its family's Bold face, or back to the regular face when it is bold; keeps italics. A family without that face is left as it is, with a message. While the Type tool edits text, Cmd+Shift+B", + ), + ( + "type.italic", + "Italic", + "", + "{} the selected type (or the Type tool's selection) in its family's Italic (or Oblique) face, or back upright when it is italic; keeps the weight. A family without that face is left as it is, with a message. While the Type tool edits text, Cmd+Shift+I", + ), + ( + "type.highlightFontName", + "Highlight Font Name", + "Cmd+Alt+Shift+F", + "{} show the Character panel if it is hidden and open its font family menu, whose search field takes the keyboard focus: type to search, Enter applies the highlighted font → {field: \"fontName\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), + ( + "type.highlightKerning", + "Highlight Kerning", + "Cmd+Alt+K", + "{} show the Character panel if it is hidden and give its Kerning field the keyboard focus with its value selected: type a value and press Enter → {field: \"kerning\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), + ( + "type.highlightTracking", + "Highlight Tracking", + "", + "{} show the Character panel if it is hidden and give its Tracking field the keyboard focus with its value selected: type a value and press Enter → {field: \"tracking\"}. Without selected type (or text the Type tool edits) the panel shows, and the error says to select type first", + ), + ( + "type.underline", + "Underline", + "Cmd+Shift+U", + "{} the Character panel's Underline button: underline the selected type (or the Type tool's selection), or remove the underline when the text the Character panel shows is underlined (text.setFormat {underline}) → underlined", + ), + ( + "type.lineComposer", + "Toggle Line Composer", + "Cmd+Alt+Shift+C", + "{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer (text.setFormat {composer}) → \"singleLine\" | \"everyLine\"", + ), + ( + "type.hyphenate", + "Hyphenate", + "Cmd+Alt+Shift+H", + "{} the Paragraph panel's Hyphenate checkbox: hyphenation off for the selected type's paragraphs (or those the Type tool's selection touches) when they all hyphenate, else on (text.setFormat {hyphenate}) → hyphenate", + ), + ("effect.last", "Last Effect…", "Cmd+Alt+Shift+E", "{} open the dialog of the last effect applied"), + ("view.zoomIn", "Zoom In", "Cmd+=", "{}"), + ("view.zoomOut", "Zoom Out", "Cmd+-", "{}"), + ("view.fitArtboard", "Fit Artboard in Window", "Cmd+0", "{}"), + ("view.fitAll", "Fit All in Window", "Cmd+Alt+0", "{}"), + ( + "view.actualSize", + "Actual Size", + "Cmd+1", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling)", + ), + ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), + ( + "view.goToArtboard", + "Go to Artboard", + "", + "{index: 0-based number | \"first\" | \"previous\" | \"next\" | \"last\"} make that artboard the status bar navigator's (the one Fit Artboard in Window and Actual Size show) and fit it in the window → {index}", + ), + ( + "view.firstArtboard", + "First Artboard", + "", + "{} the status bar navigator's First Artboard button: view.goToArtboard {index: \"first\"} → {index}", + ), + ( + "view.previousArtboard", + "Previous Artboard", + "", + "{} the navigator's Previous Artboard button: view.goToArtboard {index: \"previous\"} → {index}", + ), + ("view.nextArtboard", "Next Artboard", "", "{} the navigator's Next Artboard button: view.goToArtboard {index: \"next\"} → {index}"), + ("view.lastArtboard", "Last Artboard", "", "{} the navigator's Last Artboard button: view.goToArtboard {index: \"last\"} → {index}"), + ("view.edges", "Hide Edges", "Cmd+H", "{}"), + ("view.artboards", "Hide Artboards", "Cmd+Shift+H", "{}"), + ( + "view.template", + "Hide Template", + "Cmd+Shift+W", + "{} template layers left off the canvas (Show Template draws them again, dimmed as before) → shown", + ), + ("view.rulers", "Show Rulers", "Cmd+R", "{}"), + ( + "view.videoRulers", + "Show Video Rulers", + "", + "{} the rulers show (as Show Rulers shows them) and count the active artboard in video pixels from its top-left corner, a pixel as wide as its Video Ruler Pixel Aspect Ratio says (artboard.setProps videoRulerPixelAspectRatio) and one point tall; again (Hide Video Rulers), they count in the General unit from the ruler origin as before → whether video rulers show", + ), + ("view.boundingBox", "Hide Bounding Box", "Cmd+Shift+B", "{}"), + ("view.guides", "Hide Guides", "Cmd+;", "{}"), + ("view.smartGuides", "Smart Guides", "Cmd+U", "{}"), + ("view.grid", "Show Grid", "Cmd+'", "{}"), + ("view.snapToGrid", "Snap to Grid", "Cmd+Shift+'", "{}"), + ("view.snapToPoint", "Snap to Point", "Cmd+Alt+'", "{}"), + ("view.presentation", "Presentation Mode", "Shift+F", "{}"), + ("view.screenMode", "Screen Mode", "F", "{mode?: 0..2} (no param cycles)"), + ( + "view.rotate", + "Rotate View", + "", + "{angle: degrees, clockwise on screen as the status bar shows it} turn the view to that angle about the center of the canvas; returns {angle}, normalized to (-180, 180]", + ), + ( + "view.rotateToSelection", + "Rotate View to Selection", + "", + "{} turn the view about the center of the canvas to the angle the selected objects share (selectionRotation in document.inspect, 0 when they differ), so their bounding box is square to the window; returns {angle}", + ), + ("view.rotateReset", "Reset Rotate View", "Cmd+Shift+1", "{}"), + ("window.control", "Control", "", "{}"), + ("window.helpBar", "Help Bar", "", "{} toggle the tool-help strip independently of the status bar; returns the new visibility"), + ( + "window.control.dock", + "Dock Control Bar", + "", + "{edge: \"top\"|\"bottom\"} dock the Control bar to the top of the window, under the menu bar, or to its bottom, as the bar's panel menu (Dock to Top, Dock to Bottom) and a drag of its gripper do; kept with the workspace; another edge is an error and changes nothing; returns {edge}", + ), + ("window.toolbar", "Tools", "", "{}"), + ( + "window.toolbarColumns", + "Toolbar: Single/Double Column", + "", + "{double?: bool, toolbar?: name} show the toolbar's tools (with `toolbar`, that toolbar made with New Toolbar's) in two columns (true), one (false) or toggle (omitted), as the double arrow at the top of the toolbar does; returns the new state", + ), + ("window.toolbarAdvanced", "Toolbar: Advanced / Basic", "", "{}"), + ( + "window.toolsBesideCanvas", + "Keep Tools Beside the Canvas", + "", + "{on?: bool} dock the Tools panel between the left-side panels and the canvas (true) or at the window's left edge (false, the default), or toggle (omitted or null; any other value is an error); a floating Tools panel stays floating and docks at the chosen place when it is docked again. Kept with the workspace; a workspace saved without it docks Tools at the window's edge. Returns the new state", + ), + ( + "window.floatTools", + "Float Tool Group", + "", + "{tool: id, floating?: bool, toolbar?: name} float the toolbar group holding `tool` (in the current Basic or Advanced layout; with `toolbar`, in that toolbar made with New Toolbar) as its own strip of tool buttons (true), put it back in the toolbar (false) or toggle (omitted), as dragging or clicking a flyout's tear-off bar and the strip's × do; returns the new state", + ), + ( + "toolbar.show", + "Toolbar: Show Controls", + "", + "{control?: \"fillStroke\"|\"coloring\"|\"drawMode\"|\"screenMode\", on?: bool} show (true), hide (false) or toggle (omitted) one of the controls under the toolbar's tools (Fill and Stroke, Coloring, Draw Mode, Screen Mode), as the All Tools drawer's Show section does; saved with the preferences; returns every control's state", + ), + ( + "window.editToolbar", + "Edit Toolbar", + "", + "{open?: bool, toolbar?: name} open (true), close (false) or toggle (omitted) the All Tools drawer beside the toolbar (with `toolbar`, beside that toolbar made with New Toolbar, which shows), as the toolbar's ••• button does; while it is open, tools drag from it onto the toolbar and from the toolbar into it (Escape or a click outside closes it); returns the new state", + ), + ( + "toolbar.addTool", + "Toolbar: Add Tool", + "", + "{tool: id, slot?: n, place?: \"before\"|\"after\"|\"group\", toolbar?: name} put `tool` in the current (Basic or Advanced) toolbar (with `toolbar`, in that toolbar made with New Toolbar), moving it if it is there already: before (default) or after slot `slot` (0 = the first; omitted: at the end) in its own slot, or into that slot's group (its flyout), as dropping a tool from the Edit Toolbar drawer does; saved with the preferences; returns the toolbar's slots (lists of tool ids)", + ), + ( + "toolbar.removeTool", + "Toolbar: Remove Tool", + "", + "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", + ), + ( + "toolbar.reset", + "Toolbar: Reset", + "", + "{toolbar?: name} put the current (Basic or Advanced) toolbar back as it ships, undoing Edit Toolbar's changes (with `toolbar`, make that toolbar made with New Toolbar blank again); returns its slots", + ), + ( + "window.toolbar.new", + "New Toolbar…", + "", + "{name?: string} make a blank toolbar called `name`, of at most 200 characters (omitted: a dialog asks for the name), floating beside the Tools panel and listed under Window › Toolbars; its ••• button opens the All Tools drawer to fill it (window.editToolbar with `toolbar`); it is kept with the current workspace; returns {toolbar: name}", + ), + ( + "window.toolbar.custom", + "Show Toolbar", + "", + "{name: string, show?: bool} show (true), hide (false) or toggle (omitted) the toolbar made with New Toolbar called `name`, as its item under Window › Toolbars does (its title bar's × hides it); shown after Tab hid the toolbars, it shows alone and the others are turned off; returns the new state", + ), + ( + "window.toolbar.manage", + "Manage Toolbars…", + "", + "{} open the Manage Toolbars dialog, which lists the toolbars made with New Toolbar: a name typed for the selected one renames it, + copies it (none selected: makes a blank toolbar) and the trash can deletes it", + ), + ( + "window.toolbar.rename", + "Rename Toolbar", + "", + "{name: string, to: string} give the toolbar made with New Toolbar called `name` the name `to` (not empty, at most 200 characters, not another toolbar's whatever the case), as typing a name in Manage Toolbars does; returns {toolbar: name}", + ), + ( + "window.toolbar.duplicate", + "Duplicate Toolbar", + "", + "{name?: string} copy the toolbar made with New Toolbar called `name`, with its tools, as \"`name` Copy\" (omitted: make a blank toolbar called \"Toolbar N\"), as Manage Toolbars' + does; the copy shows and is kept with the current workspace; returns {toolbar: name}", + ), + ( + "window.toolbar.delete", + "Delete Toolbar", + "", + "{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does", + ), + ("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"), + ("window.taskBar", "Contextual Task Bar", "", "{}"), + ( + "window.pathfinder.compoundShapes", + "Shape Mode Buttons Make Compound Shapes", + "", + "{} toggles the Compound Shapes add-on's setting: on, the Pathfinder panel's Shape Mode buttons make a compound shape and Alt-click gives the permanent Pathfinder result; off (the default), the other way round. Members of a compound shape selected always take the mode", + ), + ( + "window.taskBar.pin", + "Pin Bar Position", + "", + "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", + ), + ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.dock", + "Panels", + "Tab", + "{} hide the panels, the toolbar and the Control bar, or show again the ones the last Tab hid (all three when none of them shows and Tab hid none); returns whether it showed them", + ), + ( + "window.panels", + "Panels Except Tools and Control", + "Shift+Tab", + "{} show/hide the dock and the floating panels (hiding them closes a panel popped out of the icon column), leaving the toolbar and the Control bar as they are; returns whether the panels show", + ), + ( + "window.panel", + "Show Panel", + "", + "{panel: id, toggle?: bool} e.g. layers, swatches, stroke (case-insensitive; display labels like \"Layers\" work too); toggle (the Window menu) hides a panel that shows, and shows it again where it was", + ), + ( + "window.panel.layout", + "Change Panel Layout", + "", + "{action} serialized docking action, including floating geometry, divider sizes and accordion state", + ), + ( + "window.panel.move", + "Move Panel", + "", + "{panel, anchor, zone?: tab|center|left|right|top|bottom|above|below, before?: panel, group?: bool, placement?} move a panel (with `group`, its whole group) into the group holding `anchor`: as a tab (before the `before` panel; null appends), a split beside it, or (`above` / `below`) a group of its own above or below it in its dock column or floating window; `placement` (a serialized Placement) replaces zone and before", + ), + ("window.panel.activate", "Activate Panel", "", "{panel} show and select a panel in its current group"), + ("window.panel.close", "Close Panel", "", "{panel} hide a panel"), + ( + "window.panel.collapse", + "Collapse Panel Group", + "", + "{panel, collapsed?: bool} minimize the group holding a panel to its tabs (in a floating window, the window to its title bar), or restore it, as a double-click on a tab or the drag bar does; the same as window.panel.minimize {panel, minimized}. Without `collapsed` it toggles. Returns {panel, collapsed, layout}", + ), + ( + "window.panel.float", + "Float Panel", + "", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + ), + ( + "window.panel.dock", + "Dock Panel", + "", + "{panel: id or \"tools\", anchor?: id, zone?: tab|center|left|right|top|bottom|above|below, before?: id, group?: bool, column?: bool or n, side?: Start|End, onto?: id, above?: id, below?: id, icon?: bool, collapsed?: bool} dock a panel (with `group`, its whole group): with no destination a floating panel goes back where it floated from (else joins the first dock group) and a hidden one shows where it was; with `anchor` (or `onto`) in the group holding that panel, `zone` as for window.panel.move; with `side`, as a new innermost column of that dock (`column: true` then moves its whole dock column or floating window); `column: n` with no other destination docks its group, or the whole floating window it floats in, as a new dock column at that place (1: next to the icon column, counting inwards; `true`: innermost); `icon: true` puts it in a row of its own at the end of the icon column; `above` / `below` as a group of its own above or below the group holding that panel. `collapsed` then minimizes or restores its group. \"tools\" docks the Tools panel at the left edge of the window, or beside the canvas inside any left-side dock while window.toolsBesideCanvas is on; with side: right (or End) on the right, between the canvas and the panels, as dropping it there or on the window's right edge does (default: the side it docked at last; left or Start docks it on the left), returning {panel, floating, pos, side}. Returns {layout, closed, floating}", + ), + ( + "window.collapseDock", + "Collapse Panels to Icons", + "", + "{collapsed?: bool} collapse every expanded dock column to icons (true), expand the outer dock column, Properties | Layers | Libraries (false), or toggle the outer column (omitted), as the double arrow at the top of the dock does; returns the new state", + ), + ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), + ( + "window.workspace", + "Workspace", + "", + "{name} switch workspace (Essentials, Essentials Classic, Painting, …): the one left keeps its layout changes, and the one switched to comes back as it was left (as saved if never changed)", + ), + ( + "window.workspace.reset", + "Reset Essentials", + "", + "{} reset the current workspace to the way it was saved, dropping the layout changes made in it", + ), + ("window.workspace.new", "New Workspace…", "", "{name?} save the current layout"), + ("window.workspace.manage", "Manage Workspaces…", "", "{}"), + ("window.workspace.delete", "Delete Workspace", "", "{name}"), + ("window.workspace.rename", "Rename Workspace", "", "{name, to}"), + ("window.workspace.list", "List Workspaces", "", "{}"), + ( + "window.newWindow", + "New Window", + "", + "{} open another view of the current document, with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own (titled with the view's number, \"Name:2\") or, when the current view floats, in a floating window; it becomes the current window; the Arrange commands treat each view as a window; file.close closes the current view and the last view closes the document; returns {index, view}", + ), + ( + "window.arrange.cascade", + "Cascade", + "", + "{} put every open document in a floating window of its own and stack the windows from the upper left of the document area to its lower right, 30 pt apart, in tab order, each fitted to its window, the current document's in front; on the desktop each is an OS window, on the web and Wayland a window inside the app's window; returns {floating} (document indices)", + ), + ( + "window.arrange.tile", + "Tile", + "", + "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + ), + ( + "window.arrange.floatInWindow", + "Float in Window", + "", + "{index?, view?, at?: [x, y]} move the current window, or document `index`'s view `view` (its current view without one; it becomes the current window), out of the tab strip into a floating window of its own, fitted to it, with the window's top-left corner at `at` (main window points) or else at the next place of a cascade; dragging a document tab more than 24 pt above or below the tab strip does this at the pointer; the window holding the current document takes the tools, a click in another document's window makes its document the current one; a document already floating stays where it is; returns {floating} (document indices)", + ), + ( + "window.arrange.floatAllInWindows", + "Float All in Windows", + "", + "{} move every document under the tab strip into a floating window of its own, at the next places of a cascade; returns {floating} (document indices)", + ), + ( + "window.arrange.consolidateAllWindows", + "Consolidate All Windows", + "", + "{index?, view?} show one document at a time again, under its tab, after Tile, Float in Window, Float All in Windows or Cascade; returns {tiled: false, floating: []}; with `index`, only document `index` (its view `view`, else its current view) goes back under its tab and becomes the current one, the other windows and Tile staying as they are, as when a document window is dragged by its title bar (an OS window by the tab at its top) onto the tab strip; returns {tiled, floating} (document indices)", + ), + ( + "window.nextDocument", + "Next Document", + "Cmd+F6", + "{} make the open document after the current one in tab order the current one, as a click on its tab does (after the last document it goes to the first, and from the Home screen to the first); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", + ), + ( + "window.previousDocument", + "Previous Document", + "Cmd+Shift+F6", + "{} make the open document before the current one in tab order the current one, as a click on its tab does (before the first document it goes to the last, and from the Home screen to the last); each view window.newWindow opened is a step of its own; returns {index}, with `view` for a document with more than one view", + ), + ("tool.select", "Select Tool", "", "{tool: id} (see tools)"), + ( + "tool.setOption", + "Tool Option", + "", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + ), + ( + "effect.dialog", + "Effect…", + "", + "{effect: id, index?: int (edit that applied effect in place, prefilled; OK runs effect.setParams), item?: appearance item index|null (the fill/stroke whose effects, null the object's; default: the Appearance panel's active item), aligned?: bool (index and item are rows of the first selected object's stack, which OK edits in each object where it has them, as effect.setParams does)} open the effect's dialog with live preview; without `index`, an effect already in that list first opens `effectExists` (confirm edits it, discard adds another) → {pending: \"effectExists\"}", + ), + ("ui.paramDialog", "Command Dialog", "", "{command, label?, params} open a parameter dialog for any command"), + ( + "ui.recolorDialog", + "Recolor Artwork…", + "", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + ), + ( + "ui.cropImage", + "Crop Image", + "", + "{} show a crop box on the selected image (tool `cropImage`): it starts on the part over the image's artboard; drag its handles or inside it, then Enter or the Control bar's Apply crops the image to it (object.cropImage {rect}), Escape or Cancel leaves it as it is, both back to the Selection tool. tool.setOption {key: \"rect\", value: [x, y, width, height]} sets the box", + ), + ("effect.applyLast", "Apply Last Effect", "Cmd+Shift+E", "{}"), + ( + "pathfinder.repeat", + "Repeat Pathfinder", + "Cmd+4", + "{} repeat the last successful Pathfinder panel operation, direct object.pathfinder.* command or command.batch step on the selection with current Pathfinder Options; an error until one has run", + ), + ( + "file.export.pdf", + "Save as PDF…", + "", + "{} opens the Save PDF dialog; with params = document.exportPdf options written to path (asked when missing; viewAfterSaving opens the file) → {path, bytes, warnings}", + ), + ("help.about", "About VectorCraft", "", "{}"), + ("help.checkForUpdates", "Check for Updates…", "", "{}"), + ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.safeMode", + "Safe Mode…", + "", + "{} open the Safe Mode dialog (dialog `safeMode`): whether VectorCraft is in Safe Mode, and the disabled plug-ins, each with Enable on Re-launch (engine: plugin.setEnabled). Closing it leaves Safe Mode as it is; Safe Mode is chosen at launch (--safe-mode, or the choice after a launch that stopped while a plug-in was loading, dialog `pluginStopped`)", + ), + ("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"), + ( + "ui.swatchOptions", + "Swatch Options…", + "", + "{name} edit a swatch: Swatch Options for a colour (dialog `swatchOptions`, engine: swatch.edit) or a gradient (the same dialog with `name` only; it shows the gradient), pattern editing for a pattern", + ), + ( + "ui.newSwatch", + "New Swatch…", + "", + "{spot?, global?, group?: colour group name} open New Swatch for the active fill or stroke (dialog `newSwatch`, engine: swatch.new); a color opens as a spot color with `spot`, and as a global process color with `global` alone", + ), + ( + "ui.newColorGroup", + "New Color Group…", + "", + "{swatches?: [names]} open New Color Group, from those swatches or the selected artwork (dialog `newColorGroup`, engine: swatch.newGroup)", + ), + ( + "ui.colorPicker", + "Color Picker…", + "", + "{stroke?: bool (default: the active proxy), artboard?: index (the picker is for that artboard's background color instead), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's color, or the artboard's color, white when it has none)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); RGB, HSB and hex values use the working RGB space; OK runs paint.setFill / paint.setStroke, or artboard.setProps {index, color} for an artboard", + ), + ( + "ui.sampleScreenColor", + "Sample Color from Screen", + "", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; Escape cancels it and the colors stay as they were. ui.inspect reports `screenSampler: true` until it answers. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + ), + ( + "ui.newBrush", + "New Brush…", + "", + "{ids?} (default: the selected art) open New Brush, what the Brushes panel's New Brush button and art dropped on the panel open (dialog `newBrush`, field `type`: calligraphic|scatter|art|bristle|pattern, Art when there is art, else Calligraphic; scatter, art and pattern need art, else OK gives the error `nothing selected`); OK opens that type's Brush Options for the new brush (dialog `brushOptions` with the fields of ui.brushOptions and `__create`; name: New Brush, numbered when taken; the `ids` given in `__ids`), whose OK runs brush.new {type, name, params, ids?} (a name another brush has gets a number) and whose Cancel adds no brush", + ), + ( + "ui.brushOptions", + "Brush Options…", + "", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + ), + ( + "ui.graphicStyleOptions", + "Graphic Style Options…", + "", + "{name?} open Graphic Style Options (dialog `graphicStyleOptions`, field `name`): for style `name` OK renames it (graphicStyle.rename); without, OK makes a new style of that name from the selection (graphicStyle.new)", + ), + ( + "ui.charStyleOptions", + "Character Style Options", + "", + "{name} open Character Style Options (dialog `charStyleOptions`); OK runs charStyle.edit with name, to and sparse attrs in one undo step; Cancel restores a live preview", + ), + ( + "ui.charStyleOptions.resetPanel", + "Reset Panel", + "", + "{} clear the settings of the section shown, Basic Character Formats, Advanced Character Formats, Character Color or OpenType Features, in the open Character Style Options or New Character Style dialog; available only on those sections", + ), + ( + "ui.newCharStyle", + "New Character Style…", + "", + "{} open New Character Style (dialog `newTextStyle`, field `name`, filled in with the name charStyle.new {} would give the style), what Alt-clicking the Character Styles panel's New button opens; OK runs charStyle.new with the name and the Type tool's selected characters (else the selected type) as they were when the dialog opened; Cancel adds no style", + ), + ( + "ui.newParaStyle", + "New Paragraph Style…", + "", + "{} open New Paragraph Style (dialog `newTextStyle`, field `name`, filled in with the name paraStyle.new {} would give the style), what Alt-clicking the Paragraph Styles panel's New button opens; OK runs paraStyle.new with the name and the paragraph of the Type tool's selection (else the selected type) as it was when the dialog opened; Cancel adds no style", + ), + ( + "ui.symbolOptions", + "Symbol Options…", + "F8", + "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + ), + ( + "tool.options", + "Tool Options…", + "", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil and paintbrush, the same at any zoom; pt for smooth and blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + ), + ( + "ui.colorGuideOptions", + "Color Guide Options…", + "", + "{} open Color Guide Options (dialog `colorGuideOptions`, fields `steps` 1–20 and `amount` 0–100): OK sets the Color Guide panel's variation grid (read back with `ui.inspect`: ui.color_guide; engine: color.harmony)", + ), + ( + "ui.colorBalanceDialog", + "Adjust Color Balance…", + "", + "{} open Adjust Colors for the selection (dialog `colorBalance`, fields `mode` gray|rgb|cmyk|global, channels r g b / c m y k / gray / tint (global) −100..100, `convert`, `fill`, `stroke`, `preview`): previews live, OK runs edit.colors.adjustBalance as one undo step", + ), + ( + "ui.saturateDialog", + "Saturate…", + "", + "{} open Saturate for the selection (dialog `saturate`, fields `intensity` −100..100, `preview`): previews live, OK runs edit.colors.saturate as one undo step", + ), + ( + "window.swatchLibrary", + "Swatch Library", + "", + "{library: id or name (see swatch.library.list), or the id of a persistent panel's missing library | null (close every swatch library panel)} open the swatch library in a read-only panel of its own, floating (panel id `library:swatches:`, which window.panel.* moves, docks and closes), or bring its panel forward when it is open; clicking a swatch there runs swatch.library.add with apply. ui.libraryPanel sets its view, find field and Persistent (ui.inspect: ui.library_panels) → {open: id, panel, name, count}", + ), + ( + "window.swatchLibrary.other", + "Other Library…", + "", + "{path?} (default: pick a file) load a .vcswatches, .gpl, .ase or .acb (color book) library, or another document's swatches (engine: swatch.library.load), and open it in its library panel", + ), + ( + "ui.libraryPanel", + "Library Panel Options", + "", + "{panel: a library panel's id (`library:swatches:pastels`, as window.swatchLibrary answers), library?: id or name of another library of its kind to show in the panel (Previous / Next Library; one open in a panel of its own is brought forward instead), view?: smallThumb|mediumThumb|largeThumb|smallList|largeList, showFind?: bool, persistent?: bool (reopen the panel when the app starts)} set an open library panel, or a closed persistent one's view, Show Find Field and Persistent; kept with the preferences (ui.inspect: ui.library_panels) → {panel, kind, library, view, showFind, persistent, open}", + ), + ( + "ui.libraryPanel.locate", + "Locate Library…", + "", + "{panel: an open library panel's id, path?} (default: pick a file) Locate Library… of a persistent library panel whose library's file is missing: load the library from the file, as Other Library… does, and show it in the panel, which keeps its view, Show Find Field and Persistent. When the file's library has a panel open already, the panel closes and that one is brought forward, made persistent when the closed one was → what ui.libraryPanel answers", + ), + ( + "ui.saveSwatchLibrary", + "Save Swatch Library…", + "", + "{names?: [the swatches selected in the Swatches panel]} open Save Swatch Library (dialog `saveSwatchLibrary`: name, format: vcswatches|gpl|ase|css, user: save to the user library folder, selectedOnly); OK runs swatch.library.save", + ), + ("window.userSwatchLibrary1", "User Swatch Library 1", "", "{} open the 1. User Defined swatch library (swatch.library.list, category user)"), + ("window.userSwatchLibrary2", "User Swatch Library 2", "", "{} open the 2. User Defined swatch library"), + ("window.userSwatchLibrary3", "User Swatch Library 3", "", "{} open the 3. User Defined swatch library"), + ("window.userSwatchLibrary4", "User Swatch Library 4", "", "{} open the 4. User Defined swatch library"), + ("window.userSwatchLibrary5", "User Swatch Library 5", "", "{} open the 5. User Defined swatch library"), + ("window.userSwatchLibrary6", "User Swatch Library 6", "", "{} open the 6. User Defined swatch library"), + ("window.userSwatchLibrary7", "User Swatch Library 7", "", "{} open the 7. User Defined swatch library"), + ("window.userSwatchLibrary8", "User Swatch Library 8", "", "{} open the 8. User Defined swatch library"), + ("window.userSwatchLibrary9", "User Swatch Library 9", "", "{} open the 9. User Defined swatch library"), + ("window.userSwatchLibrary10", "User Swatch Library 10", "", "{} open the 10. User Defined swatch library"), + ( + "ui.mergeGraphicStyles", + "Merge Graphic Styles…", + "", + "{names: [two or more styles]} open Graphic Style Options (dialog `graphicStyleOptions`, field `name`) to name the style OK merges from them (graphicStyle.merge)", + ), + ( + "ui.layerOptions", + "Options for Selection…", + "", + "{ids?|id?} open Layer Options for Layers panel rows (default: the highlighted rows, else the current layer), filled in from the first: dialog `layerOptions`, fields name, color (a preset name such as \"Light Blue\" or #rrggbb), template, locked, visible, printable, preview, dimImages (bool), dimPercent (0–100); an object's row has name, visible and locked. OK runs layer.setProps (one undo step); for several rows it sends only the fields set in the dialog", + ), + ( + "ui.rename", + "Rename", + "", + "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}", + ), + ( + "ui.newLayer", + "New Layer Options…", + "Cmd+Alt+L", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields", + ), + ( + "ui.newArtboard", + "New Artboard Options…", + "", + "{} open Artboard Options for a new artboard, filled in as artboard.new {} would make it (Artboard N, the last artboard's size, 20 pt to its right): dialog `artboardOptions` with new: true, fields name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.new with the fields and makes the new artboard the active one; Cancel adds nothing", + ), + ( + "artboard.selectAll", + "Select All Artboards", + "", + "{} the Artboard tool, chosen first when another tool is in use, selects every artboard, and the active artboard stays active; the art's selection stays as it is, and no undo step is recorded → {selected: [index…]} (the active artboard first)", + ), + ( + "ui.layersPanelOptions", + "Panel Options…", + "", + "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + ), + ( + "ui.navigatorPanelOptions", + "Panel Options…", + "", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + ), + ( + "ui.layersExpand", + "Expand Layers Panel Rows", + "", + "{ids?: [id…] (default: every row that holds others), open?: bool (default true)} open or close rows of the Layers panel, as clicking their triangles does → {count}", + ), + ( + "ui.layersFilter", + "Filter Layers Panel Rows", + "", + "{objects?: [paths|shapes|text|images|effects|groups|linkedFiles|guides], layers?: [locked|hidden]} set the Layers panel's Filter (By Object, By Layer): a row stays when it is of a kind in `objects` and in a state in `layers` (its own lock or eye; an empty list takes every row), or when a row inside it stays; Search All narrows the rows further. A key left out keeps its list. The filter lasts the session and does not change the document, its open rows or the selection → {objects, layers}", + ), + ( + "ui.tileEdgeColor", + "Tile Edge Color…", + "", + "{} open Tile Edge Color (dialog `tileEdgeColor`, field `color`: #rrggbb or a preset name such as \"Light Blue\"); OK sets the preference patternTileEdgeColor (prefs.set), the colour of the tile edge and swatch bounds in pattern editing mode; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing", + ), + ( + "ui.flattenTransparencyDialog", + "Flatten Transparency…", + "", + "{} open Flatten Transparency for the selection (dialog `flattenTransparency`, fields `preset` (a preset name: setting it loads its options), balance 0..100, lineArtPpi, gradientPpi 1..2400, textToOutlines, strokesToOutlines, clipComplexRegions, antiAlias, preserveAlpha, preserveOverprints, `preview` (off at first)): OK runs object.flattenTransparency with those options as one undo step", + ), + ( + "ui.flattenerPresetsDialog", + "Transparency Flattener Presets…", + "", + "{selected?: preset name} open the presets manager (dialog `flattenerPresets`, fields `selected`, then the selected preset's `name` and option keys: setting them on a saved preset saves it, a new `name` renames it; built-in presets don't change). New, Delete, Import… and Export… run flattener.presets.save / delete / import / export", + ), + ( + "ui.imageTracePresetDialog", + "Save as New Preset…", + "", + "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", + ), + ( + "ui.flattenerPreview", + "Flattener Preview", + "", + "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", + ), + ( + "ui.copyScriptConsole", + "Copy Script Console", + "", + "{first?, last?: numbers of lines the Script Console holds, both or neither} copy those lines of the Script Console to the clipboard as the panel shows them, each with its run's number and script name; without them every line, after a line counting the lines it dropped and cut when it dropped or cut any, which n does not count (Script Console panel: Copy Selected, Copy All; script.console gives the lines) → {lines: n}", + ), + ( + "window.graphicStyleLibrary", + "Graphic Style Library", + "", + "{library: id or name (see graphicStyle.libraries), or the id of a persistent panel's missing library | null (close every graphic style library panel)} open the graphic style library in a read-only panel of its own, floating (panel id `library:graphicStyles:`), or bring its panel forward when it is open; clicking a style there runs graphicStyle.addFromLibrary with apply (Alt: add). ui.libraryPanel sets its view, find field and Persistent → {open: id, panel, name, count}", + ), + ( + "window.graphicStyleLibrary.other", + "Other Library…", + "", + "{path?} (default: pick a file) load a .vcstyles library, or another document's graphic styles (engine: graphicStyle.loadLibrary), and open it in its library panel", + ), + ( + "ui.saveGraphicStyleLibrary", + "Save Graphic Style Library…", + "", + "{names?: [the styles selected in the Graphic Styles panel]} open Save Graphic Style Library (dialog `saveGraphicStyleLibrary`: name, user: save to the user library folder, selectedOnly); OK runs graphicStyle.saveLibrary", + ), + ( + "ui.loadCharStyles", + "Load Character Styles…", + "", + "{path?} (default: pick a document in an open dialog; cancelling it loads nothing) add that document's character styles to the active one (engine: charStyle.load), the Character Styles panel menu's Load Character Styles…", + ), + ( + "ui.loadParaStyles", + "Load Paragraph Styles…", + "", + "{path?} (default: pick a document in an open dialog; cancelling it loads nothing) add that document's paragraph styles to the active one (engine: paraStyle.load), the Paragraph Styles panel menu's Load Paragraph Styles…", + ), + ( + "ui.loadAllStyles", + "Load All Styles…", + "", + "{path?} (default: pick a document in an open dialog; cancelling it loads nothing) add that document's character and paragraph styles to the active one (engine: textStyle.loadAll), Load All Styles… in either panel's menu", + ), + ( + "window.userGraphicStyleLibrary1", + "User Graphic Style Library 1", + "", + "{} open the 1. User Defined graphic style library (graphicStyle.libraries, category user)", + ), + ("window.userGraphicStyleLibrary2", "User Graphic Style Library 2", "", "{} open the 2. User Defined graphic style library"), + ("window.userGraphicStyleLibrary3", "User Graphic Style Library 3", "", "{} open the 3. User Defined graphic style library"), + ("window.userGraphicStyleLibrary4", "User Graphic Style Library 4", "", "{} open the 4. User Defined graphic style library"), + ("window.userGraphicStyleLibrary5", "User Graphic Style Library 5", "", "{} open the 5. User Defined graphic style library"), + ("window.userGraphicStyleLibrary6", "User Graphic Style Library 6", "", "{} open the 6. User Defined graphic style library"), + ("window.userGraphicStyleLibrary7", "User Graphic Style Library 7", "", "{} open the 7. User Defined graphic style library"), + ("window.userGraphicStyleLibrary8", "User Graphic Style Library 8", "", "{} open the 8. User Defined graphic style library"), + ("window.userGraphicStyleLibrary9", "User Graphic Style Library 9", "", "{} open the 9. User Defined graphic style library"), + ("window.userGraphicStyleLibrary10", "User Graphic Style Library 10", "", "{} open the 10. User Defined graphic style library"), + ( + "window.symbolLibrary", + "Symbol Library", + "", + "{library: id or name (see symbol.libraries) | null (close)} open a symbol library in a library panel of its own (UI state `library_panels`, kind symbols); clicking a symbol there runs symbol.addFromLibrary, dragging one onto the canvas runs it with place → {open, panel, name, count}", + ), + ( + "window.symbolLibrary.other", + "Other Library…", + "", + "{path?} (default: pick a file) load the symbols of another document or a saved symbol library (engine: symbol.loadLibrary), and open them in a library panel", + ), + ( + "ui.saveSymbolLibrary", + "Save Symbols…", + "", + "{names?: [the symbol selected in the Symbols panel]} open Save Symbol Library (dialog `saveSymbolLibrary`: name, user: save to the user library folder, selectedOnly); OK runs symbol.saveLibrary", + ), + ("window.userSymbolLibrary1", "User Symbol Library 1", "", "{} open the 1. User Defined symbol library (symbol.libraries, category user)"), + ("window.userSymbolLibrary2", "User Symbol Library 2", "", "{} open the 2. User Defined symbol library"), + ("window.userSymbolLibrary3", "User Symbol Library 3", "", "{} open the 3. User Defined symbol library"), + ("window.userSymbolLibrary4", "User Symbol Library 4", "", "{} open the 4. User Defined symbol library"), + ("window.userSymbolLibrary5", "User Symbol Library 5", "", "{} open the 5. User Defined symbol library"), + ("window.userSymbolLibrary6", "User Symbol Library 6", "", "{} open the 6. User Defined symbol library"), + ("window.userSymbolLibrary7", "User Symbol Library 7", "", "{} open the 7. User Defined symbol library"), + ("window.userSymbolLibrary8", "User Symbol Library 8", "", "{} open the 8. User Defined symbol library"), + ("window.userSymbolLibrary9", "User Symbol Library 9", "", "{} open the 9. User Defined symbol library"), + ("window.userSymbolLibrary10", "User Symbol Library 10", "", "{} open the 10. User Defined symbol library"), + ( + "window.brushLibrary", + "Brush Library", + "", + "{library: id or name (see brush.libraries) | null (close)} open a brush library in a library panel of its own (UI state `library_panels`, kind brushes); clicking a brush there runs brush.addFromLibrary (with apply when paths are selected), dragging one onto a path runs it with apply on that path, dragging one onto the Brushes panel adds it → {open, panel, name, count}", + ), + ( + "window.brushLibrary.other", + "Other Library…", + "", + "{path?} (default: pick a file) load the brushes of another document or a saved brush library (engine: brush.loadLibrary), and open them in a library panel", + ), + ( + "ui.saveBrushLibrary", + "Save Brushes…", + "", + "{names?: [the brushes selected in the Brushes panel]} open Save Brush Library (dialog `saveBrushLibrary`: name, user: save to the user library folder, selectedOnly); OK runs brush.saveLibrary", + ), + ("window.userBrushLibrary1", "User Brush Library 1", "", "{} open the 1. User Defined brush library (brush.libraries, category user)"), + ("window.userBrushLibrary2", "User Brush Library 2", "", "{} open the 2. User Defined brush library"), + ("window.userBrushLibrary3", "User Brush Library 3", "", "{} open the 3. User Defined brush library"), + ("window.userBrushLibrary4", "User Brush Library 4", "", "{} open the 4. User Defined brush library"), + ("window.userBrushLibrary5", "User Brush Library 5", "", "{} open the 5. User Defined brush library"), + ("window.userBrushLibrary6", "User Brush Library 6", "", "{} open the 6. User Defined brush library"), + ("window.userBrushLibrary7", "User Brush Library 7", "", "{} open the 7. User Defined brush library"), + ("window.userBrushLibrary8", "User Brush Library 8", "", "{} open the 8. User Defined brush library"), + ("window.userBrushLibrary9", "User Brush Library 9", "", "{} open the 9. User Defined brush library"), + ("window.userBrushLibrary10", "User Brush Library 10", "", "{} open the 10. User Defined brush library"), + ( + "ui.expandDialog", + "Expand…", + "", + "{} open Expand for the selection (dialog `expand`, fields object, fill, stroke (all on; one the selection has nothing for is disabled, see object.expand.info), gradient: objects|mesh, steps 1..1000 (255)): OK runs object.expand with them as one undo step; dimmed, and an error, while the selection has an appearance effect.expandAppearance expands (object.expand.info's appearance)", + ), + ( + "attributes.openUrl", + "Browser", + "", + "{url?} open url, else the selection's URL (attributes.info), in the web browser (the Attributes panel's Browser button; http, https and mailto URLs only; not over the control channel or MCP) → {url}", + ), + ( + "ui.javascriptFilesDialog", + "Link JavaScript Files…", + "", + "{} open JavaScript Files for the active document (dialog `javascriptFiles`, fields `file`: a path or URL and `selected`: a linked file; the SVG Interactivity panel's Link JavaScript Files button): its list shows svgInteractivity.info's files, Add runs svgInteractivity.addFile with file and Remove runs svgInteractivity.removeFile with selected", + ), + ( + "ui.svgFilterDialog", + "Apply SVG Filter…", + "", + "{index?, item?} open Apply SVG Filter for the active document (dialog `svgFilter`, fields `selected`: a filter's name, `code`: the code being edited, `editing`: \"\", \"new\" or the name of the filter being edited; with index, for the applied svg.filter effect at index of item, as effect.dialog opens it): its list shows svgFilter.list's filters; OK runs svgFilter.apply with selected, or effect.setParams on the applied effect; New and Edit open the code, Save runs svgFilter.define, Delete runs svgFilter.delete and Import… svgFilter.import with a picked SVG file", + ), + ( + "ui.importSvgFilter", + "Import SVG Filter…", + "", + "{} pick an SVG file and add its filters to the active document's SVG filters (svgFilter.import) → svgFilter.import's result", + ), + ( + "ui.spotColors", + "Spot Colors…", + "", + "{} open Spot Colors (dialog `spotColors`, field `useLab`: true shows and separates Lab spot colours from their Lab values, false from their CMYK equivalents); OK runs swatch.spotOptions as one undo step", + ), + ( + "ui.menuDialog", + "Menu Dialog", + "", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + ), + ( + "ui.widthPointEdit", + "Width Point Edit…", + "", + "{id, index?: existing width point, t?: 0..1 for a new point, adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; double-clicking the stroke opens it too, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set; discard: true (Delete) removes an existing point or discards a prospective point", + ), + ( + "ui.corners", + "Corners…", + "", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", + ), + ( + "ui.simplifyAuto", + "Auto-Simplify", + "", + "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + ), + ( + "ui.smoothAuto", + "Auto-Smooth", + "", + "{} the open Smooth slider (Object › Path › Smooth opens it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + ), + ( + "ui.simplifyMoreOptions", + "More Options", + "", + "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + ), + ( + "ui.dialogReset", + "Reset", + "", + "{} the open dialog's Reset, which its Cancel button reads while Alt (Option on macOS) is held (Flare Tool Options, dialog `flareOptions`): its fields go back to their defaults and the dialog stays open, so OK applies them → the dialog; an error when no dialog is open or the open one has no Reset", + ), + ( + "ui.justification", + "Justification…", + "", + "{} open Justification (the Paragraph panel menu's Justification…) on the paragraphs the Paragraph panel acts on, filled in with the values it shows, with Preview (dialog `justification`: wordMin, wordDesired, wordMax 0..1000, letterMin, letterDesired, letterMax -100..500, glyphMin, glyphDesired, glyphMax 50..200 (percent), autoLeading 0..500 (percent), singleWord (fullJustify|alignLeft|alignCenter|alignRight), preview): OK runs text.setFormat with the values that changed, as one undo step, and is disabled while a row's Minimum exceeds its Desired or Desired its Maximum; an error with no type selected", + ), + ( + "ui.hyphenation", + "Hyphenation…", + "", + "{} open Hyphenation (the Paragraph panel menu's Hyphenation…) on the paragraphs the Paragraph panel acts on, filled in with the values it shows (dialog `hyphenation`: hyphenate, wordsLongerThan 1..25, afterFirst 1..15, beforeLast 1..15, hyphenLimit 0..25 (0: no limit), hyphenationZone (pt), hyphenateCapitalized): OK runs text.setFormat with the values that changed, as one undo step; an error with no type selected", + ), + ( + "ui.tateChuYokoSettings", + "Tate-chu-yoko Settings…", + "", + "{} open Tate-chu-yoko Settings (the Character panel menu's Tate-chu-yoko Settings…, with Show East Asian Options) on the characters the Character panel acts on, filled in with the values they share (dialog `tateChuYokoSettings`: tcyUpDown, tcyLeftRight (pt, -1296..1296)): OK runs text.setFormat (text.setRangeStyle while the Type tool edits text) with the values that changed, as one undo step; an error with no type selected", + ), + ( + "ui.colorGuideLimit", + "Limit Color Guide to Library", + "", + "{library: swatch library id or name (see swatch.library.list) | \"document\" (the document's swatches) | \"\" or null (no limit)} limit the Color Guide panel's colours to that library: every harmony colour and variation snaps to its nearest colour, as color.harmony {limitTo} answers (ui.inspect: ui.color_guide_limit) → {limitTo, name}", + ), + ( + "ui.colorPanel", + "Color Panel Options", + "", + "{mode?: grayscale|rgb|hsb|cmyk|websafe, options?: bool} pick the Color panel's mode as its panel menu does (the active color converts to the mode's model as one undo step), and Show Options (true) or Hide Options (false); both are kept with the preferences; RGB, HSB, Web Safe RGB and hex values use the working RGB space (ui.inspect: ui.color_mode, ui.color_hide_options) → {mode (null: none picked yet), options, shown: the mode the panel shows the color in, or tint for a tint of a global or spot swatch}", + ), + ( + "ui.savePdfDialog", + "Save PDF Dialog", + "", + "{path?, preset?, range?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks)", + ), + ( + "file.exportAs", + "Export As…", + "", + "{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}", + ), + ( + "ui.fileInfoDialog", + "File Info Dialog", + "", + "{} open File Info (dialog `fileInfo`: the file.info fields, plus __keyword, keywords typed but not added yet); OK runs file.info. The File Info… menu item opens it too", + ), + ( + "ui.rasterEffectsSettingsDialog", + "Document Raster Effects Settings Dialog", + "", + "{} open Document Raster Effects Settings (dialog `rasterEffectsSettings`: the document.rasterEffectsSettings fields); OK runs it. The menu item opens it too", + ), + ( + "ui.effectGalleryDialog", + "Effect Gallery Dialog", + "", + "{} open Effect Gallery (dialog `effectGallery`: browse raster filters, build a stack, OK applies it as separate effects in one undo step). Effect → Effect Gallery… opens it too", + ), + ( + "ui.pdfPresetsDialog", + "PDF Presets…", + "", + "{selected?: preset name} open Edit → PDF Presets (dialog `pdfPresets`, field `selected`): the built-in presets (read-only) and the saved ones, with the selected one's description and settings. New… and Edit… open the preset editor (ui.pdfPresetDialog); Delete, Import… and Export… run pdf.preset.delete / import / export", + ), + ( + "ui.pdfPresetDialog", + "PDF Preset", + "", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default VectorCraft Default)} open the preset editor (dialog `pdfPreset`: the Save PDF dialog's option fields plus `name` and `description`); OK runs pdf.preset.save and returns to PDF Presets", + ), + ("file.openRecent11", "Open Recent File 11", "", "{}"), + ("file.openRecent12", "Open Recent File 12", "", "{}"), + ("file.openRecent13", "Open Recent File 13", "", "{}"), + ("file.openRecent14", "Open Recent File 14", "", "{}"), + ("file.openRecent15", "Open Recent File 15", "", "{}"), + ("file.openRecent16", "Open Recent File 16", "", "{}"), + ("file.openRecent17", "Open Recent File 17", "", "{}"), + ("file.openRecent18", "Open Recent File 18", "", "{}"), + ("file.openRecent19", "Open Recent File 19", "", "{}"), + ("file.openRecent20", "Open Recent File 20", "", "{}"), + ("file.openRecent21", "Open Recent File 21", "", "{}"), + ("file.openRecent22", "Open Recent File 22", "", "{}"), + ("file.openRecent23", "Open Recent File 23", "", "{}"), + ("file.openRecent24", "Open Recent File 24", "", "{}"), + ("file.openRecent25", "Open Recent File 25", "", "{}"), + ("file.openRecent26", "Open Recent File 26", "", "{}"), + ("file.openRecent27", "Open Recent File 27", "", "{}"), + ("file.openRecent28", "Open Recent File 28", "", "{}"), + ("file.openRecent29", "Open Recent File 29", "", "{}"), + ("file.openRecent30", "Open Recent File 30", "", "{}"), + ("file.reveal", "Show in Folder", "", "{} show the document's file in the system file manager (desktop) → {path}"), + ( + "file.cancelExport", + "Cancel Export", + "", + "{} stop every export running in the background (Background Export): an export stops between artboards and writes no file once cancelled → {cancelled: n}", + ), + ( + "file.exportInBackground", + "Continue in Background", + "", + "{} close the export progress dialog; the exports go on, shown in the status bar → {hidden: n}", + ), + ( + "file.cancelOpen", + "Cancel Opening", + "", + "{} stop opening every file being read in the background (its progress window's Cancel): the files don't open → {cancelled: n}", + ), + ( + "file.openInBackground", + "Continue in Background", + "", + "{} close the progress window of the files being opened; they go on being read, shown in the status bar → {hidden: n}", + ), + ( + "ui.dxfOptionsDialog", + "DXF Options Dialog", + "", + "{path?, useArtboards?, range?, …document.exportDxf options} open DXF Options (dialog `dxfOptions`: fields = these options over the ones used last, a dxfPreset's options under them; the dxfPreset field shows cnc while every field it sets matches, else custom); OK checks them, remembers them and writes path (else asks). Export As… → DXF opens it too", + ), + ( + "links.editOriginal", + "Edit Original", + "", + "{id?} open the file of linked image `id` (default: the selected linked image) in the system's default app for its type (Links panel, Edit › Edit Original; only a regular file with the extension of a format document.open reads, and not over the control channel or MCP); a placed document's file opens here in a new tab, and saving it updates the documents placing it → {path}; edits saved elsewhere show after links.update", + ), + ( + "links.reveal", + "Show in Folder", + "", + "{id?} show the file of linked image `id` (default: the selected linked image) in the system's file manager → {path}", + ), + ( + "ui.placementOptionsDialog", + "Placement Options…", + "", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions", + ), + ( + "ui.relinkDialog", + "Relink…", + "", + "{ids?: [image or placed document ids]} open Relink for `ids` (default: the selected ones; dialog `relink`: ids, links ([{name, ids}], one row per linked file), scope (Replace: each|selected (default)|all|missingInFolder, see links.relink), path (picked when empty), paths (with each: the files chosen so far, one per row of links)); OK runs links.relink with them, one undo step, except with each: OK takes path, or picks a file, for the next row of links, and the last row's OK relinks them all. An error when nothing is given or selected", + ), + ( + "ui.findLinksInFolder", + "Find Linked Files in Folder…", + "", + "{folder?, ids?: [image or placed document ids]} the Links panel's Find in Folder…: asks for a folder (or takes folder), then opens Find Linked Files (dialog `findLinks`) looking in it and its subfolders for the files of linked objects `ids` (default: the selected linked images and placed documents, else every missing file; links.findFiles). An error when there is nothing to look for. Disabled where there is no folder picker (the web)", + ), + ( + "ui.packageDialog", + "Package…", + "Cmd+Alt+Shift+P", + "{} open Package for the saved document (dialog `package`: folder, name, copyLinks, linksFolder, relink, copyFonts, report; a document never saved asks to Save As first); OK saves unsaved changes, runs file.package (the web downloads the zip) and offers file.showPackage", + ), + ( + "ui.action.rename", + "Rename Action", + "", + "{set: index, action: index, name} rename the Actions panel's action at action in set (0 is the top set) to name, with spaces trimmed from both ends; its steps, function key and color stay. An index past the last set or action, or an empty name, is an error and renames nothing → {name}", + ), + ( + "ui.action.stepsIncluded", + "Include Action Steps", + "", + "{set: index, action?: index, step?: index, included: bool, others?: bool} include or exclude the playback of every step in a set, every step in one action, or one step. With a step and others: true, leave that step unchanged and apply included to every other step in its action (Alt/Option-click). Invalid indexes change nothing → {set, action?, step?, included}", + ), + ( + "ui.action.new", + "New Action", + "", + "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), which the panel does not show. Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, or a key or color that is not one of these, it is an error and nothing is added → {set, action}", + ), + ( + "ui.action.options", + "Action Options", + "", + "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, or a key or color that is not one of these is an error and changes nothing → {name, key, color}", + ), + ( + "ui.action.play", + "Play Action", + "", + "{action: name, set?: name} play the Actions panel's action named action at the speed ui.action.playbackOptions sets; set names the set to look in (default: every set). Accelerated plays it as one undoable batch → what command.batch returns. Step by Step and Pause For play its first step now and the others one at a time, each its own undo step, until the last, ui.action.stop, or a step that comes due while a different document is active than after the step before → {results: [the first step's result], pending: the steps left}. An action with a stop, at any speed, plays up to the stop and waits until ui.action.continue or ui.action.stop; at Accelerated the steps between stops are one undoable batch each → {results, pending, atStop?: true when it already waits}. A name no action has, or one that more than one action in the sets looked in has, or an action played while another is still playing step by step or with pauses, is an error and nothing plays", + ), + ( + "ui.action.playbackOptions", + "Playback Options", + "", + "{speed?: accelerated|step|pause, seconds?: 1-60} set how the Actions panel plays actions: accelerated (the default) plays every step at once, step plays one step at a time and draws the window after each, and pause waits seconds (a whole number, 1 to 60, VectorCraft's own range) between steps. A param left out keeps its value; the setting is kept with the UI preferences. Any other speed or seconds is an error and changes nothing. The panel menu's Playback Options… (dialog `actionPlayback` with speed and seconds) runs this on OK → {speed, seconds}", + ), + ( + "ui.action.record", + "Begin Recording", + "", + "{set?: index} begin recording an automatically named Action N in the Actions panel's set at set (0 is the top set), by default the current set or the first set; with no sets, make Set 1. The set becomes current, and ui.action.stop adds the recorded action after that set's existing actions. An explicit invalid set or an existing recording is an error and changes nothing → {set, name}", + ), + ( + "ui.action.stop", + "Stop Playing/Recording", + "", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses, or one waiting at a stop, whose message box closes: the steps played stay and the rest do not run. With nothing recording or playing it changes nothing → {stopped}", + ), + ( + "ui.action.insertStop", + "Insert Stop", + "", + "{set?: index, action?: index, step?: index, message?, allowContinue?: bool} insert a stop, at which a playing action waits and shows message. With set and action (0 is the top set or action), the stop goes into that action, after step, else after its last step; without them it goes into the recording in progress, after the steps recorded so far. message defaults to none, and allowContinue, which offers Continue in the message box, defaults to false. A stop in an action becomes the panel's selected step, and its action and set become the selected ones. An index past the last set, action or step, a param of another type, params that are not an object, or no action and no recording is an error and changes nothing. The panel menu's Insert Stop… (dialog `actionStopRecord` with message, allowContinue, set, action and step) runs this on OK → {set, action, step}, or {recording: true}", + ), + ( + "ui.action.continue", + "Continue Action", + "", + "{} play on from the stop the Actions panel's playing action waits at, on the document active now, and close the stop's message box (dialog `actionStopMessage`): the next step runs at once, or at Accelerated the steps up to the next stop as one undo step. The panel's Play Current Selection runs this while an action waits. With no action waiting at a stop it is an error → {results, pending, atStop?}", + ), + ( + "ui.action.deleteStep", + "Delete Action Step", + "", + "{set: index, action: index, step: index} delete one step, a stop or a command, of the Actions panel's action at action in set (0 is the top set, action or step). The steps after it keep whether they are excluded, and no step of that action stays selected. A Record Stop dialog open on that step closes, and one open on a later step of the action follows it up. A missing or invalid index is an error and changes nothing. Undo does not bring the step back. The panel's Delete Selection runs this for the selected step → {set, action, step}", + ), + ( + "ui.batchDialog", + "Batch…", + "", + "{set?: index, action?: index} open Batch (dialog `actionBatch`) for the action at set/action (default: the first action of the first set); OK runs action.batch with the dialog's source, destination and overrides", + ), + ( + "ui.actionSet.save", + "Save Actions…", + "", + "{set?: index, id?, path?} write the Actions panel's set at set (0 is the top set; default: the current set) with its actions to an action set file (.vcactions) at path, else a picked file named after the set (the web downloads it). id holds the panel's own set id, which its menu passes: the set with this id is saved wherever it is now, and set is not read. A set over 8 MiB as a file, with more than 1,000 actions or with an action of more than 10,000 steps is not written; the panel menu's Save Actions… → {path}", + ), + ( + "ui.actionSet.load", + "Load Actions…", + "", + "{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused; the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"", + ), + ( + "ui.actionSet.delete", + "Delete Action Sets", + "", + "{sets?: [index], ids?: [id]} delete the Actions panel's sets at these indexes (0 is the top set), with their actions (default: the current set). ids holds the panel's own set ids, which its question passes: the sets with these ids are deleted wherever they are now, sets is not read, and when one of them no longer exists nothing is deleted. The panel's Delete Selection on selected sets (Shift-click adds a range) asks first, and OK runs this. A recording into a deleted set stops and keeps nothing. An index past the last set is an error → {deleted: n}", + ), + ( + "ui.actionSet.duplicate", + "Duplicate Action or Action Set", + "", + "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action is an error → {set, action?}", + ), + ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), + ( + "docInfo.save", + "Save Document Info…", + "", + "{path?, selectionOnly?, category?} write Document Info's text report (document.info {format: \"text\"}) to path, else a picked file (the web downloads it); with category (a document.info category id) only that category, else every category. The panel menu's Save… passes the category the panel shows and its Selection Only → {path}", + ), + ( + "ui.epsOptionsDialog", + "EPS Options Dialog", + "", + "{path?, useArtboards?, range?, …document.exportEps options} open EPS Options (dialog `epsOptions`: fields = these options over the ones used last); OK checks them, remembers them and writes path (else asks). Export As… → EPS opens it too", + ), + ( + "file.saveForWeb", + "Save for Web (Legacy)…", + "Cmd+Alt+Shift+S", + "{} open Save for Web (dialog `saveForWeb`: fields = the webExport.settings settings, `preset` loads a preset, __view: original|optimized|2up|4up, __zoom, __kbps; Save… remembers the settings and writes the files, Done only remembers them); with settings = document.exportForWeb, written to path, else a picked file (the web downloads the files) → {path, files, bytes}", + ), + ( + "file.saveForWeb.browser", + "Preview in Browser", + "", + "{…document.exportForWeb settings} write the HTML page and its images to a temporary folder and open the page in the default browser (desktop) → {path}", + ), + ( + "file.exportSelection", + "Export Selection…", + "", + "{multiple?: false} collect the selected objects as assets (assets.add: one of them all, as one image; true: one per object) and open Export for Screens on its Assets tab with them checked → {assets: [asset id…]}; document.exportSelection exports the selection in one go instead", + ), + ( + "css.copy", + "Copy Selected Style", + "", + "{scope?: selection|all (default selection), …css.selection options} copy the CSS of the selection (css.selection; all: css.generate) to the clipboard (CSS Properties panel) → {css, rules: n}", + ), + ( + "css.exportFile", + "Export CSS…", + "", + "{path?, scope?: selection|all (default selection), …css.selection options} css.export written to path, else a picked file (the web downloads it), with the pictures of rasterized art next to it (CSS Properties panel: Export Selected CSS…, Export All…) → {path, rules, images: [path…], warnings (css.export's; the status bar shows the first)}", + ), + ( + "file.print", + "Print…", + "Cmd+P", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + ), + ( + "print.printers", + "Printers", + "", + "{} → {printers: [{name, default}] (the system's printers), service (printing is available; else Print saves a PDF), setup (print.printerSetup can open the printer settings)}", + ), + ("print.printerSetup", "Printer Setup…", "", "{printer?} open the system's settings of the printer (the Print dialog's Setup…; desktop)"), + ( + "ui.printPresetsDialog", + "Print Presets…", + "", + "{selected?: preset name} open Edit → Print Presets (dialog `printPresets`, field `selected`): [Default] (protected) and the saved presets, with how the selected one differs from [Default]. New… and Edit… open the preset editor (ui.printPresetDialog); Delete, Import… and Export… run print.presets.delete / import / export", + ), + ( + "ui.printPresetDialog", + "Print Preset", + "", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", + ), + ( + "plugin.dialog", + "Plug-in…", + "", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step)", + ), + ( + "ui.installPlugin", + "Install Plug-in…", + "", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK when it asks about permissions or a heavy budget: ui.dialog.confirm, answer_dialog and synthetic input are refused → plugin.install's result | {pending: \"pluginInstall\"} while it asks about permissions or a heavy budget | {pending: \"confirm\"} while it asks only about replacing", + ), + ( + "plugin.cancelRuns", + "Cancel Plug-in Run", + "", + "{} stop every heavy filter running in the background (its progress window's Cancel): it stops at the next slice of its budget and changes nothing → {cancelled: n}", + ), + ( + "plugin.hideRuns", + "Continue in Background", + "", + "{} close the progress window of the heavy filters running in the background; they go on, shown in the status bar → {hidden: n}", + ), + ( + "imageTrace.cancelRuns", + "Cancel Image Trace", + "", + "{} stop every Image Trace running in the background (its progress window's Cancel): it stops at its next colour and changes nothing → {cancelled: n}", + ), + ( + "imageTrace.hideRuns", + "Continue in Background", + "", + "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", + ), + ( + "ui.runScript", + "Other Script…", + "Cmd+F12", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + ), + ( + "ui.runInstalledScript", + "Run Script", + "", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (the script is checked again, then script.run runs it by its path, so its #include lines and $.evalFile read beside it), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + ), + ( + "ui.checkScript", + "Check Script…", + "", + "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", + ), + ( + "ui.perspectiveGridDialog", + "Define Perspective Grid…", + "", + "{} open View › Perspective Grid › Define Grid (dialog `perspectiveGrid`, prefilled from the grid: the fields of perspective.grid.define); OK runs perspective.grid.define", + ), + ( + "ui.perspectivePresetsDialog", + "Perspective Grid Presets…", + "", + "{selected?} open Edit › Perspective Grid Presets (dialog `perspectiveGridPresets`, field `selected`): New… and Edit… open the preset editor (dialog `perspectiveGrid` with `__mode` edit), whose OK runs perspective.presets.save and comes back; Delete, Import… and Export… run perspective.presets.*", + ), + ( + "ui.savePerspectivePreset", + "Save Grid as Preset…", + "", + "{} open View › Perspective Grid › Save Grid as Preset (dialog `perspectiveGrid` with `__mode` save, `name` a new preset name): OK runs perspective.presets.save with the fields", + ), + ( + "ui.perspectiveUserPreset1.1", + "One Point Perspective Preset 1", + "", + "{} apply the 1. saved 1-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset1.2", + "One Point Perspective Preset 2", + "", + "{} apply the 2. saved 1-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset1.3", + "One Point Perspective Preset 3", + "", + "{} apply the 3. saved 1-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset1.4", + "One Point Perspective Preset 4", + "", + "{} apply the 4. saved 1-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset1.5", + "One Point Perspective Preset 5", + "", + "{} apply the 5. saved 1-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset2.1", + "Two Point Perspective Preset 1", + "", + "{} apply the 1. saved 2-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset2.2", + "Two Point Perspective Preset 2", + "", + "{} apply the 2. saved 2-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset2.3", + "Two Point Perspective Preset 3", + "", + "{} apply the 3. saved 2-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset2.4", + "Two Point Perspective Preset 4", + "", + "{} apply the 4. saved 2-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset2.5", + "Two Point Perspective Preset 5", + "", + "{} apply the 5. saved 2-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset3.1", + "Three Point Perspective Preset 1", + "", + "{} apply the 1. saved 3-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset3.2", + "Three Point Perspective Preset 2", + "", + "{} apply the 2. saved 3-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset3.3", + "Three Point Perspective Preset 3", + "", + "{} apply the 3. saved 3-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset3.4", + "Three Point Perspective Preset 4", + "", + "{} apply the 4. saved 3-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.perspectiveUserPreset3.5", + "Three Point Perspective Preset 5", + "", + "{} apply the 5. saved 3-point perspective grid preset (perspective.grid.preset)", + ), + ( + "ui.blendOptions", + "Blend Options…", + "", + "{} open Blend Options (Object › Blend › Blend Options…, the Blend tool's double-click, Alt-click and toolbar button; dialog `blendOptions`: spacing smooth|steps|distance, steps, distance (pt), orientation page|path, preview) on the selected blend's options, previewed live: OK runs object.blend.options as one undo step; with no blend selected it sets what new blends start with", + ), + ( + "ui.livePaintGapOptions", + "Gap Options…", + "", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", + ), + ( + "ui.perspectivePlane", + "Perspective Plane Options…", + "", + "{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move", + ), +]; diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 80f0deffda..ced1db16e2 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -84,11 +84,14 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { PathData::new(out) } -/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. +/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath +/// whose refit is one segment, or two lines that enclose no area, is refitted in two parts, cut at +/// the point farthest from its start, or in three when two still give that; one of a single segment +/// stays as it is. fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); - if n == 0 { + if n == 0 || sp.closed && n < 2 { return Some(sp.clone()); } if sp.closed { @@ -101,7 +104,34 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { // along its chord, and `no_worse` can return the original subpath, so the start can keep a kink. let across = if sp.closed && opts.smooth > 0.0 { unit(end_tangent(&segs[n - 1].c) + start_tangent(&segs[0].c)) } else { None }; let across = across.filter(|_| (0..n).all(|i| turn_deg(&segs[(i + n - 1) % n], &segs[i]) <= opts.corner_angle_deg)); - let result = simplify_run_within(&segs, opts, MAX_RUN_SAMPLES, across); + let mut result = simplify_run_within(&segs, opts, MAX_RUN_SAMPLES, across); + let flat = |r: &[Seg]| r.len() < 2 || r.len() == 2 && r.iter().all(|s| s.line); + if sp.closed && flat(&result) { + // Each segment in two, and the loop cut where they meet: first at the point farthest from its + // start, then also at the point farthest from the line between those two. + let halves: Vec = segs + .iter() + .flat_map(|s| { + let (a, b) = s.c.subdivide(); + [Seg { c: a, line: s.line }, Seg { c: b, line: s.line }] + }) + .collect(); + let m = halves.len(); + let at = |i: usize| halves[i].c.p0; + let farthest = |from: &dyn Fn(Point) -> f64, skip: usize| (1..m).filter(|&i| i != skip).max_by(|&a, &b| from(at(a)).total_cmp(&from(at(b)))); + let p0 = at(0); + let j = farthest(&|p| p.distance(p0), 0).unwrap_or(m / 2); + let chord = at(j) - p0; + let off_chord = |p: Point| if chord.hypot2() > 0.0 { chord.cross(p - p0).abs() } else { p.distance(p0) }; + let k = farthest(&off_chord, j).unwrap_or(m / 2); + let refit = |cuts: &[usize]| -> Vec { + cuts.windows(2).flat_map(|w| simplify_run_within(&halves[w[0]..w[1]], opts, MAX_RUN_SAMPLES / 3, None)).collect() + }; + result = refit(&[0, j, m]); + if flat(&result) && k != j { + result = refit(&[0, j.min(k), j.max(k), m]); + } + } let s = segs_to_subpath(&result, sp.closed)?; Some(if opts.straight_lines { s } else { no_worse(sp, s) }) } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 587da33448..01e89efe08 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -1,7 +1,7 @@ use std::f64::consts::PI; use kurbo::{ParamCurve, Point, Rect, Shape as _}; -use vectorcraft_geom::{AnchorKind, FillRule, PathData, SubPath}; +use vectorcraft_geom::{Anchor, AnchorKind, FillRule, PathData, SubPath}; use vectorcraft_pathops::*; const NZ: FillRule = FillRule::NonZero; @@ -408,6 +408,35 @@ fn simplify_straight_lines_option() { assert!(max_deviation(&c, &s) <= 1.0 + 1e-6); } +/// A closed subpath whose refit is one curve stays a closed subpath that encloses an area, in a +/// compound path and on its own, with curves and with Convert to Straight Lines. +#[test] +fn simplify_keeps_a_closed_subpath_that_refits_to_one_curve() { + let small = |cx: f64, cy: f64| circle(cx, cy, 2.0).subpaths.remove(0); + let square = rect(0.0, 0.0, 1000.0, 1000.0).subpaths.remove(0); + let compound = PathData::new(vec![square, small(500.0, 500.0)]); + let lone = PathData::single(small(0.0, 0.0)); + // A straight edge and a curve that bows 2.25 pt from it. + let bow = PathData::single(SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 3.0), Point::new(0.0, 0.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 3.0)), + ], + true, + )); + for straight_lines in [false, true] { + for tolerance in [4.0, 10.0, 32.0] { + let opts = SimplifyOptions { tolerance, straight_lines, ..Default::default() }; + for path in [&compound, &lone, &bow] { + let s = simplify_with(path, &opts); + assert_eq!(s.subpaths.len(), path.subpaths.len(), "{tolerance} pt, straight lines {straight_lines}: {s:?}"); + assert!(s.subpaths.iter().all(|sp| sp.closed && sp.anchors.len() >= 2 && sp.area().abs() > 1.0), "{s:?}"); + assert!(max_deviation(path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(path, &s)); + } + } + } +} + /// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every /// 10 up; Auto-Simplify takes the lowest level whose tolerance is at most 1/400 of the size, and /// level 100 for a size under 12.5 pt. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7fd0d8edf9..b02c3b6e1d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -249,8 +249,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // the layout. if let Some(fields) = ui.as_object_mut() { fields.remove("floating_panels"); + leave_out_unreadable_paths(fields); } - json!({ + let mut inspected = json!({ "scriptRunning": app.session.script_running(), "scriptReport": app.session.script_report(), "tool": app.session.tool_id(), @@ -294,8 +295,9 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "nativeMenuBar": app.services.native_menu.is_some(), // Saves and exports still being written in the background (Background Save / Export). "background": app.background.jobs.iter().filter(|j| !j.label.is_empty()).map(|j| j.label.as_str()).collect::>(), - // Documents still being read off the UI thread (File › Open, Open Recent): their paths. - "opening": app.opening.pending.iter().map(|p| p.path.as_str()).collect::>(), + // Documents still being read off the UI thread (File › Open, Open Recent): their paths, without + // the ones outside the read root. + "opening": app.opening.pending.iter().map(|p| p.path.as_str()).filter(|p| readable(p)).collect::>(), // Files still being read off the UI thread for Place (the Place dialog's OK, drops): their // names, in the order they are placed. "placing": app.placing.pending.iter().map(|p| p.name.as_str()).collect::>(), @@ -305,7 +307,173 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // A native file dialog open off the UI thread (`open`, `place`, `save`, `folder`), waiting // for the person at the computer: what asked for it runs again when it answers. "fileDialog": app.picks.waiting_kind(), - }) + }); + let ids = unreadable_library_ids(app); + hide_library_ids(&mut inspected, &ids); + inspected +} + +/// The fields of the UI state, by their keys in `ui.inspect`'s `ui`, that hold panel ids: the panel +/// popped out of the collapsed column, the docking layout, closed panels' places and groups, the panels +/// shown as icons or collapsed, and the older floating panels' record. +const PANEL_FIELDS: [&str; 7] = + ["open_panel", "docking", "docking_hidden", "docking_hidden_groups", "docking_icons", "docking_collapsed", "floating_panels"]; + +/// The ids of the loaded libraries (`loaded/`) that the UI state refers to and whose file the +/// request may not read, each with the id a reply shows instead: `loaded/`, as a library +/// loaded without a path is named. The UI state refers to a library by its bare id in a library panel +/// and the Color Guide's limit, and by a panel id (`library::loaded/`) in the fields of +/// [`PANEL_FIELDS`] and the workspaces' layouts. Text the person types (a command palette query, a +/// workspace's name) is not read. When another of those ids already shows that name, the next free one +/// of `loaded/ (2)`, `(3)` and so on is shown, in the sorted order of the full ids, so that +/// two libraries stay two and `ui.inspect` and `ui.docking` show a library under the same id. +fn unreadable_library_ids(app: &VectorcraftApp) -> Vec<(String, String)> { + let mut ids = std::collections::BTreeSet::new(); + let ui = serde_json::to_value(&app.ui).unwrap_or_default(); + for field in PANEL_FIELDS { + collect_library_panel_ids(&ui[field], &mut ids); + } + for workspace in ["custom_workspaces", "workspace_changes"].iter().filter_map(|k| ui[k].as_array()).flatten() { + for (_, layout) in workspace.as_object().into_iter().flatten().filter(|(k, _)| k.as_str() != "name") { + collect_library_panel_ids(layout, &mut ids); + } + } + collect_library_panel_ids(&json!(app.ui.transient_panel), &mut ids); + for id in app.ui.library_panels.iter().map(|p| p.id.as_str()).chain([app.ui.color_guide_limit.as_str()]) { + add_library_id(id, &mut ids); + } + let mut hidden = Vec::new(); + let mut taken = std::collections::BTreeSet::new(); + for id in ids { + let path = &id["loaded/".len()..]; + let name = vectorcraft_engine::cmd::fileio::file_name(path); + if name != path && !readable(path) { + hidden.push((id, name)); + } else { + taken.insert(id); + } + } + let mut hidden = hidden + .into_iter() + .map(|(id, name)| { + let mut shown = format!("loaded/{name}"); + let mut n = 2; + while taken.contains(&shown) { + shown = format!("loaded/{name} ({n})"); + n += 1; + } + taken.insert(shown.clone()); + (id, shown) + }) + .collect::>(); + // The longest first, so that an id that begins another one does not replace part of it. + hidden.sort_by_key(|(id, _)| std::cmp::Reverse(id.len())); + hidden +} + +/// Adds `id` to `ids` when it is a loaded library's id (`loaded/`). +fn add_library_id(id: &str, ids: &mut std::collections::BTreeSet) { + if id.len() > "loaded/".len() && id.starts_with("loaded/") { + ids.insert(id.to_string()); + } +} + +/// Adds to `ids` the loaded library id of every library panel id (`library::loaded/`) +/// that `v` holds as a string or a key. +fn collect_library_panel_ids(v: &Value, ids: &mut std::collections::BTreeSet) { + let add = |s: &str, ids: &mut std::collections::BTreeSet| { + if let Some((_, id)) = s.strip_prefix(crate::panels::library_panel::PREFIX).and_then(|rest| rest.split_once(':')) { + add_library_id(id, ids); + } + }; + match v { + Value::String(s) => add(s, ids), + Value::Array(items) => items.iter().for_each(|item| collect_library_panel_ids(item, ids)), + Value::Object(fields) => { + for (key, item) in fields { + add(key, ids); + collect_library_panel_ids(item, ids); + } + } + _ => {} + } +} + +/// Writes each id of `ids` as the id the reply shows instead, wherever `v` holds it: in a library's +/// id, in its panel's id (`library:swatches:loaded/`) and in keys. +fn hide_library_ids(v: &mut Value, ids: &[(String, String)]) { + if ids.is_empty() { + return; + } + let hide = |s: &mut String| { + for (id, shown) in ids { + if s.contains(id.as_str()) { + *s = s.replace(id.as_str(), shown); + } + } + }; + match v { + Value::String(s) => hide(s), + Value::Array(items) => items.iter_mut().for_each(|item| hide_library_ids(item, ids)), + Value::Object(fields) => { + for (mut key, mut item) in std::mem::take(fields) { + hide(&mut key); + hide_library_ids(&mut item, ids); + fields.insert(key, item); + } + } + _ => {} + } +} + +/// The preferences that hold a folder, by their keys in `ui.engine_prefs` and the Preferences dialog. +const PREF_FOLDERS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"]; + +/// The scratch disk choices that are not paths. +const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"]; + +/// May the request being served read `path`? Under an automation read root (a control client's +/// request), `ui.inspect` leaves out a path outside the root, as `ui.menu.list` leaves out a recent +/// file or a listed script outside it. +fn readable(path: &str) -> bool { + vectorcraft_engine::file_access::check_read(path).is_ok() +} + +/// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, +/// a library panel's file and folder preferences (saved, and in an open Preferences dialog) outside +/// the read root. The UI state itself is not changed. +fn leave_out_unreadable_paths(ui: &mut serde_json::Map) { + if let Some(Value::Array(files)) = ui.get_mut("recent_files") { + files.retain(|f| f.as_str().is_some_and(readable)); + } + if let Some(Value::Array(panels)) = ui.get_mut("library_panels") { + for panel in panels.iter_mut().filter_map(Value::as_object_mut) { + if panel.get("path").and_then(Value::as_str).is_some_and(|p| !readable(p)) { + panel.remove("path"); + } + } + } + if let Some(Value::Object(prefs)) = ui.get_mut("engine_prefs") { + leave_out_unreadable_folders(prefs); + } + if let Some(Value::Object(dialog)) = ui.get_mut("dialog") + && dialog.get("kind").and_then(Value::as_str) == Some("preferences") + && let Some(Value::Object(fields)) = dialog.get_mut("fields") + { + leave_out_unreadable_folders(fields); + } +} + +/// Takes out of `prefs` the folder preferences ([`PREF_FOLDERS`]) the request may not read. An +/// empty value (no folder) and a scratch disk choice ([`SCRATCH_CHOICES`]) stay. +fn leave_out_unreadable_folders(prefs: &mut serde_json::Map) { + for key in PREF_FOLDERS { + let Some(path) = prefs.get(key).and_then(Value::as_str).map(str::trim) else { continue }; + if path.is_empty() || (key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path)) || readable(path) { + continue; + } + prefs.remove(key); + } } fn key_from(name: &str) -> Option { @@ -348,7 +516,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques "engine.commands" => ok(all_commands(app)), "document.inspect" => wrap(app.run("document.inspect", p.clone())), "ui.inspect" => ok(inspect(app, ctx)), - "ui.docking" => ok(crate::panel_docking::inspect(app, ctx)), + "ui.docking" => { + let mut docking = crate::panel_docking::inspect(app, ctx); + let ids = unreadable_library_ids(app); + hide_library_ids(&mut docking, &ids); + ok(docking) + } "ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_entries(app)).unwrap_or_default()), "ui.contextMenu.list" => ok(serde_json::to_value(crate::menus::context_entries(app)).unwrap_or_default()), "ui.tool.select" => wrap(app.run("tool.select", json!({"tool": s("tool").unwrap_or("")}))), diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 50c57db650..f725a0819c 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -360,6 +360,181 @@ fn recent_files_outside_the_read_root_are_not_listed_or_opened() { let _ = std::fs::remove_dir_all(base); } +/// `ui.inspect` leaves out the paths outside the read root that the person's work put in it: files +/// still opening, recent files, a library panel's file and folder preferences, saved and in the +/// Preferences dialog. +#[test] +fn ui_inspect_leaves_out_paths_outside_the_read_root() { + let (mut app, tx, base) = confined("inspect"); + std::fs::copy(base.join("in/a.svg"), base.join("in/c.svg")).unwrap(); + let (a, b, c) = (s(base.join("in/a.svg")), s(base.join("outside/b.svg")), s(base.join("in/c.svg"))); + let svg = std::fs::read(&a).unwrap(); + for path in [&a, &b, &c] { + assert!(crate::opening::start(&mut app, path, svg.clone()).is_ok(), "{path} opens off the UI thread"); + } + app.ui.recent_files = vec![a.clone(), b.clone(), c.clone()]; + let panel = |id: &str, path: &str| -> crate::panels::library_panel::LibraryPanel { + serde_json::from_value(json!({"kind": "swatches", "id": id, "path": path})).unwrap() + }; + let theirs = format!("loaded/{b}"); + app.ui.library_panels = vec![panel("mine", &a), panel(&theirs, &b)]; + app.ui.open_panel = Some(format!("library:swatches:{theirs}")); + let (inside, outside) = (s(base.join("in")), s(base.join("outside"))); + app.ui.engine_prefs = json!({ + "fontsFolder": inside, "templatesFolder": outside, "recoveryFolder": outside, "scratchPrimary": "Startup", + "scratchSecondary": "../private", "pluginsFolder": "", + }); + app.ui.dialog = Some(crate::state::Dialog::new("preferences", json!({"fontsFolder": inside, "templatesFolder": outside}))); + + // The person sees every path. + let ctx = egui::Context::default(); + let person = crate::control::inspect(&app, &ctx); + assert_eq!(person["opening"], json!([a, b, c])); + assert_eq!(person["ui"]["recent_files"], json!([a, b, c])); + assert_eq!(person["ui"]["library_panels"][1]["path"], b); + assert_eq!(person["ui"]["engine_prefs"]["templatesFolder"], outside); + + // The client sees the ones inside the read root, in the same order. + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let ui = &r["result"]["ui"]; + assert_eq!(r["result"]["opening"], json!([a, c]), "{r}"); + assert_eq!(ui["recent_files"], json!([a, c])); + assert_eq!(ui["library_panels"][0]["path"], a); + assert_eq!((ui["library_panels"][1]["id"].as_str(), ui["library_panels"][1].get("path")), (Some("loaded/b.svg"), None), "the panel stays"); + assert_eq!(ui["open_panel"], "library:swatches:loaded/b.svg"); + let prefs = ui["engine_prefs"].as_object().unwrap(); + assert_eq!( + (prefs["fontsFolder"].as_str(), prefs["scratchPrimary"].as_str(), prefs["pluginsFolder"].as_str()), + (Some(inside.as_str()), Some("Startup"), Some("")) + ); + assert!(["templatesFolder", "recoveryFolder", "scratchSecondary"].iter().all(|k| !prefs.contains_key(*k)), "{prefs:?}"); + let fields = ui["dialog"]["fields"].as_object().unwrap(); + assert_eq!((fields["fontsFolder"].as_str(), fields.get("templatesFolder")), (Some(inside.as_str()), None), "the Preferences dialog's copy too"); + let hidden = json!(outside).to_string(); + assert!(!r.to_string().contains(hidden.trim_matches('"')), "no path outside the root: {r}"); + let r = request(&mut app, &tx, "ui.docking", json!({})); + assert_eq!(r["result"]["flyout"], "library:swatches:loaded/b.svg", "{r}"); + assert_eq!(crate::panel_docking::inspect(&app, &ctx)["flyout"], json!(format!("library:swatches:{theirs}")), "the person's"); + assert_eq!(app.ui.recent_files, [a.clone(), b.clone(), c.clone()], "the UI state is not changed"); + assert_eq!(app.opening.pending.len(), 3, "and no open is canceled"); + + // A write root alone lets the client read none of them. + let write_only = AutomationRoots::new(&[], &[&base.join("out")]).unwrap(); + let listed = vectorcraft_engine::file_access::confine(write_only.as_ref(), || crate::control::inspect(&app, &ctx)); + assert_eq!((&listed["opening"], &listed["ui"]["recent_files"]), (&json!([]), &json!([])), "{listed}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A closed panel's former place, as `ui.docking_hidden` keeps it. +fn hidden_place() -> craft_ui::docking::Location { + serde_json::from_value(json!({"floating": null, "anchor": null, "placement": {"Tab": {"before": null}}, "size": null, "stack": null})).unwrap() +} + +/// `ui.inspect` hides the path of a library loaded from outside the read root wherever the reply holds +/// its id, also when its panel is closed: here only the Color Guide's limit and a closed panel's place +/// name it. +#[test] +fn ui_inspect_hides_a_closed_librarys_path_outside_the_read_root() { + let (mut app, tx, base) = confined("inspect-closed-lib"); + let theirs = format!("loaded/{}", s(base.join("outside/b.svg"))); + app.ui.color_guide_limit = theirs.clone(); + app.ui.docking_hidden.insert(format!("library:swatches:{theirs}"), hidden_place()); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let ui = &r["result"]["ui"]; + assert_eq!(ui["color_guide_limit"], "loaded/b.svg", "{r}"); + assert!(ui["docking_hidden"].as_object().unwrap().contains_key("library:swatches:loaded/b.svg"), "{r}"); + let hidden = json!(s(base.join("outside"))).to_string(); + assert!(!r.to_string().contains(hidden.trim_matches('"')), "no path outside the root: {r}"); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_guide_limit"], json!(theirs), "the person's"); + let _ = std::fs::remove_dir_all(base); +} + +/// Two libraries loaded from outside the read root with the same file name stay two in `ui.inspect`: +/// the second one shows as `loaded/ (2)`, the same in every place the reply names it. +#[test] +fn ui_inspect_keeps_two_hidden_libraries_with_one_file_name_apart() { + let (mut app, tx, base) = confined("inspect-same-name"); + let (x, y) = (format!("loaded/{}", s(base.join("outside/x/b.svg"))), format!("loaded/{}", s(base.join("outside/y/b.svg")))); + let panel = |id: &str| -> crate::panels::library_panel::LibraryPanel { serde_json::from_value(json!({"kind": "swatches", "id": id})).unwrap() }; + app.ui.library_panels = vec![panel(&x), panel(&y)]; + for id in [&x, &y] { + app.ui.docking_hidden.insert(format!("library:swatches:{id}"), hidden_place()); + } + app.ui.color_guide_limit = y.clone(); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let ui = &r["result"]["ui"]; + let ids: Vec<_> = ui["library_panels"].as_array().unwrap().iter().map(|p| p["id"].clone()).collect(); + assert_eq!(ids, [json!("loaded/b.svg"), json!("loaded/b.svg (2)")], "{r}"); + let keys: Vec<_> = ui["docking_hidden"].as_object().unwrap().keys().cloned().collect(); + assert_eq!(keys, ["library:swatches:loaded/b.svg", "library:swatches:loaded/b.svg (2)"], "no entry is dropped: {r}"); + assert_eq!(ui["color_guide_limit"], "loaded/b.svg (2)", "the same id everywhere"); + let _ = std::fs::remove_dir_all(base); +} + +/// `ui.inspect` and `ui.docking` show a hidden library under the same id, also when another hidden +/// library with the same file name is in only one of the replies (here as the Color Guide's limit). +#[test] +fn ui_inspect_and_ui_docking_give_a_hidden_library_the_same_id() { + let (mut app, tx, base) = confined("inspect-docking-same-id"); + let (x, y) = (format!("loaded/{}", s(base.join("outside/x/b.svg"))), format!("loaded/{}", s(base.join("outside/y/b.svg")))); + let panel: crate::panels::library_panel::LibraryPanel = serde_json::from_value(json!({"kind": "swatches", "id": y})).unwrap(); + app.ui.library_panels = vec![panel]; + app.ui.open_panel = Some(format!("library:swatches:{y}")); + app.ui.color_guide_limit = x.clone(); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let ui = &r["result"]["ui"]; + assert_eq!( + (ui["color_guide_limit"].as_str(), ui["open_panel"].as_str()), + (Some("loaded/b.svg"), Some("library:swatches:loaded/b.svg (2)")), + "{r}" + ); + let d = request(&mut app, &tx, "ui.docking", json!({})); + assert_eq!(d["result"]["flyout"], ui["open_panel"], "{d}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `ui.inspect` rewrites only the ids of libraries the UI state refers to: a script's report line and +/// a command palette query that look like a library id, with no such library, stay as written, and +/// the query does not take the file name of a real library outside the root. +#[test] +fn ui_inspect_keeps_text_that_only_looks_like_a_library_id() { + let (mut app, tx, base) = confined("inspect-lookalike"); + let real = format!("loaded/{}", s(base.join("outside/x/d.svg"))); + let panel: crate::panels::library_panel::LibraryPanel = serde_json::from_value(json!({"kind": "swatches", "id": real})).unwrap(); + app.ui.library_panels = vec![panel]; + let query = format!("library:swatches:loaded/{}", s(base.join("outside/d.svg"))); + app.ui.palette_query = query.clone(); + let text = format!("loaded/{}", s(base.join("outside/c.svg"))); + let source = format!("vc.log({})", json!(text)); + app.session.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + for _ in 0..10_000 { + if app.session.script_pump().is_some() { + break; + } + } + let r = request(&mut app, &tx, "ui.inspect", json!({})); + assert_eq!(r["result"]["scriptReport"]["log"], json!([text]), "{r}"); + assert_eq!(r["result"]["ui"]["palette_query"], json!(query), "{r}"); + assert_eq!(r["result"]["ui"]["library_panels"][0]["id"], "loaded/d.svg", "{r}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A client without automation roots sees every loaded library's full id in `ui.inspect`. +#[test] +fn ui_inspect_shows_full_library_ids_without_a_read_root() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + let theirs = format!("loaded/{}", s(std::env::temp_dir().join("vc-ui-roots-unconfined").join("b.svg"))); + let panel: crate::panels::library_panel::LibraryPanel = serde_json::from_value(json!({"kind": "swatches", "id": theirs})).unwrap(); + app.ui.library_panels = vec![panel]; + app.ui.color_guide_limit = theirs.clone(); + app.ui.docking_hidden.insert(format!("library:swatches:{theirs}"), hidden_place()); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let ui = &r["result"]["ui"]; + assert_eq!((&ui["library_panels"][0]["id"], &ui["color_guide_limit"]), (&json!(theirs), &json!(theirs)), "{r}"); + assert!(ui["docking_hidden"].as_object().unwrap().contains_key(&format!("library:swatches:{theirs}")), "{r}"); +} + /// Hidden logic-only ticks between the injection and its UI pass must not drain another step: /// one step per settled pass, not per hidden tick. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 96e5baffb3..04715474d0 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -92,7 +92,7 @@ the two can still win that race. | `engine.execute` | `{command, params}` | run any engine or UI command (see `engine.commands`). A key of `params` that the command's params description doesn't name is an error naming it and the nearest key the command takes, before anything runs (`unknown parameter `widht`; did you mean `width`?`); see [Parameter keys](mcp.md#parameter-keys) | | `engine.commands` | | every command with label, shortcut, params doc, enablement | | `document.inspect` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | layer tree, selection, the key object (`key`, null without one; a key ruler guide as `keyGuide`), history, paint defaults; `depth` / `childLimit` slice the layer tree as `document.node {summary: true}` does; `ids`, `kind`, `limit` and `offset` list just some nodes as `nodes` (with `total`) instead of the whole tree, see [mcp.md](mcp.md). Each node reports `opacity` below 1 and `blend` when it isn't Normal; objects and compound paths report `fill`, `stroke` and `strokeWidth`, a compound path's members `compoundMember: true` instead | -| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below) | +| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below), `opening` (the paths of the documents still being read). Under `--automation-read-root` the reply leaves out the paths outside the read roots (see `docs/mcp.md`) | | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5cad08fbf7..df33fa8b63 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` and EPS import: while an envelope's contents are edited, the editing data keeps its mesh (a mesh's, a top object's or a warp's grid) in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art, as if the mesh hadn't followed the envelope when it moved: the envelope drew its contents elsewhere and kept its drawn art. A mesh or top object saved in Edit Contents (or a warp of type tried on its saved grid) whose mesh draws the contents as large as the drawn art, within half a point over width and height together, but further from it than that, is now tried again, after every other way and with one more of the import's checks, with its mesh moved by as far as the drawn art's box lies from the box of what it draws; it opens live there where it then draws as the drawn art. In users' files, used locally and never committed, only envelopes saved in Edit Contents draw elsewhere than their drawn art, and nothing in their dictionaries says by how much they moved. Tests `ai::tests::an_envelope_in_edit_contents_whose_mesh_stayed_behind_opens_live_on_its_drawn_art`, `tests_native::a_warp_of_type_in_edit_contents_whose_grid_stayed_behind_opens_on_its_drawn_art` (#6570) | | 2026-11-11 | minor | `.ai` save (PDF-compatible editing copy and legacy) and `.ai`/EPS open: a layer's `Lb` colour index follows the file's numbering, where Magenta, Cyan and Yellow are 4, 5 and 6 and `LAYER_COLORS` has Yellow, Magenta and Cyan; Yellow, Magenta and Cyan layers no longer come out as Magenta, Cyan and Yellow, and the other 24 presets are unchanged (#6502, from the index and RGB pairs in users' files). `LAYER_COLORS` keeps its order, so `.vectorcraft` files and the Layers panel don't change. Scores and estimates unchanged. | | 2026-11-11 | minor | `.ai` save: stroked type writes its stroke's cap, join and miter limit into the text document (keys 61, 62 and 64, as `.ai` import reads them since #6500), so they come back when the file opens again and no longer count among the attributes of type left out; a run without a stroke doesn't count them either, as they draw nothing. Tests `ai_editing::tests::type_comes_back_as_type`, `an_unstroked_run_with_a_stroke_style_loses_nothing` (follow-up to #6472) | | 2026-11-11 | minor | `.ai` and EPS import, PDF import, SVG export and `.ai` save: type with a Horizontal Scale other than 100% and tracking or manual kerning is spaced as a `.ai`'s own page spaces it. Layout now measures tracking and manual kerning in thousandths of the em as the scale draws it (see type-parity.md, same date); they were added at the full em, so such type drifted from the page letter by letter. A `.ai`'s page writes that type's character spacing as the tracking itself in a text space as wide as the scale, which PDF scales by it (ISO 32000-1 §9.4.4). In 224 users' files (used locally, never committed), 93 render differently. Of the 25 whose render moved by more than 1% of its pixels against the page, 23 came closer. The note on the type differing from the page shows a smaller share in 5 files (11.0% to 4.4% at most) and a larger one in 2 (by 0.2 to 0.3 points). 9 more envelopes of type open live (113 to 122 of 203, none fewer in any file), and no file switched between its layers and its PDF part. PDF import: the tracking of horizontally scaled type is the file's `Tc` in thousandths of its size (it was that times the scale), the glyphs where they were (test `tests::text_placement::character_spacing_in_horizontally_scaled_type_is_the_files_tc`). SVG export writes the letter spacing in thousandths of the font size it writes (the vertical scale), so type scaled uniformly keeps its spacing in a viewer (test `text_layout::spacing_in_uniformly_scaled_type_takes_the_scale`); tracked type scaled horizontally alone still differs a little there, as before. A `.ai` saved here writes the same values as before; VectorCraft now lays them out as the file's own PDF part draws them. Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 45f7fbb6a8..f9661b1ea5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > -> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); scores and estimates unchanged. +> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); stroke-closure follow-up remains open; scores and estimates unchanged. ## Feature submission evidence @@ -307,7 +307,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools -- **Improved (#6582):** the Eraser subtracts its swept area from filled open contours, preserving fill outside the stroke. Open compound members keep their holes under either fill rule; zero-area open lines keep outline splitting. Original engine integration regressions check rendered pixels, retained geometry, mixed paths and history. Scores and estimates unchanged. +- **Improved (#6582):** the Eraser subtracts its swept area from filled open contours, preserving fill outside the stroke. Open compound members keep their holes under either fill rule; zero-area open lines keep outline splitting. Original engine integration regressions check rendered pixels, retained geometry, mixed paths and history. Review follow-up: filled open paths with a visible stroke can gain a stroke on their implicit closing edge; separate fill/stroke geometry and clipping-source handling remain unresolved. A single twice-traced contour with canceled Even-Odd fill can also reveal fill after outline splitting. Scores and estimates unchanged. - **Export-only improvement (#6309):** PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. Broader G11 scope, scores and estimates unchanged. @@ -699,6 +699,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. - **Exposed in MCP:** `add_text {vertical: true}` uses the existing vertical point, area and path type commands. Horizontal writing remains the default; the broader automation gap and estimate are unchanged. +- **Done (#6460):** headless and remote `command_list` list desktop `UI_COMMANDS` (`ui: true`); UI-only runs still need `--connect`; effect ids are not command ids; 33 tools; eight prompts (spelling, variables, path-tools added); `vectorcraft://commands/reference` in the rebuilt CLI; prefer a checkout-built CLI when a release binary lags. Estimate unchanged. ## G15 Performance budgets and a GPU renderer @@ -857,6 +858,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| | 2026-11-11 | minor | Eraser: filled open contours and compound holes use area cutting; zero-area open lines retain outline splitting (#6582). Scores and estimates unchanged. | +| 2026-11-10 | minor | G6: MCP catalogue (#6460): headless lists `UI_COMMANDS` (`ui: true`), eight prompts, effect vs command ids, 33 tools, commands/reference; estimate unchanged. | | 2026-11-11 | minor | G5: built-in Status Effects graphic style library (Poison Tint, Freeze Edge, Burn Aura, Stun Pulse, Stealth Fade, Shield Buff); Missing trimmed; estimate 7–17 → 6–16 h; MCP docs list UI Frames and Map Markers under Symbol libraries. | | 2026-11-11 | minor | G5: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem; no default 9-slice); Missing trimmed; estimate 8–18 → 7–17 h. | | 2026-11-10 | minor | G4 type: Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, #4936; the Check Spelling dialog remains; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 7d66c7c0b3..c766d812a1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14,6 +14,18 @@ It has two backends: With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries only protocol messages. +### Command catalogue (headless vs remote) + +`command_list` / `list_commands` / `vectorcraft://commands` return the live catalogue for the backend in use: + +- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that points at `--connect`. + The catalogue is mirrored in `crates/mcp/src/ui_catalog.rs` (mcp does not depend on ui-egui). Regenerate with `cargo xtask ui-commands`; `cargo xtask ci` runs `ui-commands --check` so the mirror cannot drift. +- **Remote:** the same lists, with each UI entry's `enabled` taken from the live app. Run UI commands with `command_run` / `run_command` or `invoke_menu`. + +Effect ids from `effect.list` / `apply_effect` / `vectorcraft://effect/{id}` (for example `warp.arc`, `blur.gaussian`, `threeD.revolve`, `adjust.hueSaturation`, `addon.path.dashes`, `addon.color.halftone`) are not command ids. Apply one with `effect.apply` or the `apply_effect` tool; do not pass an effect id to `command_run`. Path Effects keep the `addon.path.*` effect ids; the Path Tools add-on's *commands* are `addon.pathtools.*`. + +A release `vectorcraft-cli` on `PATH` can lag the checkout. Prefer `cargo install --path apps/vectorcraft-cli --locked` and put `$CARGO_HOME/bin` first in the MCP client's environment, or set the client's `command` to that binary's absolute path (#6460). + ## Install and register From the repository root, with Rust 1.95+ and the platform's source-build prerequisites installed: @@ -115,6 +127,16 @@ the suite) keep the agent to the folders you give it: - `file.recentFiles` and the control channel's `ui.menu.list` leave out the recent files outside the read roots. The other File › Open Recent Files rows keep their ids (`file.openRecent3` still opens the third file), and `file.openRecentN` for a file outside the roots ends with `no such recent file`, as an empty slot does. +- `ui_inspect` (the control channel's `ui.inspect`) leaves out the paths outside the read roots: in `opening`, the + documents still being read; in `ui.recent_files`, the recent files; a library panel's `path` in `ui.library_panels`; + and the folder preferences in `ui.engine_prefs` and in an open Preferences dialog's `ui.dialog.fields` + (`fontsFolder`, `pluginsFolder`, `scratchPrimary`, `scratchSecondary`, `recoveryFolder`, `templatesFolder`; an + empty folder and the scratch disk choices `Startup` and `None` stay). A library loaded from a file outside the + roots shows as `loaded/` wherever `ui_inspect` and `ui.docking` name it: its id, its panel's id, the + Color Guide's `ui.color_guide_limit` and a closed panel's key in `ui.docking_hidden`, also when its panel is + closed. When another hidden library has the same file name, the libraries take `loaded/`, + `loaded/ (2)`, `(3)` and so on in the order of their full ids, and each one keeps its id in both + replies. The other entries keep their order, and the app's own state is not changed. - Each flag may be given more than once (#3546): a path inside any of the read roots may be read, one inside any of the write roots written, so one session can read a project folder and a shared assets folder, or write to an output folder and a scratch folder, without widening a root to their common parent. A folder given twice @@ -195,7 +217,7 @@ dropped; the call reports uncertainty like any reply that never arrived whole. ### Prompts -`prompts/list` offers five workflows; `prompts/get` returns one templated user message with its +`prompts/list` offers eight workflows; `prompts/get` returns one templated user message with its arguments filled in. A missing required argument is `-32602`. | Prompt | Arguments (required first) | @@ -205,6 +227,9 @@ arguments filled in. A missing required argument is `-32602`. | `recolor` | `palette`, `method` | | `trace-and-style` | `path`, `preset`, `effect` | | `export-set` | `formats`, `directory`, `scale` | +| `check-spelling` | `scope`, `action` | +| `variables-bind` | `kind`, `source` | +| `path-tools` | `task` | ```sh echo '{"jsonrpc":"2.0","id":1,"method":"prompts/get","params":{"name":"poster","arguments":{"brief":"a jazz festival"}}}' \ @@ -374,11 +399,9 @@ The older names below remain listed because existing workflows use them. | Tool | Arguments and result | |---|---| -| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text, `schema` or `inputSchema`); returns the command array. A command with a parameter schema lists `schema` and `inputSchema` (see [Parameter schemas](#parameter-schemas)). `list_commands` lists the same commands; it takes `enabledOnly` and returns `{count, commands}` | +| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text, `schema` or `inputSchema`); returns the command array for the backend in use (see [Command catalogue](#command-catalogue-headless-vs-remote)). A command with a parameter schema lists `schema` and `inputSchema` (see [Parameter schemas](#parameter-schemas)). `list_commands` lists the same commands; it takes `enabledOnly` and returns `{count, commands}` | | `command_run` | `id`, optional `params`; runs the command through the existing backend. An unknown key in `params` is an error that names it and the nearest key the command takes (`invalid parameters for `file.new`: unknown parameter `widht`; did you mean `width`?`), so a misspelt key no longer runs the command with its default (see [Parameter keys](#parameter-keys)). `run_command` runs a command the same way and takes its id as `command` | | `command_batch` | `steps: [{id, params?}]` (at most 256), optional `stop_on_error` (default true), `atomic` and `label`; returns `completed`, `failed`, `results: [{ok, result\|error}]` and `created` (the ids the `draw_path` / `draw_shape` steps made, in order). A step's `id` is a command id, or `draw_path` / `draw_shape` with that tool's arguments as `params` (checked as `tools/call` checks them; the step's result is the tool's, so `"$N.id"` is the new object). Each edit has its own undo step, or with `atomic: true` the batch's edits are one undo step named `label` (else after its first edit; `edit.undoGroup.begin`/`end` underneath), and the edits made in a document that a step opens or creates (`document.open`, `file.new`) are one undo step there, named the same, also when no document was open before the batch. In a document that was open before the batch and that a step switches to (`document.activate`), each edit stays its own undo step; failures set `isError`. A param string `"$N.path"` or `"$last.path"` takes a value from an earlier step's result (see `run` below). Kept step results total at most 8 MiB; past that the batch stops with the reason. This is the MCP tool, not the engine command `command.batch` (that one takes `commands: [{command, params}]` and is what the Actions panel plays); use `command_run` with `command.batch` when replaying a recorded action | -| `command_list` | Optional `filter` (or `query`), `menu` (a menu path substring, levels joined with ` > `), `enabled_only`, `brief` (no `params` text, `schema` or `inputSchema`); returns the command array | -| `command_run` | `id`, optional `params`; runs the command through the existing backend. An unknown key in `params` is an error that names it and the nearest key the command takes (`invalid parameters for `file.new`: unknown parameter `widht`; did you mean `width`?`), so a misspelt key no longer runs the command with its default (see [Parameter keys](#parameter-keys)) | | `doc_inspect` | Optional `depth`, `childLimit`, `ids`, `kind`, `limit`, `offset`; same summary as `inspect_document` | | `render_preview` | Optional `max_side` (1–4096, default 1024), `artboard` (0-based, default 0) and `traceViews`; inline PNG of that artboard without editing it, drawn as `export` draws a PNG with `background: "white"` at the scale that fits `max_side` (at most 1). With `traceViews: true`, Image Trace objects draw in the view set with `imageTrace.setView` (outlines, the source image…), as in the app's window; by default they draw their tracing result. Artboards too large to render within the allocation bound return a tool error | | `ui_inspect`, `ui_screenshot` | Connected desktop state/window capture; tool errors in headless mode. `ui_inspect` is the same call as `inspect_ui`, and `ui_screenshot` is `screenshot` with `window: true`. `ui_screenshot` takes an optional `max_side` (1–4096), as `screenshot {window: true}` does: a capture whose longer side is larger is scaled down to `max_side` pixels on that side, and the reply's text gives the returned size as `width`/`height` and the capture's as `capturedWidth`/`capturedHeight`. Without `max_side` the full capture comes back | @@ -464,7 +487,7 @@ opens the picker through `run_command` with the remote backend. | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | -| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. Includes UI commands such as `view.*` and `window.*` in remote mode. | +| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a Photoshop file as its merged image; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | @@ -1419,8 +1442,9 @@ vectorcraft-cli run --cmd file.new --params '{"width":600,"height":200}' --cmd ### Parameter schemas -Some commands have a machine-readable parameter schema: at present `view.capsLock`, `view.saved.new`, -`view.saved.edit`, `view.saved.list`, `view.transparencyGrid`, `view.snapToGlyph.options` and `engine.apiReference`. The engine's +Some commands have a machine-readable parameter schema: at present a small set including `view.capsLock`, `view.saved.new`, +`view.saved.edit`, `view.saved.list`, `view.transparencyGrid`, `view.snapToGlyph.options` and `engine.apiReference` +(most of the catalogue still documents params in prose only; schemas grow command by command). The engine's `engine.commands` list gives such a command a `schema` field: an object schema in the shape of JSON Schema 2020-12 (https://json-schema.org/draft/2020-12). Its root has `$schema` (the 2020-12 dialect), `description` when the command has a summary, and `deprecated: true` when the command is deprecated. The schema uses `type`, `properties`, `required` and @@ -4570,7 +4594,7 @@ draws, and View › Snap to Grid snaps to its subdivisions. Changing either sets every document they read except a native file and the native document that an SVG, PDF, `.ai` or EPS file carries (`restored: true`), which keep the grid they were saved with. -`view.rotate {angle}` (desktop app) turns the view to `angle` degrees about the center of the canvas; a positive angle +`view.rotate {angle}` (desktop app, `ui: true`) turns the view to `angle` degrees about the center of the canvas; a positive angle turns the art clockwise on screen. View › Rotate View and the status bar's angle menu run it. It returns `{angle}`, the angle it set, normalized to (-180, 180], and `view.rotateReset` turns the view back to 0, returning `null` on success. @@ -4578,7 +4602,9 @@ Select the Rotate View Tool with `select_tool` and the tool id `rotateView`. Its drags turn the canvas about its center; Shift snaps to 15°. Document coordinates for a rotation gesture use the view at the initial down event, including when the gesture spans several calls. The control channel rejects malformed rotation packets without changing the angle and cancels -the current press. Start a new down event after an error. +the current press. Start a new down event after an error. Menu commands that only the desktop view +implements (`view.rotate`, `view.rotateReset`, `view.rotateToSelection`) are listed with `ui: true` +and need `--connect` when the headless host does not run them. Reset Rotate View is the command `view.rotateReset`: ```json @@ -4908,7 +4934,10 @@ settings and the next untitled name, without opening the dialog, and returns wha open document in tab order the current one, as a click on its tab does, and return `{index}`. After the last document comes the first, and before the first document comes the last. From the Home screen they go to the first and the last document. With no document open they fail with "no document open". `document.activate {index}` makes a given document -the current one. +the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip +does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the +current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and +remote `command_list` both list it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. @@ -8460,10 +8489,11 @@ plain path from then on. ### Path Effects (live) Effect › Path Effects holds the add-on's live geometry effects, applied with `effect.apply {effect, params}` like any -other effect, with no shortcuts. Each draws, measures, exports and stacks as the other geometry effects do; the object's -own path stays as it is until Expand Appearance (`effect.expandAppearance`) writes the result. `effect.list` documents -every parameter. Out-of-range values are clamped, and an effect whose result would pass the geometry effects' budget -(2 million anchors) leaves the path as it is. +other effect, with no shortcuts. The ids below (`addon.path.*`) are **effect** ids, not command ids; the Path Tools +add-on's commands are `addon.pathtools.*` (see above). Each effect draws, measures, exports and stacks as the other +geometry effects do; the object's own path stays as it is until Expand Appearance (`effect.expandAppearance`) writes +the result. `effect.list` documents every parameter. Out-of-range values are clamped, and an effect whose result would +pass the geometry effects' budget (2 million anchors) leaves the path as it is. | Id | Menu item | Parameters | | --- | --- | --- | diff --git a/docs/roadmap.md b/docs/roadmap.md index 73b42db7a1..b740a12f72 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > -> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); scores and estimates unchanged. +> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); stroke-closure follow-up remains open; scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -54,6 +54,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | 2026-11-07 | minor | M4/M7: `.ai`/EPS type from the text document keeps auto leading at the paragraph's share, the paragraph's hyphenation options and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them, and a line a soft return ends is justified as a wrapped line is (#6137); a user's `.ai` that opened from its PDF part now opens from its layers. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently. Scores and estimates unchanged. | | 2026-11-08 | minor | Character Styles panel: a double-click on a user style's row opens its Character Style Options (`ui.charStyleOptions`); the dialog keeps a fixed width and scrolls its sections in a shorter window, so OK and Cancel stay on screen. Tests `panels::text_styles::tests::double_clicking_a_character_style_row_opens_its_options` and `dialogs::char_style_options::tests::the_sections_scroll_in_a_window_shorter_than_the_general_list`. Scores and estimates unchanged. | | 2026-11-08 | minor | #3380, deletion only: preserve gradient placement and exact surviving geometry; consume owned subpaths with a shared original-node snapshot; consolidate status/evidence and document command/helper contracts. Compound behavior and the existing M2 status entry are retained. Endpoint highlighting remains open; scores and estimates unchanged. | +| 2026-11-10 | minor | M13 / G6: MCP catalogue (#6460): headless lists UI commands, eight prompts, 33 tools, effect vs command ids; scores and estimates unchanged. | | 2026-11-07 | minor | #3380 (deletion only): independent surviving path objects; transformed appearance, stacking, selection, cubic handles and Undo/Redo covered by `delete_path_pieces`; compound semantics retained. Endpoint highlighting remains open; scores and estimates unchanged. | | 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. | | 2026-11-07 | minor | Indian-language hyphenation (#4947): eleven MIT-licensed pattern sets, with grapheme and shaping-cluster protection in both composers and existing paragraph limits. Assamese and Sanskrit are selectable; Sanskrit automatic patterns remain pending an allowlisted source. Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a7baadced..0a78ea3b6d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,8 +1,8 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > -> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); scores and estimates unchanged. +> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); stroke-closure follow-up remains open; scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -741,9 +741,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens, links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. + - `ui.inspect` under `--automation-read-root`: the documents still opening, the recent files, library panels' files and folder preferences (saved, and in an open Preferences dialog) outside the read roots are left out of the reply, a library loaded from outside them shows by its file name in `ui.inspect` and `ui.docking`, and the app's state is not changed. `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_leaves_out_paths_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - - MCP server with 25 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, any command), attached to the running app or headless. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). + - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172). - MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads). - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. @@ -752,6 +753,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings (`xpath` is not provided). `` in an XML string gives a `SyntaxError`. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. - **UI:** Illustrator 2026 layout restyled to measured values: - Medium Dark theme, categorized and Advanced toolbars (a tool group's flyout opens on a right press, a long press or a press on its corner triangle), 35 pt document tabs, 33 pt panel tabs. - Hint bar, contextual task bar, 19 dock panels with ≡ menus. @@ -942,7 +944,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur While a spiral is dragged out, Alt adds or removes whole winds of four segments and Ctrl/Cmd changes the decay. The spiral's inner end keeps the distance from the center it had on the first modified drag event, while the outer end follows the pointer. The [default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copy) list Alt-drag to add or subtract winds and Ctrl-drag to change the decay rate; [Draw spirals](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-spirals.html) defines four segments per full wind and Decay as the amount each wind decreases. An 80% spiral has 80% of its outer radius after four segments; newly drawn spirals with the same settings wind more broadly than in earlier VectorCraft builds. Rounding the fitted count to whole winds from the count on the first Alt-only drag event, the held inner radius, the ranges (2…1000 segments, 5…99.99 % decay), Ctrl/Cmd taking precedence when both are held, and the new values staying as Spiral tool options are our own rules. Switching back to Alt uses the current count as its new base while keeping the held inner end. Escape while an arc, spiral or grid is dragged out cancels it and puts back the options its keys, Alt and Ctrl/Cmd changed (slope, open or closed, base axis, segments, decay, dividers and skews), so the next drag and the tool's options start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). - The Eraser cuts filled open contours as areas (#6582), retaining fill outside its sweep; cut filled pieces are closed as for closed input. Open compound members are cut together under their compound fill rule so holes stay empty. Zero-area open lines retain outline splitting, including lines alongside filled contours in one path. `crates/engine/tests/eraser_open_fill.rs` checks original open/closed shapes, retained/erased pixels, self-crossing fill, compound holes, mixed strokes and Undo/Redo; scores and hours are unchanged. + The Eraser cuts filled open contours as areas (#6582), retaining fill outside its sweep; cut filled pieces are closed as for closed input. Open compound members are cut together under their compound fill rule so holes stay empty. Zero-area open lines retain outline splitting, including lines alongside filled contours in one path. `crates/engine/tests/eraser_open_fill.rs` checks original open/closed shapes, retained/erased pixels, self-crossing fill, compound holes, mixed strokes and Undo/Redo. A confirmed review regression remains: closing filled open pieces can add a stroke on the original implicit closing edge; the stroke/clipping follow-up and single-contour canceled-fill limitation remain open. Scores and hours are unchanged. A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. @@ -1434,7 +1436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). @@ -1977,6 +1979,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| | 2026-11-11 | minor | Eraser: filled open contours and compound holes use area cutting; zero-area open lines retain outline splitting (#6582). Scores and estimates unchanged. | +| 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | | 2026-11-11 | minor | Bundled content: built-in Status Effects graphic style library; style libraries evidence updated; ~40% → ~42%; MCP Symbol libraries list UI Frames and Map Markers; more built-in graphic-style libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Inventory Icons symbol library (Sword, Shield, Potion, Key, Gem); symbol libraries evidence updated; ~38% → ~40%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Type advanced: the Edit Custom Dictionary dialog, #4936; evidence added; the Check Spelling dialog remains; scores and hours unchanged. | diff --git a/docs/three-d.md b/docs/three-d.md index e6dc279da3..635c1285e3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -122,11 +122,12 @@ them all. The members stay editable: moving or editing one reshapes the solids. - Each member's own geometry effects shape it first, then those of each group inside the 3D group that holds it, applied to that group's members together; the 3D group's geometry effects before the 3D effect reshape the members, and those after it bend the result as a whole. The members' other effects, and the group's own fills and - strokes, are not drawn. A member's opacity applies to its solids; its blending mode does not. An opacity mask on + strokes, are not drawn. A member's opacity and blending mode apply to its solids, and the blending mode of a group + inside the 3D group applies to the solids of that group's members together. An opacity mask on a member masks its solids, and one on a group inside the 3D group masks the solids of that group's members together. The mask stays where it is on the page; it does not turn with the solids. A disabled mask is ignored. -- When a member, or a group inside the 3D group, has an opacity mask, each solid is drawn on its own, the backmost - member's first, as when a solid is transparent. +- When a member, or a group inside the 3D group, has an opacity mask or a blending mode other than Normal, each + solid is drawn on its own, the backmost member's first, as when a solid is transparent. - When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn on its own, the backmost member's first. - Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e122732e0a..939d339548 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > -> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); scores and estimates unchanged. +> **Eraser fill update (2026-11-11):** filled open paths and compound holes use filled-area cutting (#6582); stroke-closure follow-up remains open; scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -160,7 +160,7 @@ tools, never checked side by side) isn't captured row by row. | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Live Paint Bucket, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Eraser: filled open paths and compound holes | done | Area cutting preserves fill outside the swept region (#6582); zero-area open lines retain outline splitting. Original engine integration regressions cover rendered pixels, geometry, holes and mixed strokes. | +| Eraser: filled open paths and compound holes | partial | Area cutting preserves fill outside the swept region (#6582); zero-area open lines retain outline splitting. Original engine integration regressions cover rendered pixels, geometry, holes and mixed strokes. Stroke closure and canceled-fill follow-ups remain open; see G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 260b103870..c827a1ef74 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -15,6 +15,7 @@ mod pngsuite; mod sha256; mod stats; mod test262; +mod ui_commands; mod version; mod web_fonts; @@ -30,11 +31,12 @@ commands: cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) + ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift pdf-deps verify immutable shared PDF writer and patched Krilla sources layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates and the web app test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) corpus [--download] [--affinity] show where test corpora live; --download fetches PngSuite into corpus/pngsuite, --affinity the pinned public Affinity documents into corpus/affinity @@ -59,6 +61,7 @@ fn main() -> ExitCode { Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), Some("i18n-report") => cmd_i18n_report(), + Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), Some("pdf-deps") => pdf_deps::run(&root()), Some("wasm") => cmd_wasm(), @@ -302,6 +305,7 @@ fn cmd_ci() -> Result<(), String> { ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), ("i18n-report", Box::new(cmd_ci_i18n_report)), + ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), ("wasm", Box::new(cmd_wasm)), ]; diff --git a/xtask/src/ui_commands.rs b/xtask/src/ui_commands.rs new file mode 100644 index 0000000000..4bf12a2723 --- /dev/null +++ b/xtask/src/ui_commands.rs @@ -0,0 +1,466 @@ +//! `cargo xtask ui-commands`: regenerate or check the MCP mirror of desktop `UI_COMMANDS`. +//! +//! Source of truth: `crates/ui-egui/src/menus/ui_commands.rs`. +//! Mirror: `crates/mcp/src/ui_catalog.rs` (mcp must not depend on ui-egui). +//! +//! `cargo xtask ui-commands` writes the mirror. +//! `cargo xtask ui-commands --check` fails when the committed file drifts. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +pub const SOURCE: &str = "crates/ui-egui/src/menus/ui_commands.rs"; +pub const MIRROR: &str = "crates/mcp/src/ui_catalog.rs"; +const UI_EGUI_SRC: &str = "crates/ui-egui/src"; + +pub fn run(root: &Path, check_only: bool) -> Result<(), String> { + let expected = generate(root)?; + let mirror_path = root.join(MIRROR); + if check_only { + let actual = std::fs::read_to_string(&mirror_path).map_err(|e| format!("{MIRROR}: {e}"))?; + if actual == expected { + println!("ui-commands: {MIRROR} matches {SOURCE}"); + return Ok(()); + } + return Err(format!("{MIRROR} is out of date with {SOURCE}. Run `cargo xtask ui-commands` and commit the result.")); + } + if let Some(parent) = mirror_path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("{parent:?}: {e}"))?; + } + std::fs::write(&mirror_path, expected).map_err(|e| format!("{MIRROR}: {e}"))?; + println!("ui-commands: wrote {MIRROR}"); + Ok(()) +} + +/// Build the mirror file contents from the desktop table (rustfmt'd, same as `cargo fmt`). +pub fn generate(root: &Path) -> Result { + let source = std::fs::read_to_string(root.join(SOURCE)).map_err(|e| format!("{SOURCE}: {e}"))?; + let entries = parse_ui_commands(&source)?; + let resolved = resolve_entries(root, &entries)?; + rustfmt_source(root, &render_mirror(&resolved)) +} + +/// Format `src` with the workspace `rustfmt` (edition 2024, same as `cargo fmt -p vectorcraft-mcp`). +fn rustfmt_source(root: &Path, src: &str) -> Result { + let dir = std::env::temp_dir(); + let path = dir.join(format!("vectorcraft-ui-catalog-{}.rs", std::process::id())); + std::fs::write(&path, src).map_err(|e| format!("temp mirror: {e}"))?; + let config = root.join("rustfmt.toml"); + let status = + Command::new("rustfmt").args(["--edition", "2024", "--config-path"]).arg(&config).arg(&path).status().map_err(|e| format!("rustfmt: {e}"))?; + let result = if status.success() { + std::fs::read_to_string(&path).map_err(|e| format!("temp mirror read: {e}")) + } else { + Err(format!("rustfmt failed with {status}")) + }; + let _ = std::fs::remove_file(&path); + result +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Entry { + id: IdExpr, + label: String, + shortcut: String, + params: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum IdExpr { + Lit(String), + Path(String), +} + +fn parse_ui_commands(src: &str) -> Result, String> { + let start = src.find("pub const UI_COMMANDS").ok_or_else(|| format!("{SOURCE}: no `pub const UI_COMMANDS`"))?; + let after = &src[start..]; + // Prefer `= &[` so the type `&[(&str, …)]` is not mistaken for the value. + let bracket = after.find("= &[").ok_or_else(|| format!("{SOURCE}: UI_COMMANDS is not an `= &[...]`"))?; + let open_idx = start + bracket + 3; // index of '[' + let body_start = open_idx + 1; + let body_end = find_matching_bracket(src, open_idx).ok_or_else(|| format!("{SOURCE}: unclosed UI_COMMANDS array"))?; + let body = &src[body_start..body_end]; + let tuples = split_top_level_tuples(body)?; + let mut out = Vec::with_capacity(tuples.len()); + for t in tuples { + out.push(parse_tuple(t)?); + } + if out.is_empty() { + return Err(format!("{SOURCE}: UI_COMMANDS is empty")); + } + Ok(out) +} + +fn find_matching_bracket(src: &str, open_idx: usize) -> Option { + let bytes = src.as_bytes(); + if open_idx >= bytes.len() || bytes[open_idx] != b'[' { + return None; + } + let mut depth = 0usize; + let mut in_str = false; + let mut esc = false; + let mut i = open_idx; + while i < bytes.len() { + let c = bytes[i] as char; + if in_str { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == '"' { + in_str = false; + } + i += 1; + continue; + } + match c { + '"' => in_str = true, + '[' => depth += 1, + ']' => { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + _ => {} + } + i += 1; + } + None +} + +fn split_top_level_tuples(body: &str) -> Result, String> { + let mut out = Vec::new(); + let bytes = body.as_bytes(); + let mut i = 0usize; + while i < bytes.len() { + while i < bytes.len() && ((bytes[i] as char).is_whitespace() || bytes[i] == b',') { + i += 1; + } + if i >= bytes.len() { + break; + } + if bytes[i] != b'(' { + return Err(format!("{SOURCE}: expected `(` in UI_COMMANDS, found {:?}", body[i..].chars().take(20).collect::())); + } + let start = i; + let mut depth = 0usize; + let mut in_str = false; + let mut esc = false; + while i < bytes.len() { + let c = bytes[i] as char; + if in_str { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == '"' { + in_str = false; + } + i += 1; + continue; + } + match c { + '"' => in_str = true, + '(' => depth += 1, + ')' => { + depth -= 1; + i += 1; + if depth == 0 { + out.push(&body[start..i]); + break; + } + continue; + } + _ => {} + } + i += 1; + } + if depth != 0 { + return Err(format!("{SOURCE}: unclosed tuple in UI_COMMANDS")); + } + } + Ok(out) +} + +fn parse_tuple(tup: &str) -> Result { + let inner = tup.strip_prefix('(').and_then(|s| s.strip_suffix(')')).ok_or_else(|| format!("{SOURCE}: bad tuple {tup:?}"))?; + let fields = split_fields(inner)?; + if fields.len() != 4 { + return Err(format!("{SOURCE}: tuple has {} fields, want 4: {tup}", fields.len())); + } + let id = parse_id(fields[0].trim())?; + let label = parse_string_lit(fields[1].trim())?; + let shortcut = parse_string_lit(fields[2].trim())?; + let params = parse_string_lit(fields[3].trim())?; + Ok(Entry { id, label, shortcut, params }) +} + +fn split_fields(inner: &str) -> Result, String> { + let mut out = Vec::new(); + let bytes = inner.as_bytes(); + let mut start = 0usize; + let mut i = 0usize; + let mut depth = 0isize; + let mut in_str = false; + let mut esc = false; + while i < bytes.len() { + let c = bytes[i] as char; + if in_str { + if esc { + esc = false; + } else if c == '\\' { + esc = true; + } else if c == '"' { + in_str = false; + } + i += 1; + continue; + } + match c { + '"' => in_str = true, + '(' | '[' | '{' => depth += 1, + ')' | ']' | '}' => depth -= 1, + ',' if depth == 0 => { + out.push(inner[start..i].trim()); + start = i + 1; + } + _ => {} + } + i += 1; + } + let last = inner[start..].trim(); + if !last.is_empty() { + out.push(last); + } + Ok(out) +} + +fn parse_id(field: &str) -> Result { + if field.starts_with('"') { + return Ok(IdExpr::Lit(parse_string_lit(field)?)); + } + if field.starts_with("crate::") { + return Ok(IdExpr::Path(field.to_string())); + } + Err(format!("{SOURCE}: unsupported id expression `{field}`")) +} + +fn parse_string_lit(field: &str) -> Result { + let s = field.trim(); + if !s.starts_with('"') { + return Err(format!("{SOURCE}: expected string literal, got `{s}`")); + } + let mut out = String::new(); + let mut chars = s[1..].chars(); + while let Some(c) = chars.next() { + if c == '\\' { + let Some(n) = chars.next() else { + return Err(format!("{SOURCE}: trailing escape in {s}")); + }; + match n { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + '\\' | '"' | '\'' => out.push(n), + other => return Err(format!("{SOURCE}: unknown escape `\\{other}` in {s}")), + } + } else if c == '"' { + return Ok(out); + } else { + out.push(c); + } + } + Err(format!("{SOURCE}: unclosed string {s}")) +} + +fn resolve_entries(root: &Path, entries: &[Entry]) -> Result, String> { + let mut out = Vec::with_capacity(entries.len()); + for e in entries { + let id = match &e.id { + IdExpr::Lit(s) => s.clone(), + IdExpr::Path(path) => resolve_const_path(root, path)?, + }; + out.push((id, e.label.clone(), e.shortcut.clone(), e.params.clone())); + } + Ok(out) +} + +fn resolve_const_path(root: &Path, path: &str) -> Result { + let trimmed = path.strip_prefix("crate::").ok_or_else(|| format!("{SOURCE}: path `{path}` does not start with crate::"))?; + let mut parts: Vec<&str> = trimmed.split("::").collect(); + let const_name = parts.pop().ok_or_else(|| format!("{SOURCE}: empty path `{path}`"))?; + resolve_in_module(root, &parts, const_name, path) +} + +fn resolve_in_module(root: &Path, module_parts: &[&str], const_name: &str, original: &str) -> Result { + let file = module_file(root, module_parts).ok_or_else(|| format!("{SOURCE}: no file for `{original}`"))?; + let src = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?; + if let Some(v) = find_str_const(&src, const_name) { + return Ok(v); + } + // Follow `pub use path::{..., CONST, ...}` / `pub use path::CONST`. + for target in reexport_targets(&src, const_name) { + let mut next = module_parts.to_vec(); + if target.first() == Some(&"super") { + next.pop(); + next.extend(target.iter().skip(1).copied()); + } else if target.first() == Some(&"crate") { + next = target.iter().skip(1).copied().collect(); + } else { + next.extend(target); + } + if let Ok(v) = resolve_in_module(root, &next, const_name, original) { + return Ok(v); + } + } + Err(format!("{SOURCE}: could not resolve `{original}` (`pub const {const_name}: &str` missing under {})", file.display())) +} + +fn module_file(root: &Path, parts: &[&str]) -> Option { + let base = root.join(UI_EGUI_SRC); + if parts.is_empty() { + return Some(base.join("lib.rs")); + } + let mut dir = base.clone(); + for (i, p) in parts.iter().enumerate() { + let last = i + 1 == parts.len(); + if last { + let rs = dir.join(format!("{p}.rs")); + if rs.is_file() { + return Some(rs); + } + let mod_rs = dir.join(p).join("mod.rs"); + if mod_rs.is_file() { + return Some(mod_rs); + } + return None; + } + dir = dir.join(p); + } + None +} + +fn find_str_const(src: &str, name: &str) -> Option { + // `pub const NAME: &str = "...";` (allow whitespace) + let needle = format!("pub const {name}:"); + let mut search = src; + while let Some(idx) = search.find(&needle) { + let after = &search[idx + needle.len()..]; + let after = after.trim_start(); + if !after.starts_with("&str") { + search = &search[idx + needle.len()..]; + continue; + } + let after = after["&str".len()..].trim_start(); + if !after.starts_with('=') { + search = &search[idx + needle.len()..]; + continue; + } + let after = after[1..].trim_start(); + return parse_string_lit(after).ok(); + } + None +} + +fn reexport_targets<'a>(src: &'a str, const_name: &str) -> Vec> { + let mut out = Vec::new(); + for line in src.lines() { + let t = line.trim(); + if !t.starts_with("pub use ") { + continue; + } + let rest = t.trim_start_matches("pub use ").trim_end_matches(';').trim(); + if let Some((path, braced)) = rest.split_once("::{") { + let names = braced.trim_end_matches('}'); + let hit = names.split(',').map(str::trim).any(|n| n == const_name); + if hit { + out.push(path.split("::").collect()); + } + } else if let Some((path, name)) = rest.rsplit_once("::") + && name.trim() == const_name + { + out.push(path.split("::").collect()); + } + } + out +} + +fn render_mirror(rows: &[(String, String, String, String)]) -> String { + let mut out = String::new(); + out.push_str("//! Desktop UI command catalogue for headless MCP discovery (`ui: true`).\n"); + out.push_str("//! Generated from `crates/ui-egui/src/menus/ui_commands.rs` by `cargo xtask ui-commands`.\n"); + out.push_str("//! Do not edit by hand; re-run the xtask when that table changes.\n"); + out.push('\n'); + out.push_str("/// `(id, label, shortcut, params doc)` — same shape as the desktop `UI_COMMANDS` table.\n"); + out.push_str("pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[\n"); + for (id, label, shortcut, params) in rows { + out.push_str(" ("); + out.push_str(&rust_string_lit(id)); + out.push_str(", "); + out.push_str(&rust_string_lit(label)); + out.push_str(", "); + out.push_str(&rust_string_lit(shortcut)); + out.push_str(", "); + out.push_str(&rust_string_lit(params)); + out.push_str("),\n"); + } + out.push_str("];\n"); + out +} + +fn rust_string_lit(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } + out.push('"'); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_literal_and_path_ids() { + let src = r#" +pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ + ( + crate::addons::arrange::ZOOM, + "Zoom to Selection", + "", + "{importer: \"plugin.\"}", + ), + ("app.language", "Interface Language", "Cmd+L", "{}"), +]; +"#; + let entries = parse_ui_commands(src).unwrap(); + assert_eq!(entries.len(), 2); + assert!(matches!(entries[0].id, IdExpr::Path(_))); + assert_eq!(entries[0].params, "{importer: \"plugin.\"}"); + assert_eq!(entries[1].id, IdExpr::Lit("app.language".into())); + } + + #[test] + fn escape_round_trip_no_extra_backslash() { + let s = "{importer: \"plugin.\"}"; + let lit = rust_string_lit(s); + assert_eq!(lit, r#""{importer: \"plugin.\"}""#); + assert!(!lit.contains(r#"\\\""#)); + } + + #[test] + fn find_const_in_source() { + let src = r#"pub const ZOOM: &str = "addon.arrange.zoomSelection";"#; + assert_eq!(find_str_const(src, "ZOOM").as_deref(), Some("addon.arrange.zoomSelection")); + } +}