diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 9ba4666598..bf15cc340e 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -4,11 +4,11 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Rect, Vec2, rotate_deg}; -use super::edit::{copy_above, selected_roots}; +use super::edit::selected_roots; use super::object::group_nodes; use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or}; use crate::EngineError; -use vectorcraft_doc::Scaling; +use vectorcraft_doc::{Node, Scaling}; const CMD: &str = "object.stepAndRepeat"; const MAX_CELLS: usize = 10_000; @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -119,6 +119,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) { return Err(bad(CMD, "gaps and margin must be finite")); } + if margin < 0.0 { + return Err(bad(CMD, "`margin` must be 0 or more")); + } let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) }; let sheet = sheet_param(p)?; let mut roots = selected_roots(s)?; @@ -148,6 +151,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { return Err(EngineError::Other("the selection has no area to repeat".into())); } + if w + gx <= EPS || h + gy <= EPS { + return Err(bad(CMD, "a negative gap must be smaller than the width or height it is between")); + } let anchor = if fill { let sheet = sheet.or_else(|| { let c = d.bounds_of(&roots, false).unwrap_or(b).center(); @@ -180,6 +186,9 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if roots.len() > 1 { roots = vec![group_nodes(d, &roots)?]; } + // Every copy is made first, and all of them go in with one insertion. + let originals: Vec<(NodeId, Node)> = roots.iter().filter_map(|id| d.node(*id).map(|n| (*id, n.clone()))).collect(); + let mut lists: Vec<(NodeId, Vec)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect(); let mut copied: Vec = vec![]; let mut first = Affine::IDENTITY; for c in &cells { @@ -188,11 +197,21 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { first = m; continue; } - let copies = copy_above(d, &roots, |_, _, n| { + for ((_, original), (_, list)) in originals.iter().zip(lists.iter_mut()) { + let mut n = d.reid(original); n.transform(m, sc); - super::object::keep_pixel_aligned(n, sc); - })?; - copied.extend(copies); + super::object::keep_pixel_aligned(&mut n, sc); + copied.push(n.id); + list.push(n); + } + } + if !copied.is_empty() { + // The copy of the last cell goes directly above its original and the first cell's on top. + for (_, list) in &mut lists { + list.reverse(); + } + d.insert_beside(lists, false)?; + super::typecmd::refresh_bounds_of(d, &copied); } if first != Affine::IDENTITY { for id in &roots { diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 991800d964..4d807f7d8d 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -131,6 +131,46 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(e.execute(CMD, &json!({})).is_err()); } +#[test] +fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() { + let (mut s, _) = setup(); + let steps = undo_steps(&s); + assert!(s.execute(CMD, &json!({"fill": true, "margin": -5})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 1, "columns": 3, "gapX": -50})).is_err()); + assert!(s.execute(CMD, &json!({"rows": 3, "columns": 1, "gapY": -40})).is_err()); + assert!(s.execute(CMD, &json!({"fill": true, "gap": -50})).is_err()); + assert_eq!(undo_steps(&s), steps, "a refusal records no undo step"); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": -10})).unwrap(); + assert_eq!(bounds(&s, r["ids"][1].as_u64().unwrap()), (40.0, 0.0, 90.0, 30.0), "a gap above minus the width overlaps neighbors"); +} + +#[test] +fn copies_go_in_with_one_walk_of_the_document_whatever_the_count() { + let walks = |columns: u64| { + let (mut s, _) = setup(); + for i in 0..50 { + s.execute("shape.rectangle", &json!({"x": 0, "y": 100 + i, "width": 5, "height": 5})).unwrap(); + } + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let before = vectorcraft_doc::tree_walks(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": columns, "gap": 1})).unwrap(); + assert_eq!(r["count"], json!(columns)); + vectorcraft_doc::tree_walks() - before + }; + assert_eq!(walks(40), walks(2), "the walks of the document do not grow with the number of copies"); +} + +#[test] +fn the_last_cells_copy_sits_directly_above_the_original() { + let (mut s, id) = setup(); + let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 1})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + let order: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(order, [id, ids[2], ids[1]]); +} + #[test] fn fill_ignores_explicit_counts() { let (mut s, _) = setup(); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d8d01956f4..b105e606b6 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1013,13 +1013,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts +/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a +/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files. fn path_key(p: &str) -> String { - let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); - let p = p.replace('\\', "/"); - let p = p.trim_end_matches('/').to_string(); - if windows { p.to_lowercase() } else { p } + let b = p.as_bytes(); + let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); + if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } /// `app.redraw()`: returns without changing anything. The app draws a frame between the run's @@ -1503,6 +1503,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { }) } +/// `documents.addDocumentNoUI(startupPreset)`: a new document from the New Document profile +/// `startupPreset` names, as `addDocument(startupPreset)` makes it, without the New Document +/// dialog. Arguments after `startupPreset` are ignored. +fn docs_add_document_no_ui(h: &Host, a: &[Data]) -> Answer { + docs_add_document(h, &a[..a.len().min(2)]) +} + /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are /// left out. The settings stay with the run, which hands the script an object of the @@ -1581,6 +1588,19 @@ fn preset_of(h: &Host, d: &Data) -> Option { (i < h.dom.presets.borrow().len()).then_some(i) } +/// `DocumentPreset.typename`: a `TypeError` for a preset from an earlier run, as its settings give. +fn preset_typename(h: &Host, a: &[Data]) -> Answer { + preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?; + Ok(text("DocumentPreset")) +} + +/// `DocumentPreset.toString()`: `[DocumentPreset]`, or a `TypeError` for a preset from an earlier +/// run. +fn preset_to_string(h: &Host, a: &[Data]) -> Answer { + preset_of(h, arg(a, 0)).ok_or_else(|| HostError::Type("this is not a DocumentPreset".into()))?; + Ok(text("[DocumentPreset]")) +} + /// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one. fn preset_enum(key: &str) -> Option<&'static str> { Some(match key { @@ -2949,8 +2969,8 @@ fn classes(link: &Link) -> Vec { new_preset(&h) }); let mut members = vec![ - ("typename".to_string(), typename_of("DocumentPreset"), typed("string")), - ("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])), + ("typename".to_string(), get(link, preset_typename), typed("string")), + ("toString".to_string(), method(link, preset_to_string), returns("string", &[])), ]; members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } @@ -2988,6 +3008,7 @@ fn classes(link: &Link) -> Vec { method(l, docs_add_document), returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), ), + ("addDocumentNoUI", method(l, docs_add_document_no_ui), returns("Document", &[("startupPreset", "string")])), ("toString", class_text("Documents"), returns("string", &[])), ]), Some(function(l, docs_at)), diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index ad2711558e..20411101d0 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -631,13 +631,14 @@ fn rearrange_refuses_bad_indices_and_at() { assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); } -/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). -fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet), +/// inside the returned temporary folder, which is removed when dropped, also when the test fails. +fn with_profiles(name: &str) -> (Session, std::path::PathBuf, vectorcraft_testkit::TempDir) { + let root = vectorcraft_testkit::TempDir::new(&format!("newdoc-profiles-{name}")); + let dir = root.join(format!("vc-newdoc-profiles-{name}")); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); - (s, dir) + (s, dir, root) } fn swatch_names(s: &Session) -> Vec { @@ -705,7 +706,7 @@ fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { #[test] fn an_edited_profile_starts_the_documents_of_its_category() { - let (mut s, dir) = with_profiles("edited"); + let (mut s, dir, _root) = with_profiles("edited"); let listed = s.execute("file.newProfiles", &json!({})).unwrap(); let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); @@ -733,7 +734,6 @@ fn an_edited_profile_starts_the_documents_of_its_category() { s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); - let _ = std::fs::remove_dir_all(&dir); } /// The fill, stroke and weight of `id` in the active document. @@ -745,7 +745,7 @@ fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::P #[test] fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("default-style"); + let (mut s, _, _root) = with_profiles("default-style"); // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); @@ -796,12 +796,11 @@ fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke assert_eq!(s.paint.fill, green); s.execute("paint.default", &json!({})).unwrap(); assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn the_profile_follows_the_preset_access_and_reset() { - let (mut s, dir) = with_profiles("choice"); + let (mut s, dir, _root) = with_profiles("choice"); edit_print_profile(&mut s, &dir); // A request that may not read the folder gets the defaults, and the reason; edit is refused // before anything is written. @@ -841,7 +840,6 @@ fn the_profile_follows_the_preset_access_and_reset() { assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The first run's style of text object `id`. @@ -853,7 +851,7 @@ fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle { #[test] fn a_profiles_normal_character_style_is_the_default_font() { - let (mut s, dir) = with_profiles("default-font"); + let (mut s, _, _root) = with_profiles("default-font"); // The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"}); @@ -891,13 +889,12 @@ fn a_profiles_normal_character_style_is_the_default_font() { let st = first_run(&s, &made["id"]); let default = vectorcraft_doc::CharStyle::default(); assert_eq!((st.font_family, st.size), (default.font_family, default.size)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults"); + let (mut s, _, _root) = with_profiles("apply-defaults"); const GLOW: &str = r#""#; // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. @@ -987,7 +984,6 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); assert_eq!(s.doc().unwrap().history.step(), step); - let _ = std::fs::remove_dir_all(&dir); } /// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's @@ -995,7 +991,7 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { #[test] fn profile_defaults_stay_with_an_unrelated_object_selected() { use vectorcraft_color::Paint; - let (mut s, dir) = with_profiles("apply-defaults-selected"); + let (mut s, _, _root) = with_profiles("apply-defaults-selected"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); s.execute("paint.setFill", &json!({"none": true})).unwrap(); @@ -1013,7 +1009,6 @@ fn profile_defaults_stay_with_an_unrelated_object_selected() { assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); - let _ = std::fs::remove_dir_all(&dir); } /// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open @@ -1026,7 +1021,7 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { "roman": {"font": "JetBrains Mono", "size": roman}, }}) }; - let (mut s, dir) = with_profiles("apply-defaults-composite"); + let (mut s, _, _root) = with_profiles("apply-defaults-composite"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); @@ -1052,12 +1047,11 @@ fn profile_defaults_bring_the_composite_font_of_the_default_font() { s.execute("edit.undo", &json!({})).unwrap(); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(profile(&s), Some(100.0)); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { - let (mut s, dir) = with_profiles("errors"); + let (mut s, dir, _root) = with_profiles("errors"); let elsewhere = dir.with_extension("elsewhere"); std::fs::create_dir_all(&dir).unwrap(); std::fs::create_dir_all(&elsewhere).unwrap(); @@ -1084,22 +1078,19 @@ fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let inside = crate::file_access::AutomationRoots::new(&[dir.as_path()], &[dir.as_path()]).unwrap().unwrap(); let e = run(&mut s, &inside, "file.newProfiles.reset"); assert!(e.starts_with(&format!("{whole}: ")), "{e}"); - let _ = std::fs::remove_dir_all(&elsewhere); - let _ = std::fs::remove_dir_all(&dir); } /// The new document's links find their files from the profile's file, as a document opened from /// that file does; a document without a profile has no such file. #[test] fn the_new_document_links_from_the_profile_file() { - let (mut s, dir) = with_profiles("links"); + let (mut s, dir, _root) = with_profiles("links"); edit_print_profile(&mut s, &dir); assert_eq!(s.execute("file.new", &json!({"preset": "A4"})).unwrap()["profile"], "Print"); let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert_eq!(s.doc().unwrap().links_from, None); - let _ = std::fs::remove_dir_all(&dir); } /// A color profile the profile's file carries is installed when this machine lacks it, as opening @@ -1111,7 +1102,7 @@ fn a_profile_brings_the_color_profile_its_file_carries() { return; } use vectorcraft_color::cms; - let (mut s, dir) = with_profiles("icc"); + let (mut s, dir, _root) = with_profiles("icc"); let builtin = cms::profiles().into_iter().find(|p| p.kind == cms::ProfileKind::Rgb && p.builtin && p.name != cms::SRGB).unwrap(); let icc = cms::icc_bytes(&builtin.name).unwrap().to_vec(); let name = format!("Profile RGB {}", std::process::id()); @@ -1140,12 +1131,11 @@ fn a_profile_brings_the_color_profile_its_file_carries() { std::fs::write(dir.join("Web.vectorcraft"), serde_json::to_vec(&v).unwrap()).unwrap(); let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profile"] == "Web" && r["warnings"][0].as_str().unwrap_or_default().contains(&broken), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { - let (mut s, dir) = with_profiles("damaged"); + let (mut s, dir, _root) = with_profiles("damaged"); s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); let defaults = swatch_names(&s); std::fs::create_dir_all(&dir).unwrap(); @@ -1162,23 +1152,20 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); - let _ = std::fs::remove_dir_all(&dir); } #[cfg(unix)] #[test] fn a_profile_that_is_a_link_is_not_followed() { - let (mut s, dir) = with_profiles("link"); + let (mut s, dir, root) = with_profiles("link"); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); // A profile the folder held, moved out and linked back in. - let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + let outside = root.join("outside.vectorcraft"); std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); assert!(r.get("profile").is_none(), "{r}"); - let _ = std::fs::remove_file(&outside); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..a6e792f5c1 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -970,7 +970,11 @@ fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); let d = &s.active().unwrap().doc; assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); - assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + if keep { + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "keepEmpty true keeps it, empty"); + } else { + assert!(d.node(compound).is_none(), "keepEmpty false deletes the compound path"); + } } } @@ -1002,11 +1006,23 @@ fn a_grid_by_column_takes_the_number_of_rows() { let distinct = |mut v: Vec| { v.sort_unstable(); v.dedup(); - v.len() + v }; let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); - assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + assert_eq!((tops.len(), lefts.len()), (rows, cols), "{layout} {count}"); + // Each artboard's row and column, counted from the top and from the left: a grid by column + // fills each column top to bottom, and the right-to-left grid starts at the rightmost column. + let index = |v: &[i64], x: f64| v.iter().position(|&t| t == x.round() as i64); + let placed: Vec<_> = boards.iter().map(|b| (index(&tops, b.rect.y0), index(&lefts, b.rect.x0))).collect(); + let expected: Vec<_> = (0..count) + .map(|i| match layout { + "GridByRow" => (Some(i / cols), Some(i % cols)), + "GridByCol" => (Some(i % rows), Some(i / rows)), + _ => (Some(i % rows), Some(cols - 1 - i / rows)), + }) + .collect(); + assert_eq!(placed, expected, "{layout} {count}"); } } @@ -1382,6 +1398,18 @@ fn a_document_preset_is_an_instance_of_its_class() { assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); } +/// A preset kept from an earlier run throws from `typename` and `toString()` as it does from its +/// settings. +#[test] +fn a_document_preset_from_an_earlier_run_throws_from_typename_and_to_string() { + let mut s = Session::new(); + run(&mut s, "#targetengine keep\nvar p = new DocumentPreset();").unwrap(); + for member in ["p.width", "p.typename", "p.toString()", "String(p)"] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains("TypeError") && e.contains("not a DocumentPreset"), "{member}: {e}"); + } +} + /// The values the presets hold count against the run's heap, a value assigned again in place of /// the one before it. #[test] @@ -1559,6 +1587,23 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +/// `addDocumentNoUI(startupPreset)` makes the document `addDocument(startupPreset)` makes, and +/// ignores the arguments after the preset's name. +#[test] +fn add_document_no_ui_makes_the_startup_presets_document() { + let mut s = Session::new(); + let out = log( + &mut s, + "var a = app.documents.addDocument('Web'); var p = new DocumentPreset(); p.width = 333;\ + var b = app.documents.addDocumentNoUI('Web', p, true);\ + vc.log([b.typename, b.width === a.width, b.height === a.height, b.width === 333, app.documents.length]);", + ); + assert_eq!(out, vec![json!(["Document", true, true, false, 2])]); + let e = failure(&mut s, "app.documents.addDocumentNoUI('No Such Preset');"); + assert!(e.contains("no startup preset called No Such Preset"), "{e}"); + assert_eq!(s.documents().len(), 2); +} + #[test] fn setting_selected_keeps_how_the_other_objects_are_selected() { let (mut s, a, b) = doc(); @@ -1598,16 +1643,19 @@ fn add_document_takes_only_a_document_preset() { #[test] fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-profile"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); // A profile with no file gives the defaults. let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); assert_eq!(out, vec![json!("Document")]); assert_eq!(s.doc().unwrap().links_from, None); - // A script reads the profile's file in the app's own folder. + // A script reads the profile's file in the app's own folder, with no document open from it. s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); log(&mut s, "app.documents.addDocument('Print');"); assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); @@ -1634,13 +1682,12 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { // A startup preset with no profile reads no file. let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { - let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let root = vectorcraft_testkit::TempDir::new("script-add-document-warning"); + let dir = root.join("profiles"); let mut s = Session::new(); s.attach_new_doc_profiles(dir.clone()); s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); @@ -1658,7 +1705,6 @@ fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); assert!(named, "{lines:?}"); assert_eq!(s.documents().len(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1761,8 +1807,7 @@ fn setters_on_a_stale_item_report_it_before_a_bad_value() { fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_ones() { // `pageItems[0]` is the topmost object, the one made last. let (mut s, _, b) = doc(); - let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = vectorcraft_testkit::TempDir::new("dom-revert"); let path = dir.join("saved.vectorcraft"); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { @@ -1778,7 +1823,6 @@ fn objects_read_before_a_revert_are_stale_and_ones_read_after_are_the_loaded_one ); assert_eq!(out, vec![json!(2)]); assert_eq!(s.active().unwrap().doc.node(b).unwrap().name.as_deref(), Some("loaded")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -2046,6 +2090,21 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); } +/// Outside Windows a `\` is part of a file name: `/a\b.svg` is not the open `/a/b.svg`. +#[test] +fn get_is_file_open_keeps_a_backslash_in_a_unix_file_name() { + let (mut s, _, _) = doc(); + let fixture = vectorcraft_testkit::TempDir::new("script-file-open-backslash"); + let dir = fixture.join("a"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("b.svg"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let same = serde_json::to_string(&path.to_string_lossy()).unwrap(); + let backslash = serde_json::to_string(&format!("{}\\b.svg", dir.to_string_lossy())).unwrap(); + let out = log(&mut s, &format!("vc.log(app.getIsFileOpen({same})); vc.log(app.getIsFileOpen({backslash}));")); + assert_eq!(out, vec![json!(true), json!(cfg!(windows))]); +} + #[test] fn a_menu_command_runs_its_command_on_the_selection() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 8fd3e8c8fe..fe56754ca3 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -88,10 +88,10 @@ fn a_run_is_one_undo_step_in_each_document_it_changed() { #[test] fn a_run_that_changes_nothing_leaves_no_step_no_mark_and_no_journal_entry() { + let dir = fresh_folder("noop"); for source in ["", "var a = 1 + 2;", "vc.log(vc.document); vc.commands.length;"] { let mut s = two_docs(); - s.execute("document.save", &json!({"path": std::env::temp_dir().join(format!("vc-noop-{}.svg", std::process::id())).to_string_lossy()})) - .unwrap(); + s.execute("document.save", &json!({"path": dir.join("noop.svg").to_string_lossy()})).unwrap(); let before = state(&s); let revisions = |s: &Session| s.documents().iter().map(|d| d.revision).collect::>(); let revisions_before = revisions(&s); @@ -183,6 +183,11 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw new ReferenceError('BridgeTalk is not defined');", "thrown", "ReferenceError: BridgeTalk is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw new ReferenceError('Window is not defined');", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: activeDocument is not defined';", "thrown", "ReferenceError: activeDocument is not defined", "script"), + ("throw new ReferenceError('activeDocument is not defined');", "thrown", "ReferenceError: activeDocument is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -266,9 +271,7 @@ fn bad_parameters_are_refused_before_anything_runs() { #[test] fn files_are_checked_before_they_are_read() { - let dir = std::env::temp_dir().join(format!("vc-script-run-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let dir = fresh_folder("checked"); let write = |name: &str, bytes: &[u8]| { let p = dir.join(name); std::fs::write(&p, bytes).unwrap(); @@ -296,7 +299,6 @@ fn files_are_checked_before_they_are_read() { assert_eq!(s.execute("script.run", &path(&upper)).unwrap()["log"], json!([3])); std::fs::create_dir_all(dir.join("folder.js")).unwrap(); assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,7 +343,6 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { assert_eq!(kept["log"], json!(["1xy"]), "{kept}"); let e = s.execute("script.run", &path(&write("pattern.jsx", "var [a] = [1];"))).unwrap_err().to_string(); assert!(e.contains("SyntaxError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -367,7 +368,6 @@ fn a_js_script_reads_object_literal_extensions_and_function_names_and_a_jsx_scri assert_eq!(legacy["log"], json!([false]), "{legacy}"); // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "var a = 1; var o = { a };").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -390,7 +390,6 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() } // Script text given without a file keeps the ExtendScript language. assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -417,7 +416,6 @@ fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); assert!(e.contains("TypeError"), "{e}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -451,7 +449,6 @@ fn every_script_reads_e4x_and_has_the_xml_objects() { s.execute("script.run", &path(&write("first.js", "#targetengine xmlkept\nlet k = 1;"))).unwrap(); let later = s.execute("script.run", &path(&write("second.jsx", "#targetengine xmlkept\nvc.log(XML('2').toString());"))).unwrap(); assert_eq!(later["log"], json!(["2"]), "{later}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -474,15 +471,11 @@ fn a_js_script_defines_classes_and_a_jsx_script_cannot() { assert!(e.contains("SyntaxError"), "{name}: {e}"); } assert!(run(&mut s, "var C = class {};").unwrap_err().to_string().contains("SyntaxError")); - let _ = std::fs::remove_dir_all(&dir); } -/// A new empty folder for test `name`. -fn fresh_folder(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir +/// A new empty folder for test `name`, removed when dropped, also when the test fails. +fn fresh_folder(name: &str) -> vectorcraft_testkit::TempDir { + vectorcraft_testkit::TempDir::new(&format!("script-run-{name}")) } /// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder @@ -530,7 +523,6 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { assert!(!s.guides_locked(), "the failed batch's Lock Guides does not stay"); assert!(path.exists()); assert_eq!(r["written"], json!([p]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -544,7 +536,6 @@ fn an_export_that_fails_names_no_file() { assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// The commands a script runs read and write only where its `File` and `Folder` objects may (its @@ -594,7 +585,6 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let r = run(&mut s, &call("document.save", &own)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); assert!(own.exists()); - let _ = std::fs::remove_dir_all(&dir); } /// The color at the middle of the PNG at `path`. @@ -656,7 +646,6 @@ fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); - let _ = std::fs::remove_dir_all(&dir); } /// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate @@ -674,7 +663,8 @@ fn tried(id: &str, params: &str) -> String { #[test] fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { use crate::tests_links::{RED, open, place, png, save, session, write}; - let art = fresh_folder("gate-linked-runs").join("art"); + let root = fresh_folder("gate-linked-runs"); + let art = root.join("art"); std::fs::create_dir_all(&art).unwrap(); let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); @@ -704,7 +694,6 @@ fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() log.push(later["log"][0].clone()); assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); - let _ = std::fs::remove_dir_all(art.parent().unwrap()); } /// A data set value a script gives a document, and a document a script opens, let no later run @@ -741,7 +730,6 @@ fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { s.execute("document.save", &json!({"path": mine})).unwrap(); let saved = run(&mut s, &read_secret).unwrap(); assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); - let _ = std::fs::remove_dir_all(&dir); } /// A save the person started before a script's command changed the document, and that finishes @@ -766,7 +754,6 @@ fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { job.complete(&mut s, uid); let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); assert_eq!(r["log"], json!(["denied"]), "{r}"); - let _ = std::fs::remove_dir_all(&dir); } /// A command a script runs does not save into the app's own libraries; the same command run @@ -784,7 +771,6 @@ fn a_scripts_commands_do_not_save_into_the_apps_libraries() { assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -867,7 +853,6 @@ fn an_abandoned_run_reports_the_files_it_wrote() { let report = s.script_report().unwrap(); assert_eq!((report["kind"].as_str(), report["written"].clone()), (Some("stopped"), json!([p])), "{report}"); assert!(s.script_failure_text().unwrap().contains(&p)); - let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -1457,15 +1442,13 @@ fn a_file_saved_before_a_failure_stays_written_and_is_named() { assert!(e.contains(&p), "{e}"); assert_eq!(s.script_report().unwrap()["written"], json!([p])); assert_eq!(state(&s), before, "the document does not keep the new path"); - let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope /// the frames that advance it run in. #[test] fn a_framed_run_keeps_the_file_access_scope_it_started_in() { - let dir = std::env::temp_dir().join(format!("vc-script-scope-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = fresh_folder("scope"); let (allowed, outside) = (dir.join("allowed"), dir.join("outside")); std::fs::create_dir_all(&allowed).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -1492,13 +1475,12 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); - let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_committed_run_exports_what_it_drew() { - let path = std::env::temp_dir().join(format!("vc-script-export-{}.svg", std::process::id())); - let _ = std::fs::remove_file(&path); + let dir = fresh_folder("export"); + let path = dir.join("export.svg"); let p = path.to_string_lossy().into_owned(); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); @@ -1509,7 +1491,6 @@ fn a_committed_run_exports_what_it_drew() { assert_eq!(svg.matches(" JsResult { interp.get_from(o, &key_of(k), &Value::Object(o)) } -fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property_indexed(o, &key_of(k)) +/// The element at `k` when the object or its prototypes have one: [[HasProperty]], then [[Get]]. +/// An object of a host class with an indexer answers an array index with one call of the indexer, +/// made as `k in object` makes it, and has the element when the answer is not `undefined`. +fn element_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult> { + let key = key_of(k); + if crate::value::array_index(&key).is_some() + && let Some(f) = interp.host_indexer(o)? + { + let v = interp.host_index(&f, o, crate::Data::Number(k), true)?; + return Ok((!matches!(v, Value::Undefined)).then_some(v)); + } + if !interp.has_property_indexed(o, &key)? { + return Ok(None); + } + interp.get_from(o, &key, &Value::Object(o)).map(Some) } /// The estimated bytes a new element adds. diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 9b7ca4bfa5..1afff8a1f1 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -5,11 +5,12 @@ //! the range is much longer than the object has properties (a sparse array such as //! `new Array(4294967295)`), so a long empty range costs nothing and no index is allocated for //! it. The list of indices is made again whenever a script adds an index property to any object -//! while the method runs. Every index visited takes a unit of fuel. +//! while the method runs. An object of a host class with an indexer has every index of the range +//! visited, since its elements are not properties. Every index visited takes a unit of fuel. use super::{ - Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, get_at, has_at, length_of, method, native, new_array, object_to_string, put_at, - require_callable, to_integer, + Builder, ELEMENT_BYTES, arg, constructor, create_at, delete_at, element_at, get_at, length_of, method, native, new_array, object_to_string, + put_at, require_callable, to_integer, }; use crate::heap::{Class, NativeKind, ObjId}; use crate::interp::{Abrupt, Interp, JsResult, strict_eq}; @@ -121,7 +122,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { impl Indices { fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec) -> JsResult { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; - if hi.saturating_sub(lo) > DENSE_SPAN { + // An object of a host class with an indexer holds its elements in the host, not in + // properties, so every index of the range is visited. + if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() { let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); if hi - lo > (present as u64).saturating_mul(8) { it.sparse = Some(it.gather(interp)?); @@ -206,11 +209,7 @@ impl Indices { /// The element at `k` when the object or its prototypes have one. fn element(interp: &mut Interp, o: ObjId, k: u64) -> JsResult> { - let k = k as f64; - if !has_at(interp, o, k)? { - return Ok(None); - } - get_at(interp, o, k).map(Some) + element_at(interp, o, k as f64) } /// ToObject of `this`, kept reachable while `f` runs. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 7f20a30adf..cbbc5a5adb 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -21,7 +21,10 @@ //! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the //! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what //! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as -//! a third argument, and is true when it gives a value other than `undefined`. +//! a third argument, and is true when it gives a value other than `undefined`. The `Array.prototype` +//! methods that skip missing elements, such as `forEach` and `map`, read each index of such an +//! object with that one call and take its answer as the element, so an indexer called with `true` +//! gives the element itself, or `undefined` when there is none. //! //! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each //! member of its class and of the classes it descends from, apart from the members that are not @@ -105,7 +108,10 @@ pub struct HostClass { /// What `reflect` tells of the members, each under the name of one of `members`. A member /// without an entry has the type `unknown` and nothing else. pub info: Vec<(String, MemberInfo)>, - /// What `object[i]` gives for an array index `i`. + /// What `object[i]` gives for an array index `i`. Called with `true` as a third argument, it + /// gives the same element, or `undefined` when there is none. The `Array.prototype` methods that + /// skip missing elements, such as `forEach` and `map`, make that call and use its answer as the + /// element; reads without the third argument, such as those of `join`, are ordinary reads. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. pub construct: Option, @@ -365,7 +371,8 @@ impl Interp { /// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an /// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer - /// gets `true` as a third argument. + /// gets `true` as a third argument and gives the element itself, or `undefined` when there is + /// none, not a marker. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { self.use_fuel()?; if self.host_ref_size(id)?.is_none() { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index cd7518eb4b..31450070f8 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -1035,6 +1035,49 @@ fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() { assert_eq!(calls.get(), 1); } +/// A realm with `it`, a host collection of `len` numbers whose element `i` is `i`, and the count +/// of the indexer's calls. +fn numbers(len: usize) -> (Realm, Rc>) { + let mut r = realm(10_000_000); + let calls: Rc> = Rc::default(); + let seen = calls.clone(); + let index: HostFunction = Rc::new(move |a| { + seen.set(seen.get() + 1); + match a.get(1) { + Some(Data::Number(n)) if *n < len as f64 => Ok(Data::Number(*n)), + _ => Ok(Data::Undefined), + } + }); + let length: HostFunction = Rc::new(move |_| Ok(Data::Number(len as f64))); + let class = HostClass { + name: "Numbers".into(), + parent: None, + members: vec![("length".into(), HostMember::Get(length))], + info: Vec::new(), + index: Some(index), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Numbers", &[1.0]))]).unwrap(); + (r, calls) +} + +#[test] +fn array_methods_visit_every_element_of_a_long_host_collection() { + let (mut r, _) = numbers(5000); + let source = "var n = 0; Array.prototype.forEach.call(it, function () { n++; }); \ + var m = Array.prototype.map.call(it, function (x) { return x; }); \ + [n, m.length, m[4999], Array.prototype.lastIndexOf.call(it, 0), Array.prototype.indexOf.call(it, 4999)].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("5000,5000,4999,0,4999".into())); +} + +#[test] +fn array_methods_call_the_indexer_once_for_each_element() { + let (mut r, calls) = numbers(3); + let source = "var s = 0; Array.prototype.forEach.call(it, function (x) { s += x; }); s"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(3.0)); + assert_eq!(calls.get(), 3); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index c20582141e..db83163e57 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1127,21 +1127,35 @@ mod tests { open(&mut app); let out = laid_out(&mut app); let nodes = out.platform_output.accesskit_update.as_ref().map(|u| u.nodes.clone()).unwrap_or_default(); - let card = nodes + // The Home screen's own document cards stand behind the dialog, and the update lists nodes in no fixed order: + // the card is looked for under the dialog only. + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut in_dialog = Vec::new(); + let mut stack: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Dialog).map(|(id, _)| *id).collect(); + while let Some(id) = stack.pop() { + if let Some(node) = by_id.get(&id) { + in_dialog.push(*node); + stack.extend(node.children().iter().copied()); + } + } + let cards: Vec<_> = in_dialog .iter() - .find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false)) - .and_then(|(_, n)| n.bounds()) + .filter(|n| n.role() == egui::accesskit::Role::ListItem && n.label().is_some_and(|l| !l.is_empty()) && n.is_selected() == Some(false)) + .filter_map(|n| n.bounds()) .map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) - .expect("a preset card that is not selected"); + .collect(); + assert!(!cards.is_empty(), "a preset card that is not selected"); let shapes = crate::tests_labels::flat_painted_shapes(&out.shapes); let rects: Vec<_> = shapes.iter().filter_map(|shape| if let egui::Shape::Rect(rect) = shape { Some(rect) } else { None }).collect(); let veil = |fill: egui::Color32| fill.a() > 0 && fill.a() < scrim.a() && fill.to_opaque() == scrim.to_opaque(); - assert!( - rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)), - "a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}", - rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::>() - ); - assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile"); + for card in cards { + assert!( + rects.iter().any(|rect| veil(rect.fill) && rect.rect.contains_rect(card.shrink(1.0)) && card.expand(1.0).contains_rect(rect.rect)), + "a veil of the scrim {scrim:?} covers the resting card {card:?}: {:?}", + rects.iter().filter(|rect| card.expand(1.0).contains_rect(rect.rect)).map(|rect| (rect.rect, rect.fill)).collect::>() + ); + assert!(rects.iter().any(|rect| rect.fill == egui::Color32::WHITE && card.contains_rect(rect.rect)), "the card's paper is on the tile"); + } } /// Recent shows each entry as it was made: a portrait and a landscape A3 are two documents, and diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 927b344d8d..4a14fe4d2a 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -21,6 +21,40 @@ pub(crate) const CMD: &str = "object.stepAndRepeat"; pub(crate) struct Open { pub id: DialogId, pub preview: LivePreview, + /// The opening document's uid and revert count. + document: (u64, u64), +} + +impl Open { + fn in_source(&self, app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|doc| (doc.uid, doc.reverts) == self.document) + } + + /// Why OK is refused while the opening document is not the active one, after a revert too. + fn away(&self, app: &mut VectorcraftApp) -> Option { + if self.in_source(app) { + return None; + } + let (uid, _) = self.document; + if app.session.active().is_some_and(|doc| doc.uid == uid) { + let reason = tl!("The document was reverted. Reopen this dialog to continue."); + app.status(reason); + Some(reason.into()) + } else if app.session.documents().iter().any(|doc| doc.uid == uid) { + Some("switch back to the document where Step and Repeat was opened".into()) + } else { + Some("the document where Step and Repeat was opened has closed".into()) + } + } +} + +/// Rolls back the preview of an open dialog and drops its record. +fn cancel_open(app: &mut VectorcraftApp) { + if let Some(open) = app.object_dialogs.step.take() + && open.in_source(app) + { + open.preview.cancel(app); + } } fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> { @@ -104,6 +138,9 @@ pub(crate) fn open(app: &mut VectorcraftApp) { fn try_open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; + // Rolls back the preview of a dialog this one replaces, before the cut paths are listed. + cancel_open(app); + let document = app.session.active().map(|doc| (doc.uid, doc.reverts)).ok_or("no document")?; let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0); let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points); let cuts = cut_options(app); @@ -112,23 +149,28 @@ fn try_open(app: &mut VectorcraftApp) -> Result { }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; + if let Some(reason) = open.away(app) { + app.object_dialogs.step = Some(open); + return Err(reason); + } let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields)); if done.is_err() { app.object_dialogs.step = Some(open); } done.map(|_| ()) }; - let cancel: Box = Box::new(|app| { - if let Some(open) = app.object_dialogs.step.take() { - open.preview.cancel(app); - } - }); + let cancel: Box = Box::new(cancel_open); let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?; - app.object_dialogs.step = Some(Open { id, preview: LivePreview::default() }); + app.object_dialogs.step = Some(Open { id, preview: LivePreview::default(), document }); Ok(Value::Null) } +/// Each frame: previews the dialog's values on the opening document while Preview is on. Another +/// document, or the opening one after a revert, gets no preview. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + if !app.object_dialogs.step.as_ref().is_some_and(|open| open.in_source(app)) { + return; + } let Some(mut open) = app.object_dialogs.step.take() else { return }; let shown = app.dialogs().and_then(|host| host.with(|h| h.get_by_id::(open.id).map(|d| (d.is_previewing(), params(d.fields()))))); @@ -165,4 +207,100 @@ mod tests { let ids: Vec = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect(); assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i))); } + + type Harness = egui_kittest::Harness<'static, VectorcraftApp>; + + /// An app with two documents, each with one selected square, the first one active. + fn two_documents() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + for x in [20, 70] { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app + } + + /// A harness that shows the dialog host and runs this module's pump each frame. + fn start(app: VectorcraftApp) -> Harness { + let mut ready = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut ready, true) { + crate::testing::install(ui.ctx()); + app.adopt_context(ui.ctx()); + return; + } + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + pump(app, ui.ctx()); + crate::dialogs::host::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h + } + + fn id(h: &Harness) -> DialogId { + h.state().object_dialogs.step.as_ref().expect("Step and Repeat is open").id + } + + fn set(h: &mut Harness, key: &str, value: Value) { + let (ctx, id) = (h.ctx.clone(), id(h)); + h.state().dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, key, value)).unwrap(); + h.run_steps(2); + } + + fn confirm(h: &mut Harness) { + let (ctx, id) = (h.ctx.clone(), id(h)); + assert!(h.state().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)) || h.state().object_dialogs.step.is_some()); + h.run_steps(3); + } + + fn objects(h: &Harness) -> usize { + h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len() + } + + #[test] + fn preview_and_ok_stay_on_the_opening_document() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6, "the opening document previews 2 × 3"); + + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + let other = h.state().session.doc().unwrap().doc.clone(); + set(&mut h, "columns", json!(4)); + assert_eq!(h.state().session.doc().unwrap().doc, other, "Preview must leave the other document unchanged"); + confirm(&mut h); + assert_eq!(h.state().session.doc().unwrap().doc, other, "OK must leave the other document unchanged"); + assert!(h.state().object_dialogs.step.is_some(), "the dialog stays open"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK applies on the opening document"); + assert_eq!(objects(&h), 8); + } + + #[test] + fn reopening_rolls_back_the_earlier_preview() { + let mut h = start(two_documents()); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "columns", json!(3)); + assert_eq!(objects(&h), 6); + open(h.state_mut()); + h.run_steps(2); + set(&mut h, "preview", json!(false)); + assert_eq!(objects(&h), 1, "the first dialog's preview is rolled back"); + assert!(!h.state().session.in_interaction()); + set(&mut h, "columns", json!(3)); + confirm(&mut h); + assert!(h.state().object_dialogs.step.is_none(), "OK of the reopened dialog applies"); + assert_eq!(objects(&h), 6); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 31412c3703..55886fae8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2969,8 +2969,10 @@ through `$`: name in that thread chooses is VectorCraft's own reading; names with no VectorCraft tool throw. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, - which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of - columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol` and the number + of columns for `GridByRow` and `RLGridByRow`; `Row`, `RLRow` and `Column` put the artboards in one row or column and + do not use it; a supplied value must still be a whole number from 1 to `numArtBoards`, which is 1 when omitted, or + `add` throws a `RangeError`), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` @@ -2990,7 +2992,10 @@ through `$`: profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. - `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + `showOptionsDialog` true throws `Dialog unavailable` with no document made. `addDocumentNoUI(startupPreset)` + makes the document `addDocument(startupPreset)` makes and ignores any further arguments. A `DocumentPreset` kept + from an earlier run (with `#targetengine`) throws a `TypeError` when its settings are read or assigned and when its `typename` + or `toString()` is read. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems`, `selection` and `views`. `views` (https://ai-scripting.docsforadobe.dev/jsobjref/Views/) lists each window, tab, or tiled pane the desktop app has drawn for the document, in view-number order. Each view @@ -3022,8 +3027,9 @@ through `$`: object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` - (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs - `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is already in + the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` on the + copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when @@ -3093,7 +3099,9 @@ through `$`: nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, - letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + letter case is ignored and `\` matches `/`) and does not resolve the path it is given. On Windows every path is a + Windows path; on macOS and Linux only a path that starts with a drive letter is, and in the others `\` is a + character of a file name. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the @@ -4504,8 +4512,9 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing. are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a -boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, -also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. +boolean or `null`. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps +it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean or `null` +is rejected. `null` for `guides`, `keepEmpty` or `keepJoined` counts as leaving the key out. Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as `path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected (the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected @@ -4513,7 +4522,7 @@ whole, as `path.removeAnchors` leaves it, so the next Delete removes the whole p cut there, and their selected anchors stay in the path, as with `keepJoined: false`; and objects selected whole are deleted, in the same undo step. `keepJoined` defaults to the `deleteKeepsPathsJoined` preference, and the value used joins the journal entry; a saved step without it opens the paths, as it did when it was recorded. With `ids`, `keepJoined` has no -effect. A `keepJoined` value that is not a boolean is an error, with or without `ids`. +effect. A `keepJoined` value that is not a boolean or `null` is an error, with or without `ids`. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff6429756c..db42c0d72c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. @@ -1190,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), 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: 7,000 of 7,070 runs pass (the 35 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` 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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), 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. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `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: 7,000 of 7,070 runs pass (the 35 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,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,514 of 1,514 runs pass. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`.