From 33bee45ab19ccae866ff485739a07973eb1b5736 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:14:31 -0800 Subject: [PATCH 001/533] Dialogs: windows that fit their lists to the screen scroll once the lists are smallest Import Shortcut Set shrinks its Keys and Shortcuts lists to fit the window's height, down to a tenth of their size. In a window too short for the rest of the dialog with its lists at their smallest, the dialog ran off the top (by 42 pt at 1280 by 400), and at 300 pt Apply and Cancel were out of reach. Dialogs whose rows scroll inside them (scrolled_rows: Transform Each, Recolor Artwork, Symbolism Options, the tracing presets' replace list and plugin forms) ran off the same way once their rows were down to nothing. - modal::fits_itself_then_scrolls marks contents that fit themselves and says whether they are at their smallest. While they are and the window is still taller than the screen has room for, the window scrolls as a whole. scrolled_rows and Import Shortcut Set use it. - scrolled_rows are drawn at least one control tall, so a row stays in reach while the window scrolls as a whole. - While a window scrolls as a whole, the rest of it is measured from its full height (modal::full_height), not from the part in view, so the lists grow back when the window is made taller. - Import Shortcut Set leaves the gaps above and below the window, as the other dialogs do, and counts its Keys list at the height it is drawn when it holds fewer rows than its room. When the rest of the dialog changes, it draws the next frame at once. Character and Paragraph Style Options keep fitting themselves without scrolling as a whole. --- crates/ui-egui/src/dialogs/modal.rs | 81 ++++++++--- crates/ui-egui/src/dialogs/shortcut_import.rs | 22 ++- crates/ui-egui/src/dialogs/tests_scroll.rs | 131 ++++++++++++++++-- 3 files changed, 196 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index 580f985c8d..61484445c3 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -3,8 +3,8 @@ //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows //! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its -//! heading and buttons stay in view. A window without such rows that is still too tall or too wide -//! for the screen scrolls as a whole on that axis. +//! heading and buttons stay in view. A window without such rows, or with them at their smallest, +//! that is still too tall or too wide for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -71,12 +71,13 @@ pub(crate) fn show_at( }); } // A window whose contents are wider than the screen has room for, or taller without - // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, - // so none of it is out of reach. The contents keep their ids whether the window scrolls - // or not, so a field being edited keeps its text when that changes. + // rows that scroll ([`scrolled_rows`], [`body_rows`]) or with its own rows at their + // smallest ([`fits_itself_then_scrolls`]), scrolls as a whole on that axis, so none of + // it is out of reach. The contents keep their ids whether the window scrolls or not, so + // a field being edited keeps its text when that changes. let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); - let (r, contents) = if wide || tall { + let (r, contents, view) = if wide || tall { let room = whole_room(ctx, margin); let mut area = egui::ScrollArea::new([wide, tall]); if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { @@ -89,12 +90,18 @@ pub(crate) fn show_at( .min_scrolled_width(room.x) .min_scrolled_height(room.y) .show(ui, |ui| ui.scope_builder(scope, add).inner); - (out.inner, out.content_size) + // The area's rectangle is the one it was given before its contents were drawn; on + // an axis that does not scroll, the window grows to the contents anyway. + (out.inner, out.content_size, if tall { out.inner_rect.height() } else { out.content_size.y }) } else { let r = ui.scope_builder(scope, add).inner; - (r, ui.min_rect().size()) + let size = ui.min_rect().size(); + (r, size, size.y) }; - ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + ctx.data_mut(|m| { + m.insert_temp(id.with(CONTENTS_KEY), contents); + m.insert_temp(id.with(VIEW_KEY), view); + }); r })?; keep_rest(ctx, id, shown.response.rect.height(), margin); @@ -209,11 +216,18 @@ const REST_KEY: &str = "modal-rest"; /// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). const OWN_ROWS_KEY: &str = "modal-own-rows"; const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: its contents fit themselves to the screen and let the window scroll as +/// a whole below their smallest ([`fits_itself_then_scrolls`]) this frame, and whether they are at +/// their smallest. +const OWN_WHOLE_KEY: &str = "modal-own-whole"; /// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. const BODY_KEY: &str = "modal-body"; -/// Under a modal window's id: how large its contents would be without scrolling as a whole, this -/// frame. +/// Under a modal window's id: how large its contents would be without scrolling as a whole +/// (`CONTENTS_KEY`) and how tall the part of them in view is (`VIEW_KEY`), this frame; and how tall +/// the window would be without scrolling as a whole, as last drawn (`FULL_KEY`, [`full_height`]). const CONTENTS_KEY: &str = "modal-contents"; +const VIEW_KEY: &str = "modal-view"; +const FULL_KEY: &str = "modal-full"; /// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on /// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). const TALL_KEY: &str = "modal-tall"; @@ -235,10 +249,11 @@ const HOLDS_KEY: &str = "modal-holds"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as -/// last drawn (a frame late, as only the drawn window knows its height). +/// last drawn (a frame late, as only the drawn window knows its height), and at least +/// one control tall; below that, the window scrolls as a whole ([`fits_itself_then_scrolls`]). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - fits_itself(ui); + fits_itself_then_scrolls(ui, rows_room(ui.ctx(), ui.layer_id().id) <= ui.spacing().interact_size.y); let (r, drawn, _) = rows(ui, salt, true, add); ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); r @@ -251,6 +266,21 @@ pub(crate) fn fits_itself(ui: &egui::Ui) { ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); } +/// [`fits_itself`] for contents whose smallest size can still be taller than the screen has room +/// for: while they are drawn at their `smallest` and the window is taller than the room, it +/// scrolls as a whole. The contents fit themselves to the screen's height less the gaps above and +/// below the window and the rest of the window as [`full_height`] gives it. +pub(crate) fn fits_itself_then_scrolls(ui: &egui::Ui, smallest: bool) { + fits_itself(ui); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_WHOLE_KEY), smallest)); +} + +/// How tall modal window `id` was when last drawn, with all of its contents: while it scrolls as a +/// whole, taller than the part drawn on the screen. +pub(crate) fn full_height(ctx: &egui::Context, id: Id) -> Option { + ctx.data(|m| m.get_temp::(id.with(FULL_KEY))) +} + /// The body of a shared dialog window. While the window would be taller than the screen has room /// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; /// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. @@ -294,7 +324,7 @@ pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { } /// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the -/// window as last drawn. +/// window as last drawn (as tall as all of it while it scrolls as a whole, [`full_height`]). fn rows_room(ctx: &egui::Context, id: Id) -> f32 { let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) @@ -308,7 +338,10 @@ fn rows_room(ctx: &egui::Context, id: Id) -> f32 { /// scrolling. fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { let id = ui.layer_id().id; - let room = rows_room(ui.ctx(), id); + let mut room = rows_room(ui.ctx(), id); + if ui.ctx().data(|m| m.get_temp::(id.with(OWN_WHOLE_KEY))).is_some() { + room = room.max(ui.spacing().interact_size.y); + } let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); if !scroll { let rows = ui.scope_builder(scope, add); @@ -329,13 +362,21 @@ fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl /// one (the window just opened, or what is around them changed), the next frame is drawn at once, /// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll /// while the window would be taller than the screen has room for without them scrolling; a window -/// without rows that scroll scrolls as a whole while its contents would be taller than the room, -/// and any window scrolls sideways while its contents would be wider. +/// without rows that scroll, or with rows of its own at their smallest +/// ([`fits_itself_then_scrolls`]), scrolls as a whole while its contents would be taller than the +/// room, and any window scrolls sideways while its contents would be wider. fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let view = ctx.data_mut(|m| m.remove_temp::(id.with(VIEW_KEY))).unwrap_or(contents.y); + // While the window scrolls as a whole, the rest of it is measured from the window as tall as + // all of its contents. Measured from the part in view, rows sized from the rest would stay + // short when the screen grows, and the window would go on scrolling. + let height = height + (contents.y - view).max(0.0); + ctx.data_mut(|m| m.insert_temp(id.with(FULL_KEY), height)); let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + let own_whole = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_WHOLE_KEY))); ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); let room = whole_room(ctx, margin); let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; @@ -343,8 +384,10 @@ fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, _ => false, }; - // A window that fits itself to the screen's height can still be too wide for it. - let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + // A window that fits itself to the screen can still be too wide for it, and too tall once what + // it sizes is at its smallest. + let over = contents.y > room.y + 0.5; + let whole = [contents.x > room.x + 0.5, own_whole.map_or(!own && rows.is_none() && over, |smallest| smallest && over)]; let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); let mut repaint = tall != was_tall || whole != was_whole; diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 3409a0b987..de8de13cda 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -79,6 +79,8 @@ const CHORD_W: f32 = 90.0; /// The tallest the Keys and Shortcuts lists get (points). const KEYS_LIST_H: f32 = 140.0; const ROWS_LIST_H: f32 = 280.0; +/// The share of their tallest the Keys and Shortcuts lists shrink to at the least. +const SMALLEST_SHARE: f32 = 0.1; /// An entry of the file and what it becomes. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -666,15 +668,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let statuses = review.statuses(); // The Keys and Shortcuts lists get the window's height less the rest of the dialog, as the frame - // before drew it. + // before drew it, and the gaps above and below the dialog. let id = egui::Id::unique("dialog-shortcut-import"); let rest = ctx.data(|m| m.get_temp::(id.with("rest"))).unwrap_or(0.0); let (keys, mods) = review.asked(); let keys_open = d.bool("__keysOpen") && (!keys.is_empty() || !mods.is_empty()); - let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); + let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { - crate::dialogs::modal::fits_itself(ui); + crate::dialogs::modal::fits_itself_then_scrolls(ui, rows_h <= ROWS_LIST_H * SMALLEST_SHARE); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); @@ -739,8 +741,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); }); }); - if let Some(window) = ctx.memory(|m| m.area_rect(id)) { - ctx.data_mut(|m| m.insert_temp(id.with("rest"), window.height() - lists)); + // When the rest of the dialog changed, the next frame is drawn at once, for the lists to fit + // without waiting for input. + if let Some(window) = crate::dialogs::modal::full_height(ctx, id) + && (window - lists - rest).abs() > 0.5 + { + ctx.data_mut(|m| m.insert_temp(id.with("rest"), window - lists)); + ctx.request_repaint(); } if review != before { if review.rows.iter().map(|r| &r.target).ne(before.rows.iter().map(|r| &r.target)) { @@ -764,7 +771,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { /// window are left for them: their tallest, or both shorter by the same share, down to a tenth. fn list_heights(room: f32, keys_open: bool) -> (f32, f32) { let tallest = if keys_open { KEYS_LIST_H + ROWS_LIST_H } else { ROWS_LIST_H }; - let share = (room / tallest).clamp(0.1, 1.0); + let share = (room / tallest).clamp(SMALLEST_SHARE, 1.0); (KEYS_LIST_H * share, ROWS_LIST_H * share) } @@ -837,7 +844,8 @@ fn keys_section(ui: &mut egui::Ui, d: &mut Dialog, review: &mut Review, height: } }) }); - list.inner.inner_rect.height() + // The list shrinks to its rows when they are fewer than `height` holds. + list.inner.content_size.y.min(list.inner.inner_rect.height()) } /// A vertical list that scrolls when its contents are taller than `height` points, and is then diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs index 3f24dcaba1..c43f67488b 100644 --- a/crates/ui-egui/src/dialogs/tests_scroll.rs +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -10,13 +10,15 @@ use super::*; type Open = fn(&mut VectorcraftApp); -/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls -/// ([`modal::scrolling`]). +/// What a dialog drew: the shapes, the dialog window's rectangle, how it scrolls +/// ([`modal::scrolling`]), and whether it scrolled upright as a whole in any frame since it was +/// opened or the window last changed size. struct Shown { shapes: Vec, window: Rect, body: Option, whole: [bool; 2], + tall_once: bool, } /// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away @@ -24,6 +26,12 @@ struct Shown { /// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists /// inside it) and draw it until it settles again. fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { + show_resized(open, None, size, scroll) +} + +/// [`show_in`], with the dialog first drawn until it settles in a window `first_size` in size when +/// that is given. +fn show_resized(open: Open, first_size: Option, size: egui::Vec2, scroll: bool) -> Shown { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); @@ -45,9 +53,9 @@ fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { .unwrap_or((egui::Id::NULL, Rect::NOTHING)) }; let mut time = 0.0; - let mut frames = |app: &mut VectorcraftApp, first: Vec| { + let mut frames = |app: &mut VectorcraftApp, first: Vec, screen: Rect| { let mut first = Some(first); - let mut shapes = vec![]; + let (mut shapes, mut tall_once) = (vec![], false); for _ in 0..12 { time += 1.0; let input = @@ -55,10 +63,15 @@ fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); out.textures_delta.clear(); shapes = std::mem::take(&mut out.shapes); + tall_once |= modal::scrolling(&ctx, window(&ctx).0).1[1]; } - shapes + (shapes, tall_once) }; - let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]); + if let Some(first_size) = first_size { + let first_screen = Rect::from_min_size(Pos2::ZERO, first_size); + frames(&mut app, vec![egui::Event::PointerMoved(first_screen.max - vec2(2.0, 2.0))], first_screen); + } + let (mut shapes, tall_once) = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))], screen); if scroll { let wheel = egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, @@ -69,16 +82,16 @@ fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { }; let (id, w) = window(&ctx); let (body, whole) = modal::scrolling(&ctx, id); - let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole, tall_once }; // On the window's upright bar, else on its body's bar, else on its sideways bar, else at // its right edge. let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); - shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); + shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel], screen).0; } let (id, window) = window(&ctx); let (body, whole) = modal::scrolling(&ctx, id); - Shown { shapes, window, body, whole } + Shown { shapes, window, body, whole, tall_once } } /// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or @@ -110,12 +123,13 @@ fn body_bar(shown: &Shown) -> Option { } /// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that -/// runs most of the window's height (lists inside it are shorter). +/// runs most of the window's height, or all of it but the margins of a short window (lists inside +/// it are shorter). fn whole_bar(shown: &Shown) -> Option { let w = shown.window; bars(shown, false, true) .into_iter() - .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height()) + .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= (0.8 * w.height()).min(w.height() - 48.0)) .max_by(|a, b| a.height().total_cmp(&b.height())) } @@ -332,7 +346,7 @@ fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() }; let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); out.textures_delta.clear(); - let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] }; + let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2], tall_once: false }; seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen); } seen @@ -386,6 +400,99 @@ fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); } +#[test] +fn a_window_that_fits_itself_scrolls_as_a_whole_once_its_lists_are_at_their_smallest() { + // These dialogs size their own lists from the window's height. In a window that holds them + // with shorter lists, they fit without scrolling; in one too short for them with their lists at + // their smallest, they scroll as a whole instead of running off the screen. + // A dialog, how it opens, its buttons, text in its lists or rows, and window heights with + // whether it scrolls in each and whether that text is then seen at the top or the end of the + // window. Import Shortcut Set's lists at their smallest are shorter than one of their rows, and + // they scroll inside themselves; in a 90 pt window Transform Each's first row is in view only + // part way down. + type Case = (&'static str, Open, &'static [&'static str], &'static [&'static str], &'static [(f32, bool, bool)]); + let opens: [Case; 2] = [ + ( + "Import Shortcut Set", + open_shortcut_import, + &["Apply", "Cancel"], + &["/Key 902"], + &[(600.0, false, true), (400.0, true, false), (300.0, true, false)], + ), + ( + "Transform Each", + |app| { + app.run("ui.menuDialog", json!({"command": "object.transformEach"})).unwrap(); + }, + &["OK", "Cancel"], + &["Scale"], + &[(200.0, false, true), (150.0, true, true), (120.0, true, true), (90.0, true, false)], + ), + ]; + let mut wrong = vec![]; + for (name, open, labels, rows, heights) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + if tall.whole != [false; 2] { + wrong.push(format!("{name}: in a large window it scrolls ({:?})", tall.whole)); + } + // The Keys list of Import Shortcut Set is open, so both of its lists shrink. + if !texts(&tall).iter().any(|(s, ..)| rows.contains(&s.as_str())) { + wrong.push(format!("{name}: its lists or rows are not drawn in a large window")); + } + for &(height, scrolls, rows_seen) in heights { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1280.0, height)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + if !screen.contains_rect(shown.window) || shown.whole != [false, scrolls] || whole_bar(&shown).is_some() != scrolls { + wrong.push(format!( + "{name} at {height}: the window ({:?}) stays on the screen and scrolls as a whole ({:?}) with its bar ({:?}) only when {scrolls}", + shown.window, + shown.whole, + bars(&shown, false, true) + )); + } + if !scrolls && shown.window.height() >= tall.window.height() { + wrong.push(format!("{name} at {height}: its lists are not shorter than in a large window ({:?})", shown.window)); + } + if !scrolls && shown.tall_once { + wrong.push(format!("{name} at {height}: it scrolled as a whole while its lists were fitting to the window")); + } + let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels)); + for label in labels { + let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen); + if !seen(&top) && !seen(&end) { + wrong.push(format!("{name} at {height}: {label} cannot be scrolled into view: {top:?} {end:?}")); + } + } + let (top, end) = (buttons(&shown, screen, rows), buttons(&scrolled, screen, rows)); + if rows_seen && !top.iter().chain(&end).any(|(_, seen)| *seen) { + wrong.push(format!("{name} at {height}: its lists or rows cannot be scrolled into view: {top:?} {end:?}")); + } + } + // Grown from the shortest window to the tallest that holds it, it stops scrolling and is + // as tall as when opened there. + let (fits, short) = (heights[0].0, heights[heights.len() - 1].0); + let opened = show_in(open, vec2(1280.0, fits), false); + let grown = show_resized(open, Some(vec2(1280.0, short)), vec2(1280.0, fits), false); + if grown.whole != [false; 2] || (grown.window.height() - opened.window.height()).abs() > 1.0 { + wrong.push(format!( + "{name} grown from {short} to {fits}: it scrolls ({:?}) or its height ({:?}) differs from opened there ({:?})", + grown.whole, grown.window, opened.window + )); + } + } + // The same in a window too narrow for Import Shortcut Set, where it goes on scrolling sideways. + let opened = show_in(open_shortcut_import, vec2(640.0, 600.0), false); + let grown = show_resized(open_shortcut_import, Some(vec2(640.0, 300.0)), vec2(640.0, 600.0), false); + if opened.whole != [true, false] || grown.whole != [true, false] || (grown.window.height() - opened.window.height()).abs() > 1.0 { + wrong.push(format!( + "Import Shortcut Set grown from 640 by 300 to 640 by 600 ({:?}, {:?}) scrolls sideways only and is as tall as opened there ({:?}, {:?})", + grown.whole, grown.window, opened.whole, opened.window + )); + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + #[test] fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right From afe28e06e0ace962f13654be26d9accbbe08515a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:35:42 -0800 Subject: [PATCH 002/533] Menus: labels start in one check column, checked or not The in-app menus put the check column into the label text. A checked row started with a check mark and two spaces, an unchecked row with five spaces, and rows with no on/off state started with nothing. In the proportional interface font these prefixes have different widths, so checked, unchecked, plain and submenu labels started at different x positions. The mark is now its own text section, and the label after it starts at the end of one fixed column. A menu level that has on/off rows keeps the column on every row, including plain commands, disabled rows and submenus. Panel menus, the panel submenus next to them, the Float Panel and Move Panel To items after a panel's rows in its tab's context menu, Arrange Documents and the workspace switcher use the same helper. The text of each row is unchanged, so accessible names still start with the mark. A label with a line that runs right to left is laid out as before. --- crates/ui-egui/src/canvas/task_bar.rs | 2 +- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/dialogs/recolor.rs | 4 +- crates/ui-egui/src/menus/bar.rs | 30 +++++---- crates/ui-egui/src/menus/keyboard.rs | 45 ++++++++----- crates/ui-egui/src/menus/tests.rs | 59 +++++++++++++++++ crates/ui-egui/src/panel_docking.rs | 21 ++++++- crates/ui-egui/src/panel_docking/tests.rs | 56 +++++++++++++++++ crates/ui-egui/src/panels/align.rs | 2 +- crates/ui-egui/src/panels/brushes.rs | 4 +- crates/ui-egui/src/panels/character.rs | 8 ++- crates/ui-egui/src/panels/color_wheel.rs | 4 +- crates/ui-egui/src/panels/css_properties.rs | 3 +- crates/ui-egui/src/panels/graphic_styles.rs | 4 +- crates/ui-egui/src/panels/layers/controls.rs | 4 +- crates/ui-egui/src/panels/libraries.rs | 2 +- crates/ui-egui/src/panels/library_panel.rs | 2 +- crates/ui-egui/src/panels/opentype.rs | 2 +- crates/ui-egui/src/panels/paragraph.rs | 4 +- crates/ui-egui/src/panels/properties.rs | 4 +- crates/ui-egui/src/panels/swatches/actions.rs | 4 +- crates/ui-egui/src/panels/symbols.rs | 4 +- crates/ui-egui/src/panels/tabs.rs | 3 +- crates/ui-egui/src/widgets.rs | 41 +++++++++++- crates/ui-egui/src/widgets/buttons.rs | 63 ++++++++++++++++--- crates/ui-egui/src/workspaces.rs | 7 +-- 26 files changed, 320 insertions(+), 64 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 03ced4f7c6..952e1831fa 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -526,7 +526,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The actions and chips the bar offers for this selection or tool, each // checked while it shows, which turns it on or off; then Reset Bar // Actions, which shows every action again. - ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Bar Actions"), None), |ui| { ui.set_min_width(170.0); for (label, action, shown) in task_bar_offered(ui.ctx()) { let Some(action) = action else { continue }; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 511967d45f..6ed79d9719 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -199,7 +199,7 @@ fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { menus::Item::Cmd(label, id, p) => { let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; let label = crate::i18n::t_id(id, label); - let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + let text = crate::widgets::check_row_text(ui, if checked == Some(true) { "✓ " } else { " " }, label, None); if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { clicked = Some((id, if p.is_null() { json!({}) } else { p })); ui.close(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1b80ce5e35..403468f2ed 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1831,7 +1831,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut pick = Some((i, true)); ui.close(); } - ui.menu_button(tl!("Limit to Library"), |ui| { + ui.menu_button(widgets::check_row_text(ui, "", tl!("Limit to Library"), None), |ui| { let cur = d.str("limitTo"); if widgets::menu_item(ui, tl!("None"), true, cur.is_empty()) { limit_to = Some("".to_string()); @@ -2615,7 +2615,7 @@ fn color_menu(ui: &mut Ui, rows: &[Value], i: usize, base: Option) -> Opt } if let Some(c) = rows.get(i).and_then(to_color) { // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Select Shade")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Select Shade"), None), |ui| { if let Some(sv) = shade_grid(ui, &c) { choice = Some(MenuChoice::Shade(i, sv)); } diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs index d0e1d237d7..540607da71 100644 --- a/crates/ui-egui/src/menus/bar.rs +++ b/crates/ui-egui/src/menus/bar.rs @@ -40,7 +40,7 @@ pub fn menu_bar(app: &mut VectorcraftApp, ui: &mut egui::Ui) -> f32 { let mut titles = Vec::with_capacity(tree.len()); for (title, items) in tree.iter() { let cue = root_rows.iter().find(|r| r.label == crate::i18n::t(title)).and_then(|r| r.cue.as_ref()).filter(|_| show_cues); - let text = keyboard::text(ui, crate::i18n::t(title), "", cue, Some(13.0)); + let text = keyboard::text(ui, crate::i18n::t(title), None, cue, Some(13.0)); let resp = ui.push_id(("menu-bar-root", *title), |ui| ui.add(egui::Button::new(text))).inner; crate::palette::note_spot(ui, resp.rect, || crate::palette::SpotAt::Menu((*title).to_string())); keyboard::bind_root(&ctx, title, &resp); @@ -164,7 +164,12 @@ fn render_items_scoped( if let Some(path) = path { keyboard::note_level(ui.ctx(), path); } - for e in items.iter().filter_map(|it| entry(app, it)) { + let entries: Vec = items.iter().filter_map(|it| entry(app, it)).collect(); + // A menu that shows check marks keeps one check column for all of its rows, as native menus + // do: every label starts at the same x, checked or not, and on submenus and plain commands too. + let column = checks && entries.iter().any(|e| matches!(e, Entry::Item(r) if r.checked.is_some())); + let room = column.then_some(""); + for e in entries { match e { Entry::Sep => { ui.separator(); @@ -176,7 +181,7 @@ fn render_items_scoped( if let Some(access) = rows.next() { ui.push_id(access.key.salt(), |ui| { let cue = access.cue.as_ref().filter(|_| keyboard::cues(ui.ctx())); - let text = keyboard::text(ui, label, "", cue, None); + let text = keyboard::text(ui, label, room, cue, None); if !ui.is_sizing_pass() { keyboard::prepare_submenu(ui.ctx(), access, ui.next_auto_id()); } @@ -198,7 +203,8 @@ fn render_items_scoped( } }); } else { - ui.menu_button(label, |ui| { + let text = keyboard::text(ui, label, room, None, None); + ui.menu_button(text, |ui| { widgets::menu_scroll(ui, |ui| { widgets::menu_min_width(ui, 200.0); render_items(app, ui, children, checks || shows_marks(app, children), clicked); @@ -206,7 +212,7 @@ fn render_items_scoped( }); } } - Entry::Item(row) => render_row(app, ui, &row, checks, rows.next(), clicked), + Entry::Item(row) => render_row(app, ui, &row, column, rows.next(), clicked), } } } @@ -224,27 +230,27 @@ fn only_toggles(app: &VectorcraftApp, items: &[Item]) -> bool { rows.peek().is_some() && rows.all(|e| matches!(e, Entry::Item(r) if r.checked.is_some())) } -/// One menu item: its label (with a check mark, or the room for one, under `checks`), its shortcut, -/// and Type › Font's samples. -fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, checks: bool, access: Option<&AccessRow>, clicked: &mut Option<(String, Value)>) { +/// One menu item: its label (after a check mark or the room for one, under `column`: the menu +/// keeps a check column), its shortcut, and Type › Font's samples. +fn render_row(app: &VectorcraftApp, ui: &mut egui::Ui, row: &Row, column: bool, access: Option<&AccessRow>, clicked: &mut Option<(String, Value)>) { let sc = row.shortcut.map(shown_shortcut).unwrap_or_default(); let Some((id, p)) = row.command else { ui.add_enabled_ui(false, |ui| { let cue = access.and_then(|r| r.cue.as_ref()).filter(|_| keyboard::cues(ui.ctx())); - let text = keyboard::text(ui, row.label.as_ref(), "", cue, None); + let text = keyboard::text(ui, row.label.as_ref(), column.then_some(""), cue, None); ui.add(egui::Button::new(text).shortcut_text(sc)); }) .response .on_disabled_hover_text(tl!("Coming soon — tracked in the parity plan")); return; }; - let prefix = match row.checked.filter(|_| checks) { + let mark = column.then_some(match row.checked { Some(true) => "✓ ", Some(false) => " ", None => "", - }; + }); let cue = access.and_then(|r| r.cue.as_ref()).filter(|_| keyboard::cues(ui.ctx())); - let text = keyboard::text(ui, row.label.as_ref(), prefix, cue, None); + let text = keyboard::text(ui, row.label.as_ref(), mark, cue, None); // Type → Font: each family's sample after its name (Enable in-menu font previews). let sampled = p.get("font").and_then(Value::as_str).filter(|_| id == "text.setStyle" && app.session.prefs.font_preview); let draw = |ui: &mut egui::Ui| match sampled { diff --git a/crates/ui-egui/src/menus/keyboard.rs b/crates/ui-egui/src/menus/keyboard.rs index 6c496a67b3..8354b18f4a 100644 --- a/crates/ui-egui/src/menus/keyboard.rs +++ b/crates/ui-egui/src/menus/keyboard.rs @@ -917,24 +917,41 @@ pub(super) fn finish_bar(ctx: &Context, open: bool, command_chosen: bool) { } /// A layout job changes only presentation; literal '&'/'_' and all native/shared labels survive. -pub(super) fn text(ui: &egui::Ui, label: &str, prefix: &str, cue: Option<&Cue>, size: Option) -> egui::WidgetText { - let Some(cue) = cue else { - let text = format!("{prefix}{label}"); - return match size { - Some(size) => egui::RichText::new(text).size(size).color(super::Tokens::get(ui.ctx()).text).into(), - None => text.into(), - }; +/// With `mark` (a check mark, the room for one, or nothing), the label starts at the end of the +/// menu's check column ([`crate::widgets::check_column_job`]). +pub(super) fn text(ui: &egui::Ui, label: &str, mark: Option<&str>, cue: Option<&Cue>, size: Option) -> egui::WidgetText { + let split = cue.and_then(|cue| { + let (before, rest) = label.split_at_checked(cue.range.start)?; + let (letter, after) = rest.split_at_checked(cue.range.len())?; + Some((before, letter, after)) + }); + let color = match (split, size) { + (Some(_), _) => ui.visuals().text_color(), + (None, Some(_)) => super::Tokens::get(ui.ctx()).text, + (None, None) => egui::Color32::PLACEHOLDER, }; - let Some((before, rest)) = label.split_at_checked(cue.range.start) else { return format!("{prefix}{label}").into() }; - let Some((letter, after)) = rest.split_at_checked(cue.range.len()) else { return format!("{prefix}{label}").into() }; + if split.is_none() && mark.is_none() { + return match size { + Some(size) => egui::RichText::new(label).size(size).color(color).into(), + None => label.into(), + }; + } let mut font = egui::TextStyle::Button.resolve(ui.style()); if let Some(size) = size { font.size = size; } - let format = egui::TextFormat { font_id: font, color: ui.visuals().text_color(), ..Default::default() }; - let mut job = egui::text::LayoutJob::default(); - job.append(&format!("{prefix}{before}"), 0.0, format.clone()); - job.append(letter, 0.0, egui::TextFormat { underline: egui::Stroke::new(1.0, format.color), ..format.clone() }); - job.append(after, 0.0, format); + let format = egui::TextFormat { font_id: font, color, ..Default::default() }; + let (mut job, lead) = match mark { + Some(mark) => crate::widgets::check_column_job(ui, mark, label, &format), + None => (egui::text::LayoutJob::default(), 0.0), + }; + match split { + Some((before, letter, after)) => { + job.append(before, lead, format.clone()); + job.append(letter, 0.0, egui::TextFormat { underline: egui::Stroke::new(1.0, format.color), ..format.clone() }); + job.append(after, 0.0, format); + } + None => job.append(label, lead, format), + } job.into() } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index fa94c19cd5..f00bddb9f0 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -491,6 +491,65 @@ fn opening_the_file_menu_reads_the_scripts_folder_again() { let _ = std::fs::remove_dir_all(dir); } +/// The Window menu keeps one check column: the labels of checked and unchecked panels, of plain +/// commands and of submenus all start at the same x. +#[test] +fn window_menu_labels_start_in_one_column() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let titles = bar_frame(&mut app, &ctx, vec![]); + let titles = if titles.is_empty() { bar_frame(&mut app, &ctx, vec![]) } else { titles }; + let window = menu_tree().iter().filter(|(t, _)| *t != "VectorCraft").position(|(t, _)| *t == "Window").unwrap(); + egui::Popup::open_id(&ctx, titles[window].1); + // Each text drawn, with the x where its label starts (after any check mark or blank room). + let mut shown: Vec<(String, f32)> = vec![]; + for _ in 0..3 { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + menu_bar(&mut app, ui); + }); + out.textures_delta.clear(); + fn texts(s: &egui::Shape, out: &mut Vec<(String, f32)>) { + match s { + egui::Shape::Text(t) => { + let start = t.galley.rows.first().and_then(|r| Some(r.pos.x + r.row.glyphs.iter().find(|g| g.chr != ' ' && g.chr != '✓')?.pos.x)); + if let Some(x) = start { + out.push((t.galley.text().to_string(), t.pos.x + x)); + } + } + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + shown.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + } + // A row that is on and one that is off, by their state in the menu. + let tree = menu_tree(); + let (_, items) = tree.iter().find(|(t, _)| *t == "Window").unwrap(); + let state = |on: bool| { + items.iter().find_map(|it| match entry(&app, it) { + Some(Entry::Item(row)) if row.checked == Some(on) => Some(row.label.to_string()), + _ => None, + }) + }; + let (on, off) = (state(true).expect("a checked Window item"), state(false).expect("an unchecked Window item")); + let x = |label: &str| { + shown + .iter() + .find(|(t, _)| t.trim_start_matches(['✓', ' ']) == label) + .map(|(_, x)| *x) + .unwrap_or_else(|| panic!("{label} missing from {shown:?}")) + }; + let column = x(&on); + for label in [off.as_str(), "New Window", "Arrange", "Workspace"] { + let at = x(label); + assert!((at - column).abs() < 0.5, "{label:?} starts at {at}, the checked {on:?} at {column}"); + } +} + #[test] fn a_popup_covering_a_title_does_not_switch_menus() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index fb0ab20a30..6e35ca8388 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1548,6 +1548,12 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { } } +/// Where a tab's context menu records whether the panel's own items, drawn first, use the check +/// column. +fn check_column_key(ui: &egui::Ui) -> egui::Id { + ui.scope_id().with("panel-menu-check-column") +} + /// The panels' content, labels and icons. struct PanelContent<'a> { app: &'a mut VectorcraftApp, @@ -1637,7 +1643,20 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } fn panel_menu(&mut self, ui: &mut egui::Ui, id: &String) { - crate::panels::panel_menu_items(self.app, ui, id); + let before = ui.cursor().min; + // A panel can draw no rows, as Layers does with no document open. + let drew = crate::panels::panel_menu_items(self.app, ui, id) && ui.cursor().min != before; + ui.data_mut(|d| d.insert_temp(check_column_key(ui), drew)); + } + + /// The stock tab-menu items (Float Panel, Move Panel To, the group items) after a panel's own + /// menu items start their labels at the same check column. Other docking menus keep plain text. + fn action_label(&mut self, ui: &egui::Ui, logical: &str, _font: &egui::FontId, _color: egui::Color32) -> egui::WidgetText { + if ui.data(|d| d.get_temp::(check_column_key(ui))).unwrap_or(false) { + crate::widgets::check_row_text(ui, "", logical, None) + } else { + logical.into() + } } fn group_header_width(&self, panels: &[String], active: &String, floating: bool, _strip_width: f32) -> f32 { diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2c90c7cd54..d5029f9762 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -2040,3 +2040,59 @@ fn the_double_triangle_on_the_tab_strip_cycles_the_display_sizes() { assert!(h.app.ui.color_hide_options); assert!(cycle_button(&h, "swatches").is_none()); } + +/// Right-click `panel`'s tab and return each text drawn with the x of its first glyph that is not +/// a space or a check mark, on the screen and within the text. +fn tab_menu_texts(h: &mut Harness, panel: &str) -> Vec<(String, f32, f32)> { + let tab = h.tab(panel).expect("the tab is drawn").center(); + let secondary = |pressed| Event::PointerButton { pos: tab, button: PointerButton::Secondary, pressed, modifiers: Default::default() }; + h.frame(vec![Event::PointerMoved(tab), secondary(true)]); + h.frame(vec![secondary(false)]); + let mut shown: Vec<(String, f32, f32)> = vec![]; + for _ in 0..3 { + h.time += 0.05; + let input = egui::RawInput { time: Some(h.time), screen_rect: Some(SCREEN), ..Default::default() }; + let app = &mut h.app; + let mut out = h.ctx.run_ui(input, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + fn texts(s: &egui::Shape, out: &mut Vec<(String, f32, f32)>) { + match s { + egui::Shape::Text(t) => { + let start = t.galley.rows.first().and_then(|r| Some(r.pos.x + r.row.glyphs.iter().find(|g| g.chr != ' ' && g.chr != '✓')?.pos.x)); + if let Some(x) = start { + out.push((t.galley.text().trim_start_matches(['✓', ' ']).to_string(), t.pos.x + x, x)); + } + } + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + shown.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut shown)); + } + h.press(egui::Key::Escape, Default::default()); + shown +} + +#[test] +fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() { + let mut h = Harness::new(); + crate::theme::install_fonts(&h.ctx); + h.frame(vec![]); + let shown = tab_menu_texts(&mut h, "layers"); + let find = |shown: &[(String, f32, f32)], label: &str| { + shown.iter().find(|(t, ..)| t == label).map(|(_, x, within)| (*x, *within)).unwrap_or_else(|| panic!("{label} missing from {shown:?}")) + }; + let (panel_item, stock) = (find(&shown, "New Layer…").0, find(&shown, "Float Panel").0); + assert!((panel_item - stock).abs() < 0.5, "\"Float Panel\" starts at {stock}, the panel's \"New Layer…\" at {panel_item}"); + // With no document the Layers menu has no rows of its own, so nothing is indented. + h.app.run("file.close", json!({})).unwrap(); + h.frame(vec![]); + let shown = tab_menu_texts(&mut h, "layers"); + assert!(!shown.iter().any(|(t, ..)| t == "New Layer…"), "no Layers rows without a document"); + let within = find(&shown, "Float Panel").1; + assert!(within < 0.5, "\"Float Panel\" starts {within} into its text with no rows before it"); +} diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index ca838c03b9..4c268b088c 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -562,7 +562,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("select.key", json!({})).ok(); } // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Align to Glyph Bounds")), |ui| glyph_bounds_items(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Align to Glyph Bounds"), None), |ui| glyph_bounds_items(app, ui)); } /// The Align to Glyph Bounds submenu: Point Text and Area Text, each checked while Align and diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index eb4b882ad0..ef69ea8d87 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -638,7 +638,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), "br-list", true); } ui.separator(); - ui.menu_button(tl!("Open Brush Library"), |ui| library_panel::library_menu::(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Brush Library"), None), |ui| { + library_panel::library_menu::(app, ui) + }); if menu_item(ui, tl!("Save Brush Library…"), has_brushes, false) { save_library(app, targets); } diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 1cb759fa69..16eda1ea13 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1745,7 +1745,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let align = shared(app, |s| s.char_align); ui.add_enabled_ui(has, |ui| { // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Character Alignment")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Character Alignment"), None), |ui| { use vectorcraft_doc::CharAlign; for (label, a, key) in [ (tl!("Roman Baseline"), CharAlign::RomanBaseline, "romanBaseline"), @@ -1803,10 +1803,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.prefs.show_indic_options { let digits = shared(app, |s| s.digits); ui.add_enabled_ui(has, |ui| { - ui.menu_button(format!(" {}", tl!("Digits")), |ui| widgets::menu_scroll(ui, |ui| digits_items(app, ui, digits))); + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Digits"), None), |ui| { + widgets::menu_scroll(ui, |ui| digits_items(app, ui, digits)) + }); }); ui.add_enabled_ui(has, |ui| { - ui.menu_button(format!(" {}", tl!("Character Direction")), |ui| char_direction_items(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Character Direction"), None), |ui| char_direction_items(app, ui)); }); // A mixed selection is unchecked; choosing it enables kashidas for the whole range. let kashidas = shared(app, |s| s.kashidas) == Some(true); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c868f0e2c7..c0c2808a29 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -307,7 +307,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_enabled_ui(set.view == View::Box, |ui| { - ui.menu_button(format!(" {}", tl!("Box Channel")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Box Channel"), None), |ui| { for ch in Channel::ALL { if menu_item(ui, ch.name(), true, ch == set.channel) { command(app, &json!({ "channel": ch.id() })).ok(); @@ -339,7 +339,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { command(app, &json!({ "harmony": !set.harmony })).ok(); } ui.add_enabled_ui(set.view == View::Wheel, |ui| { - ui.menu_button(format!(" {}", tl!("Harmony Rule")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Harmony Rule"), None), |ui| { for rule in harmony_rules() { if menu_item(ui, rule.label(), true, rule == set.harmony_rule) { command(app, &json!({ "harmonyRule": rule.id() })).ok(); diff --git a/crates/ui-egui/src/panels/css_properties.rs b/crates/ui-egui/src/panels/css_properties.rs index eae559dff5..fb3e622d96 100644 --- a/crates/ui-egui/src/panels/css_properties.rs +++ b/crates/ui-egui/src/panels/css_properties.rs @@ -236,7 +236,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); let before = opts.clone(); - ui.menu_button(format!(" {}", crate::i18n::fmt(tl!("Units: {units}"), &[("units", opts.units.name())])), |ui| { + let units = crate::i18n::fmt(tl!("Units: {units}"), &[("units", opts.units.name())]); + ui.menu_button(widgets::check_row_text(ui, " ", &units, None), |ui| { for u in CssUnits::ALL { if menu_item(ui, u.name(), true, opts.units == u) { opts.units = u; diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 4650c88628..d5627b02e7 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -904,7 +904,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.run("ui.graphicStyleOptions", json!({ "name": n })).ok(); } - ui.menu_button(tl!("Open Graphic Style Library"), |ui| library_panel::library_menu::(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Graphic Style Library"), None), |ui| { + library_panel::library_menu::(app, ui) + }); if menu_item(ui, tl!("Save Graphic Style Library…"), has_doc, false) { run(app, "ui.saveGraphicStyleLibrary", json!({ "names": sel })); } diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 31f07c4929..2f7fbd6ea3 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -260,7 +260,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { pub(super) fn collect_for_export_menu(ui: &mut Ui, enabled: bool, mut run: impl FnMut(bool)) { ui.add_enabled_ui(enabled, |ui| { // English labels match the rest of this panel menu (and Object › Collect for Export). - ui.menu_button("Collect for Export", |ui| { + ui.menu_button(widgets::check_row_text(ui, "", "Collect for Export", None), |ui| { if widgets::menu_item(ui, "As Single Asset", true, false) { run(false); ui.close(); @@ -276,7 +276,7 @@ pub(super) fn collect_for_export_menu(ui: &mut Ui, enabled: bool, mut run: impl /// Save Selection › Save Selection…, Update Selection and Edit Selection…, enabled and run as in /// the Select menu, then the active document's saved selections: choosing one recalls it. fn save_selection_menu(app: &mut VectorcraftApp, ui: &mut Ui) { - ui.menu_button(format!(" {}", tl!("Save Selection")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Save Selection"), None), |ui| { widgets::menu_scroll(ui, |ui| { for (label, id) in [("Save Selection…", "select.save"), ("Update Selection", "select.update"), ("Edit Selection…", "select.editSaved")] { diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index 44f4b30ed5..c2d1f86394 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -657,7 +657,7 @@ impl Items<'_> { fn group_menu(&self, ui: &mut Ui, act: &mut Option, kind: ItemKind, key: &str) { let at = self.group_of(kind, key); let item = json!({ "kind": kind_param(kind), "item": key }); - ui.menu_button(format!(" {}", tl!("Move to Group")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Move to Group"), None), |ui| { widgets::menu_scroll(ui, |ui| { if menu_item(ui, "No Group", true, at.is_none()) { if at.is_some() { diff --git a/crates/ui-egui/src/panels/library_panel.rs b/crates/ui-egui/src/panels/library_panel.rs index 5690c9e518..5d40718ad0 100644 --- a/crates/ui-egui/src/panels/library_panel.rs +++ b/crates/ui-egui/src/panels/library_panel.rs @@ -837,7 +837,7 @@ pub(crate) fn library_items(ui: &mut Ui, libs: &[LibraryRef], checked: &dyn Fn(& } } for s in subs { - ui.menu_button(tl!(s), |ui| { + ui.menu_button(widgets::check_row_text(ui, "", tl!(s), None), |ui| { crate::widgets::menu_scroll(ui, |ui| { for l in libs.iter().filter(|l| l.submenu == Some(s)) { item(ui, l); diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 4cfcb27e89..2d15effcbe 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -362,7 +362,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut toggle = None; ui.add_enabled_ui(!sets.is_empty(), |ui| { // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Stylistic Sets")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Stylistic Sets"), None), |ui| { widgets::menu_scroll(ui, |ui| { for (set, flag, on) in &sets { if widgets::menu_item_name(ui, &set_label(set), true, *on) { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 99f11eec57..40878a07e2 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -852,7 +852,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let hang = style.as_ref().map(|(_, p)| p.burasagari); ui.add_enabled_ui(has, |ui| { // Indented like the items beside it (their check column). - ui.menu_button(format!(" {}", tl!("Burasagari")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Burasagari"), None), |ui| { use vectorcraft_doc::Burasagari; for (label, b, key) in [ (tl!("None"), Burasagari::None, "none"), @@ -874,7 +874,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { // checked, and none is when they differ. let kinsoku_type = shared_para(app, |p| p.kinsoku_type); ui.add_enabled_ui(has, |ui| { - ui.menu_button(format!(" {}", tl!("Kinsoku Shori Type")), |ui| { + ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Kinsoku Shori Type"), None), |ui| { for (label, t, key) in [ (tl!("Push In First"), KinsokuShoriType::PushInFirst, "pushInFirst"), (tl!("Push Out First"), KinsokuShoriType::PushOutFirst, "pushOutFirst"), diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 10e2236a60..4373f0e77a 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -665,7 +665,9 @@ fn artboard_size_controls_inner( ui.separator(); } for (cat, list) in &cats { - ui.menu_button(tl!(cat), |ui| { + // Beside the Fit rows, the categories start at their check column. + let label = if fits.is_some() { widgets::check_row_text(ui, "", tl!(cat), None) } else { tl!(cat).into() }; + ui.menu_button(label, |ui| { widgets::menu_scroll(ui, |ui| { for s in list { if widgets::menu_item_name(ui, crate::dialogs::preset_name(&s.name), true, same(s)) { diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index dc26c78550..8194171ab9 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -313,7 +313,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("ui.spotColors", json!({})).ok(); } ui.separator(); - ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Swatch Library"), None), |ui| { + library_panel::library_menu::(app, ui) + }); if menu_item(ui, tl!("Save Swatch Library…"), true, false) { app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok(); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e351e1a385..bf21980f22 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -625,7 +625,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.separator(); - ui.menu_button(tl!("Open Symbol Library"), |ui| library_panel::library_menu::(app, ui)); + ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Symbol Library"), None), |ui| { + library_panel::library_menu::(app, ui) + }); let has_symbols = app.session.active().is_some_and(|d| !d.doc.symbols.is_empty()); if menu_item(ui, tl!("Save Symbol Library…"), has_symbols, false) { save_library(app, sel.into_iter().collect()); diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index a09c634967..3439bff4bb 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -860,7 +860,8 @@ fn story_has_tabs(app: &VectorcraftApp) -> bool { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((_, para, _)) = current_para(app) else { - ui.add_enabled(false, egui::Button::new(tl!("Select text")).frame(false)); + let text = crate::widgets::check_row_text(ui, "", tl!("Select text"), Some(12.5)); + ui.add_enabled(false, egui::Button::new(text).frame_when_inactive(false)); snap_to_unit_item(ui); return; }; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b67df13c7f..a091b65200 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -31,7 +31,8 @@ pub use buttons::{ primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{ - button_width, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, primary_button_width, secondary_button_width, + button_width, check_column_job, check_row_text, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, + primary_button_width, secondary_button_width, }; #[cfg(test)] use chips::gradient_chip_colors; @@ -1058,6 +1059,44 @@ mod button_tests { }); out.textures_delta.clear(); } + + /// A menu row whose label runs right to left is laid out as the label alone: no check-column + /// space goes into it, and its words keep the order they have on their own (in "אבג PDF" the + /// Latin word is drawn left of the Hebrew one), on the first line and on a later line of a + /// label that starts in English. + #[test] + fn a_right_to_left_menu_label_is_laid_out_as_it_reads() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + for label in ["אבג PDF", "Title\nאבג PDF", "Title\u{2029}אבג PDF"] { + let layout = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Button); + let galley = layout(check_row_text(ui, "", label, None)); + let alone = layout(egui::RichText::new(label).font(egui::TextStyle::Button.resolve(ui.style())).into()); + assert!( + (galley.size().x - alone.size().x).abs() < 0.5, + "{label:?}: the row is {} wide, the label alone {}", + galley.size().x, + alone.size().x + ); + if label.contains('\u{2029}') { + // egui breaks rows only at a line feed; the width check above covers this label. + continue; + } + let x = |c: char| { + galley + .rows + .iter() + .flat_map(|r| r.row.glyphs.iter().map(move |g| (g.chr, r.pos.x + g.pos.x))) + .find(|(g, _)| *g == c) + .map(|(_, x)| x) + }; + let (latin, hebrew) = (x('P').unwrap(), x('א').unwrap()); + assert!(latin < hebrew, "{label:?}: PDF at {latin} is not left of the Hebrew word at {hebrew}"); + } + }); + out.textures_delta.clear(); + } } /// How the shared widgets look once laid out and painted: shapes of whole frames, measured. diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 0de8ded5e1..752d733db1 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -227,16 +227,65 @@ pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> /// [`menu_item_name`] that returns the row's response. fn menu_item_name_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { - let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; - ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) + let text = check_row_text(ui, if checked { "✓ " } else { " " }, label, Some(12.5)); + ui.add_enabled(enabled, egui::Button::new(text).frame_when_inactive(false)) } /// [`menu_item`] that shows `hint` under the pointer while the row is disabled, to say why it is /// gray. pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { - let label = tl!(label); - let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; - ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) - .on_disabled_hover_text(tl!(hint)) - .clicked() + let text = check_row_text(ui, if checked { "✓ " } else { " " }, tl!(label), Some(12.5)); + ui.add_enabled(enabled, egui::Button::new(text).frame_when_inactive(false)).on_disabled_hover_text(tl!(hint)).clicked() +} + +/// The width of the check-mark column of the in-app menus: room for the widest mark a row puts +/// before its label (a check mark and two spaces, or five spaces) in the button font. A font +/// without the check mark cannot draw one, so only the spaces count then. +fn check_column_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Button.resolve(ui.style()); + ui.ctx().fonts_mut(|f| { + let mark = if f.has_glyph(&font, '✓') { "✓ " } else { " " }; + let mut width = |text: &str| f.layout_no_wrap(text.to_string(), font.clone(), Color32::PLACEHOLDER).size().x; + width(mark).max(width(" ")) + }) +} + +/// Starts the text of a menu row for `label` with `mark` (a check mark, blank room for one, or +/// nothing) in `format`, and returns the leading space for the label after it. Every row's label +/// then starts at the end of the same check column, whatever the width of its mark, as in native +/// menus. A label with a line that runs right to left keeps its mark as plain text before it and +/// no leading space, so it is laid out in its own direction as before. +pub(crate) fn check_column_job(ui: &Ui, mark: &str, label: &str, format: &egui::TextFormat) -> (egui::text::LayoutJob, f32) { + let mut job = egui::text::LayoutJob::default(); + if !mark.is_empty() { + job.append(mark, 0.0, format.clone()); + } + if label.split(is_paragraph_separator).any(|line| vectorcraft_text::paragraph_is_rtl(line, None)) { + return (job, 0.0); + } + let mark_width = if mark.is_empty() { + 0.0 + } else { + ui.ctx().fonts_mut(|f| f.layout_no_wrap(mark.to_string(), format.font_id.clone(), Color32::PLACEHOLDER).size().x) + }; + (job, (check_column_width(ui) - mark_width).max(0.0)) +} + +/// Does `c` end a paragraph for the bidirectional algorithm (bidi class B: line feed, carriage +/// return, the information separators U+001C to U+001E, next line and the paragraph separator)? +fn is_paragraph_separator(c: char) -> bool { + matches!(c, '\n' | '\r' | '\u{1C}'..='\u{1E}' | '\u{85}' | '\u{2029}') +} + +/// A menu row's text: `mark`, then `label` at the end of the check column +/// ([`check_column_job`]), in the button font at `size` when one is given. +pub(crate) fn check_row_text(ui: &Ui, mark: &str, label: &str, size: Option) -> egui::WidgetText { + let mut font_id = egui::TextStyle::Button.resolve(ui.style()); + if let Some(size) = size { + font_id.size = size; + } + let format = egui::TextFormat { font_id, color: Color32::PLACEHOLDER, ..Default::default() }; + let (mut job, lead) = check_column_job(ui, mark, label, &format); + job.append(label, lead, format); + job.into() } diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index c409b6b71a..538318f21e 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -454,11 +454,8 @@ pub fn popup(app: &mut VectorcraftApp, ui: &mut egui::Ui) { crate::menus::Item::Cmd(label, id, p) => { // As the Window menu draws it: custom workspace names (and Reset ) as they are. let label = crate::menus::display_label(app, id, label); - let text = match crate::menus::checked(app, id, &p) { - Some(true) => format!("✓ {label}"), - Some(false) => format!(" {label}"), - None => format!(" {label}"), - }; + let mark = if crate::menus::checked(app, id, &p) == Some(true) { "✓ " } else { " " }; + let text = crate::widgets::check_row_text(ui, mark, &label, None); if ui.add(egui::Button::new(text).min_size(egui::vec2(220.0, 0.0))).clicked() { clicked = Some((id, if p.is_null() { json!({}) } else { p })); ui.close(); From f2c3651a10cce6c5ef483765859813c904bbea9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:11:01 -0800 Subject: [PATCH 003/533] Menus: measure the check column once per frame Every menu row measured the check column and its own mark again, so a menu with one row per font family repeated the same layouts on every frame. The widths are now kept for the rest of the frame, per font. A tab's context menu records in the frame it draws the panel's rows whether they use the column. The stock items read that record only in the same frame, so a later docking menu without the panel's rows keeps plain labels. The files that already import `widgets` call the helper as `widgets::check_row_text`. --- crates/ui-egui/src/canvas/task_bar.rs | 2 +- crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/dialogs/recolor.rs | 2 +- crates/ui-egui/src/panel_docking.rs | 9 +++-- crates/ui-egui/src/panel_docking/tests.rs | 32 ++++++++++++++++ crates/ui-egui/src/panels/align.rs | 2 +- crates/ui-egui/src/panels/brushes.rs | 4 +- crates/ui-egui/src/panels/character.rs | 6 +-- crates/ui-egui/src/panels/color_wheel.rs | 4 +- crates/ui-egui/src/panels/graphic_styles.rs | 2 +- crates/ui-egui/src/panels/layers/controls.rs | 2 +- crates/ui-egui/src/panels/libraries.rs | 2 +- crates/ui-egui/src/panels/opentype.rs | 2 +- crates/ui-egui/src/panels/paragraph.rs | 4 +- crates/ui-egui/src/panels/swatches/actions.rs | 4 +- crates/ui-egui/src/panels/symbols.rs | 4 +- crates/ui-egui/src/panels/tabs.rs | 2 +- crates/ui-egui/src/widgets/buttons.rs | 37 ++++++++++++++----- crates/ui-egui/src/workspaces.rs | 2 +- 19 files changed, 86 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 952e1831fa..62456b9ecf 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -526,7 +526,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { // The actions and chips the bar offers for this selection or tool, each // checked while it shows, which turns it on or off; then Reset Bar // Actions, which shows every action again. - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Bar Actions"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Bar Actions"), None), |ui| { ui.set_min_width(170.0); for (label, action, shown) in task_bar_offered(ui.ctx()) { let Some(action) = action else { continue }; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 6ed79d9719..f87b1d0d54 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -199,7 +199,7 @@ fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { menus::Item::Cmd(label, id, p) => { let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; let label = crate::i18n::t_id(id, label); - let text = crate::widgets::check_row_text(ui, if checked == Some(true) { "✓ " } else { " " }, label, None); + let text = widgets::check_row_text(ui, if checked == Some(true) { "✓ " } else { " " }, label, None); if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { clicked = Some((id, if p.is_null() { json!({}) } else { p })); ui.close(); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 403468f2ed..a033500632 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2615,7 +2615,7 @@ fn color_menu(ui: &mut Ui, rows: &[Value], i: usize, base: Option) -> Opt } if let Some(c) = rows.get(i).and_then(to_color) { // Indented like the items beside it (their check column). - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Select Shade"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Select Shade"), None), |ui| { if let Some(sv) = shade_grid(ui, &c) { choice = Some(MenuChoice::Shade(i, sv)); } diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 6e35ca8388..0b954bca35 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1646,13 +1646,16 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { let before = ui.cursor().min; // A panel can draw no rows, as Layers does with no document open. let drew = crate::panels::panel_menu_items(self.app, ui, id) && ui.cursor().min != before; - ui.data_mut(|d| d.insert_temp(check_column_key(ui), drew)); + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(check_column_key(ui), (pass, drew))); } /// The stock tab-menu items (Float Panel, Move Panel To, the group items) after a panel's own - /// menu items start their labels at the same check column. Other docking menus keep plain text. + /// menu items start their labels at the same check column. Other docking menus keep plain text, + /// and so does a menu whose panel items were not drawn in this pass. fn action_label(&mut self, ui: &egui::Ui, logical: &str, _font: &egui::FontId, _color: egui::Color32) -> egui::WidgetText { - if ui.data(|d| d.get_temp::(check_column_key(ui))).unwrap_or(false) { + let pass = ui.ctx().cumulative_pass_nr(); + if ui.data(|d| d.get_temp::<(u64, bool)>(check_column_key(ui))) == Some((pass, true)) { crate::widgets::check_row_text(ui, "", logical, None) } else { logical.into() diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index d5029f9762..249e1df66d 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -2096,3 +2096,35 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() { let within = find(&shown, "Float Panel").1; assert!(within < 0.5, "\"Float Panel\" starts {within} into its text with no rows before it"); } + +/// A docking menu drawn in a later pass without the panel's rows, in the same place as a tab menu +/// that had them, starts its labels at the edge. +#[test] +fn a_later_docking_menu_without_panel_rows_is_not_indented() { + use craft_ui::docking::DockContent; + let mut h = Harness::new(); + crate::theme::install_fonts(&h.ctx); + h.frame(vec![]); + let layout = layout_of(&h.app.ui); + // Where "Float Panel" starts within its text, after the panel's rows (`with_rows`) or alone. + let mut starts = |with_rows: bool| { + let mut start = None; + let app = &mut h.app; + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }, |ui| { + let mut content = PanelContent { app, layout: &layout }; + if with_rows { + content.panel_menu(ui, &"layers".to_string()); + } + let font = egui::TextStyle::Button.resolve(ui.style()); + let text = content.action_label(ui, "Float Panel", &font, egui::Color32::PLACEHOLDER); + let galley = text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Button); + start = galley.rows.first().and_then(|r| r.row.glyphs.first()).map(|g| g.pos.x); + }); + out.textures_delta.clear(); + start.expect("\"Float Panel\" is laid out") + }; + let after_rows = starts(true); + assert!(after_rows > 0.5, "after the panel's rows \"Float Panel\" starts at the check column, not at {after_rows}"); + let alone = starts(false); + assert!(alone < 0.5, "a later menu without the panel's rows indents \"Float Panel\" by {alone}"); +} diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index 4c268b088c..daab669f7b 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -562,7 +562,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("select.key", json!({})).ok(); } // Indented like the items beside it (their check column). - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Align to Glyph Bounds"), None), |ui| glyph_bounds_items(app, ui)); + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Align to Glyph Bounds"), None), |ui| glyph_bounds_items(app, ui)); } /// The Align to Glyph Bounds submenu: Point Text and Area Text, each checked while Align and diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index ef69ea8d87..ce4d1e1b2e 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -638,9 +638,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), "br-list", true); } ui.separator(); - ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Brush Library"), None), |ui| { - library_panel::library_menu::(app, ui) - }); + ui.menu_button(widgets::check_row_text(ui, "", tl!("Open Brush Library"), None), |ui| library_panel::library_menu::(app, ui)); if menu_item(ui, tl!("Save Brush Library…"), has_brushes, false) { save_library(app, targets); } diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 16eda1ea13..622bf60c18 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -1745,7 +1745,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let align = shared(app, |s| s.char_align); ui.add_enabled_ui(has, |ui| { // Indented like the items beside it (their check column). - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Character Alignment"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Character Alignment"), None), |ui| { use vectorcraft_doc::CharAlign; for (label, a, key) in [ (tl!("Roman Baseline"), CharAlign::RomanBaseline, "romanBaseline"), @@ -1803,12 +1803,12 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if app.session.prefs.show_indic_options { let digits = shared(app, |s| s.digits); ui.add_enabled_ui(has, |ui| { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Digits"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Digits"), None), |ui| { widgets::menu_scroll(ui, |ui| digits_items(app, ui, digits)) }); }); ui.add_enabled_ui(has, |ui| { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Character Direction"), None), |ui| char_direction_items(app, ui)); + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Character Direction"), None), |ui| char_direction_items(app, ui)); }); // A mixed selection is unchecked; choosing it enables kashidas for the whole range. let kashidas = shared(app, |s| s.kashidas) == Some(true); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c0c2808a29..ce65bd2a55 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -307,7 +307,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_enabled_ui(set.view == View::Box, |ui| { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Box Channel"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Box Channel"), None), |ui| { for ch in Channel::ALL { if menu_item(ui, ch.name(), true, ch == set.channel) { command(app, &json!({ "channel": ch.id() })).ok(); @@ -339,7 +339,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { command(app, &json!({ "harmony": !set.harmony })).ok(); } ui.add_enabled_ui(set.view == View::Wheel, |ui| { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Harmony Rule"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Harmony Rule"), None), |ui| { for rule in harmony_rules() { if menu_item(ui, rule.label(), true, rule == set.harmony_rule) { command(app, &json!({ "harmonyRule": rule.id() })).ok(); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d5627b02e7..40f34e6a82 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -904,7 +904,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { app.run("ui.graphicStyleOptions", json!({ "name": n })).ok(); } - ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Graphic Style Library"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, "", tl!("Open Graphic Style Library"), None), |ui| { library_panel::library_menu::(app, ui) }); if menu_item(ui, tl!("Save Graphic Style Library…"), has_doc, false) { diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 2f7fbd6ea3..59c4d2fa19 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -276,7 +276,7 @@ pub(super) fn collect_for_export_menu(ui: &mut Ui, enabled: bool, mut run: impl /// Save Selection › Save Selection…, Update Selection and Edit Selection…, enabled and run as in /// the Select menu, then the active document's saved selections: choosing one recalls it. fn save_selection_menu(app: &mut VectorcraftApp, ui: &mut Ui) { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Save Selection"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Save Selection"), None), |ui| { widgets::menu_scroll(ui, |ui| { for (label, id) in [("Save Selection…", "select.save"), ("Update Selection", "select.update"), ("Edit Selection…", "select.editSaved")] { diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index c2d1f86394..b4e83cee61 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -657,7 +657,7 @@ impl Items<'_> { fn group_menu(&self, ui: &mut Ui, act: &mut Option, kind: ItemKind, key: &str) { let at = self.group_of(kind, key); let item = json!({ "kind": kind_param(kind), "item": key }); - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Move to Group"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Move to Group"), None), |ui| { widgets::menu_scroll(ui, |ui| { if menu_item(ui, "No Group", true, at.is_none()) { if at.is_some() { diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 2d15effcbe..745f77e8ad 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -362,7 +362,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut toggle = None; ui.add_enabled_ui(!sets.is_empty(), |ui| { // Indented like the items beside it (their check column). - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Stylistic Sets"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Stylistic Sets"), None), |ui| { widgets::menu_scroll(ui, |ui| { for (set, flag, on) in &sets { if widgets::menu_item_name(ui, &set_label(set), true, *on) { diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 40878a07e2..67229fbd47 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -852,7 +852,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let hang = style.as_ref().map(|(_, p)| p.burasagari); ui.add_enabled_ui(has, |ui| { // Indented like the items beside it (their check column). - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Burasagari"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Burasagari"), None), |ui| { use vectorcraft_doc::Burasagari; for (label, b, key) in [ (tl!("None"), Burasagari::None, "none"), @@ -874,7 +874,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { // checked, and none is when they differ. let kinsoku_type = shared_para(app, |p| p.kinsoku_type); ui.add_enabled_ui(has, |ui| { - ui.menu_button(crate::widgets::check_row_text(ui, " ", tl!("Kinsoku Shori Type"), None), |ui| { + ui.menu_button(widgets::check_row_text(ui, " ", tl!("Kinsoku Shori Type"), None), |ui| { for (label, t, key) in [ (tl!("Push In First"), KinsokuShoriType::PushInFirst, "pushInFirst"), (tl!("Push Out First"), KinsokuShoriType::PushOutFirst, "pushOutFirst"), diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 8194171ab9..87390b76a3 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -313,9 +313,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { app.run("ui.spotColors", json!({})).ok(); } ui.separator(); - ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Swatch Library"), None), |ui| { - library_panel::library_menu::(app, ui) - }); + ui.menu_button(widgets::check_row_text(ui, "", tl!("Open Swatch Library"), None), |ui| library_panel::library_menu::(app, ui)); if menu_item(ui, tl!("Save Swatch Library…"), true, false) { app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok(); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index bf21980f22..bacaa95553 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -625,9 +625,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.separator(); - ui.menu_button(crate::widgets::check_row_text(ui, "", tl!("Open Symbol Library"), None), |ui| { - library_panel::library_menu::(app, ui) - }); + ui.menu_button(widgets::check_row_text(ui, "", tl!("Open Symbol Library"), None), |ui| library_panel::library_menu::(app, ui)); let has_symbols = app.session.active().is_some_and(|d| !d.doc.symbols.is_empty()); if menu_item(ui, tl!("Save Symbol Library…"), has_symbols, false) { save_library(app, sel.into_iter().collect()); diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 3439bff4bb..3b9ee285d8 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -860,7 +860,7 @@ fn story_has_tabs(app: &VectorcraftApp) -> bool { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((_, para, _)) = current_para(app) else { - let text = crate::widgets::check_row_text(ui, "", tl!("Select text"), Some(12.5)); + let text = widgets::check_row_text(ui, "", tl!("Select text"), Some(12.5)); ui.add_enabled(false, egui::Button::new(text).frame_when_inactive(false)); snap_to_unit_item(ui); return; diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 752d733db1..e9048b8143 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -243,13 +243,36 @@ pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hi /// without the check mark cannot draw one, so only the spaces count then. fn check_column_width(ui: &Ui) -> f32 { let font = egui::TextStyle::Button.resolve(ui.style()); - ui.ctx().fonts_mut(|f| { - let mark = if f.has_glyph(&font, '✓') { "✓ " } else { " " }; - let mut width = |text: &str| f.layout_no_wrap(text.to_string(), font.clone(), Color32::PLACEHOLDER).size().x; - width(mark).max(width(" ")) + once_per_pass(ui, egui::Id::unique(("menu-check-column-width", &font)), || { + ui.ctx().fonts_mut(|f| { + let mark = if f.has_glyph(&font, '✓') { "✓ " } else { " " }; + let mut width = |text: &str| f.layout_no_wrap(text.to_string(), font.clone(), Color32::PLACEHOLDER).size().x; + width(mark).max(width(" ")) + }) }) } +/// The width of a row's `mark` in `font`. +fn mark_width(ui: &Ui, mark: &str, font: &egui::FontId) -> f32 { + once_per_pass(ui, egui::Id::unique(("menu-check-mark-width", mark, font)), || { + ui.ctx().fonts_mut(|f| f.layout_no_wrap(mark.to_string(), font.clone(), Color32::PLACEHOLDER).size().x) + }) +} + +/// `measure()`, worked out on the first call of a pass and kept under `id` for the rest of it: +/// every row of a menu (one per font family in Type › Font) asks for the same widths. +fn once_per_pass(ui: &Ui, id: egui::Id, measure: impl FnOnce() -> f32) -> f32 { + let pass = ui.ctx().cumulative_pass_nr(); + if let Some((at, width)) = ui.data(|d| d.get_temp::<(u64, f32)>(id)) + && at == pass + { + return width; + } + let width = measure(); + ui.data_mut(|d| d.insert_temp(id, (pass, width))); + width +} + /// Starts the text of a menu row for `label` with `mark` (a check mark, blank room for one, or /// nothing) in `format`, and returns the leading space for the label after it. Every row's label /// then starts at the end of the same check column, whatever the width of its mark, as in native @@ -263,11 +286,7 @@ pub(crate) fn check_column_job(ui: &Ui, mark: &str, label: &str, format: &egui:: if label.split(is_paragraph_separator).any(|line| vectorcraft_text::paragraph_is_rtl(line, None)) { return (job, 0.0); } - let mark_width = if mark.is_empty() { - 0.0 - } else { - ui.ctx().fonts_mut(|f| f.layout_no_wrap(mark.to_string(), format.font_id.clone(), Color32::PLACEHOLDER).size().x) - }; + let mark_width = if mark.is_empty() { 0.0 } else { mark_width(ui, mark, &format.font_id) }; (job, (check_column_width(ui) - mark_width).max(0.0)) } diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 538318f21e..53b562e106 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -455,7 +455,7 @@ pub fn popup(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // As the Window menu draws it: custom workspace names (and Reset ) as they are. let label = crate::menus::display_label(app, id, label); let mark = if crate::menus::checked(app, id, &p) == Some(true) { "✓ " } else { " " }; - let text = crate::widgets::check_row_text(ui, mark, &label, None); + let text = widgets::check_row_text(ui, mark, &label, None); if ui.add(egui::Button::new(text).min_size(egui::vec2(220.0, 0.0))).clicked() { clicked = Some((id, if p.is_null() { json!({}) } else { p })); ui.close(); From 92cc8c77e5e50cb4f0ad37a88eb31c518f5c1eed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:19:32 -0800 Subject: [PATCH 004/533] Scripts: layers, groups, compound paths and artboards for scripts A document now has layers, activeLayer, groupItems, compoundPathItems and artboards, and every page item has its layer. - Layers and sublayers: add, remove, removeAll, getByName, index, name, visibility, lock, print, preview, dim images, opacity, color, stacking, move and zOrder, each through the existing layer and node commands. - Groups: clipped makes or releases the clipping mask, and groupItems.add() makes an empty group through the new narrow command object.newGroup. A document's groupItems and compoundPathItems hold every group or compound path at any depth; a layer's or group's hold only the ones directly in it. - Artboards: add, insert, remove, getByName, rectangles, names, ruler origin, pixel aspect ratio and display options, and the active artboard. A new artboard gets an "Artboard N" name no other artboard has. setActiveArtboardIndex adds no undo step; script.run's report lists the change in activeArtboards and the app shows it. - Bad values throw before any command runs, and a value a layer or artboard already has runs no command. Handles to a deleted layer or artboard throw Stale layer or Stale artboard. Docs: docs/mcp.md, docs/gaps.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/arrange.rs | 31 + crates/engine/src/cmd/object/commands.rs | 11 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/script/dom.rs | 56 +- crates/engine/src/script/dom/layers.rs | 1339 +++++++++++++++++ crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests/script_dom.rs | 337 ++++- .../tests/it/script_host_vs_scriptcheck.rs | 56 +- crates/ui-egui/src/script_runs.rs | 17 + crates/ui-egui/src/tests/script_run.rs | 12 + docs/gaps.md | 6 +- docs/mcp.md | 53 +- docs/target-app-parity.md | 3 +- 13 files changed, 1883 insertions(+), 42 deletions(-) create mode 100644 crates/engine/src/script/dom/layers.rs diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index a0f292fecf..bd993ec1ec 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,6 +105,37 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } +/// `object.newGroup`: an empty group in a layer or a group (default: the current layer), on top +/// of its contents or at `index` (0 = bottom). The selection stays as it is. +pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.newGroup"; + let st = s.doc()?; + let parent = match p.get("parent") { + None | Some(Value::Null) => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?, + Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?), + }; + let index = match p.get("index") { + None | Some(Value::Null) => usize::MAX, + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?, + }; + let d = &st.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + let gid = s.edit("Group", |d, _| { + let gid = d.alloc_id(); + let clips = d.node(parent).is_some_and(Node::clips); + let index = if clips { index.max(1) } else { index }; + d.insert(Some(parent), index, Node::group(gid, Vec::new()))?; + Ok(gid) + })?; + Ok(json!({ "id": gid.0 })) +} + /// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was. pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result { if ids.is_empty() { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..dab3a0378c 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -1,5 +1,5 @@ use super::align::{align, can_distribute, distribute, distribute_spacing}; -use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all}; +use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all}; use super::bounds::set_bounds; use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release}; use super::pixelgrid::set_pixel_aligned; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_selection, group ), + cmd!( + "object.newGroup", + "Group", + [], + None, + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom; default: on top)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", + has_doc, + new_group + ), cmd!( "object.ungroup", "Ungroup", diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..d7be5411ae 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -334,6 +334,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.mesh.movePoints", "object.mesh.setPointColor", "object.move", + "object.newGroup", "object.nudge", "object.objectsOnPath.attach", "object.objectsOnPath.detach", diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..7bfecbb264 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +pub(super) mod layers; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,9 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + /// The documents whose active artboard `setActiveArtboardIndex` changed: each one's uid and + /// the artboard's id. + pub(super) active_artboards: RefCell>, } impl State { @@ -151,7 +156,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document, layer or page item `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -162,7 +167,10 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "Layer" => { + layers::layer_of(&h, arg(&a, 0))?; + } + c if c == "PageItem" || ITEM_CLASSES.contains(&c) => { item_of(&h, arg(&a, 0))?; } _ => {} @@ -1122,22 +1130,34 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; let n = with_doc(h, doc, |_, st| page_items(h, st).len()); Ok(num(float(n as u64))) } fn items_typename(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(text("PageItems")) } fn items_parent(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) } fn items_at(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; @@ -1145,6 +1165,9 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_by_name(h, a); + } let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { @@ -1169,6 +1192,9 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); @@ -1644,19 +1670,6 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -fn layer_name(h: &Host, a: &[Data]) -> Answer { - let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); - with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) -} - -fn layer_typename(h: &Host, a: &[Data]) -> Answer { - layer_name(h, a)?; - Ok(text("Layer")) -} - fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } @@ -1752,11 +1765,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), ]); - document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] - .into_iter() - .map(|m| later(l, "Document", m)), - ); + document.extend(["pathItems", "textFrames", "swatches", "symbols", "views", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m))); + document.extend(layers::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1795,12 +1805,12 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("remove", method(l, item_remove)), ("zOrder", method(l, item_z_order)), ]); + page_item.extend(layers::page_item_members(l)); page_item.extend( [ "artworkKnockout", "blendingMode", "isIsolated", - "layer", "pixelAligned", "sliced", "tags", @@ -1820,8 +1830,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), layers::members(c, l), None))); + classes.extend(layers::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs new file mode 100644 index 0000000000..a6b165fbef --- /dev/null +++ b/crates/engine/src/script/dom/layers.rs @@ -0,0 +1,1339 @@ +//! Layers, groups, compound paths and artboards in the script object model, as the help pages +//! , +//! , +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A layer is named by its id and an artboard by its artboard id, so a handle keeps naming the same +//! one after others are added, moved or removed, and throws once it is gone. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `layers` lists layers top first, as the Layers panel shows them; `groupItems`, +//! `compoundPathItems` and a layer's or group's `pageItems` list art in paint order, bottom first, +//! as `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or +//! compound path at any depth; a layer's or group's hold the ones directly in it. +//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes +//! a sublayer on top of that layer's contents. The new layer becomes the current one. +//! - `locked` true means the layer is locked. +//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or +//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it. +//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255. +//! - `CompoundPathItems.add()` throws: a compound path holds at least one path. +//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a +//! document, the limit `Documents.add` uses. Artboard names are unique: a name another artboard +//! has throws. +//! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global +//! rulers, setting it moves the document's zero point. +//! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report +//! lists it in `activeArtboards` for the app to show. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{ + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, doc_of, + doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, number, on_doc, + page_items, placement_of, property, set_selection, text, typename, whole, with_doc, +}; +use crate::script::{Host, Link}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error for a layer that was deleted, or that came from an earlier run. +pub const STALE_LAYER: &str = "Stale layer"; +/// The error for an artboard that was deleted, or that came from an earlier run. +pub const STALE_ARTBOARD: &str = "Stale artboard"; +/// The longest name a layer takes, in characters, as Layer Options keeps it. +pub const MAX_LAYER_NAME: usize = 512; + +type Result = std::result::Result; + +/// What a collection of art lists. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + /// Every page item. + Any, + /// Groups (`GroupItem`). + Group, + /// Compound paths (`CompoundPathItem`). + Compound, +} + +impl Kind { + fn class(self) -> &'static str { + match self { + Kind::Any => "PageItems", + Kind::Group => "GroupItems", + Kind::Compound => "CompoundPathItems", + } + } + + fn holds(self, n: &crate::doc::Node) -> bool { + match self { + Kind::Any => typename(n).is_some(), + Kind::Group => typename(n) == Some("GroupItem"), + Kind::Compound => typename(n) == Some("CompoundPathItem"), + } + } +} + +fn type_error(what: &str) -> HostError { + HostError::Type(format!("this is not a {what}")) +} + +/// The id a command's result gives under `key`. +fn result_id(d: &Data, key: &str) -> Option { + let Data::Object(o) = d else { return None }; + match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { + Some(Data::Number(n)) => whole(*n), + _ => None, + } +} + +// ---- Layer ---- + +/// The layer `d` names, which must still be a layer of its document. +pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> { + let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(type_error("Layer")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer)); + if !ok { + return Err(HostError::Error(STALE_LAYER.into())); + } + Ok((doc, id)) +} + +fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { + layer_of(h, arg(a, 0)) +} + +fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("Layer", &[float(h.run), float(uid), high, low]) +} + +/// Reads the layer `this` names with `f`. +fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let (doc, id) = this_layer(h, a)?; + with_doc(h, doc, |_, st| match st.doc.node(id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_LAYER.into())), + }) +} + +/// Runs `id` with `params` and the layer's id on its document, unless `unchanged` says the layer +/// already has what they set. +fn set_layer(h: &Host, a: &[Data], command_id: &str, unchanged: impl FnOnce(&crate::doc::Node) -> bool, params: Value) -> Answer { + let (doc, id) = this_layer(h, a)?; + let same = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(unchanged)); + if !same { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id.0])); + } + on_doc(h, doc.uid, true, |h| command(h, command_id, &p))?; + } + Ok(Data::Undefined) +} + +fn layer_flags(n: &crate::doc::Node) -> (bool, bool, Option, crate::doc::LayerColor) { + match &n.kind { + NodeKind::Layer { printable, preview, dim_images, color, .. } => (*printable, *preview, *dim_images, *color), + _ => (true, true, None, crate::doc::LayerColor::Preset(0)), + } +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +fn layer_set_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + if name.trim().is_empty() { + return Err(HostError::Range("a layer's name cannot be empty".into())); + } + if name.chars().count() > MAX_LAYER_NAME { + return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); + } + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), json!({"name": name})) +} + +fn layer_visible(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.visible))) +} + +fn layer_set_visible(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "visible")?; + set_layer(h, a, "layer.setProps", |n| n.visible == v, json!({"visible": v})) +} + +fn layer_locked(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn layer_set_locked(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "locked")?; + set_layer(h, a, "layer.setProps", |n| n.locked == v, json!({"locked": v})) +} + +fn layer_printable(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).0))) +} + +fn layer_set_printable(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "printable")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).0 == v, json!({"printable": v})) +} + +fn layer_preview(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).1))) +} + +fn layer_set_preview(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "preview")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).1 == v, json!({"preview": v})) +} + +fn layer_dim(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).2.is_some()))) +} + +fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "dimPlacedImages")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).2.is_some() == v, json!({"dimImages": v})) +} + +fn layer_opacity(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) +} + +fn layer_color(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| { + let [r, g, b] = layer_flags(n).3.rgb(); + let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v))); + Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)])) + }) +} + +/// `color = {red, green, blue}`: each a whole number from 0 to 255. +fn layer_set_color(h: &Host, a: &[Data]) -> Answer { + let Data::Object(o) = arg(a, 1) else { return Err(HostError::Type("color must be an object with red, green and blue".into())) }; + let mut rgb = [0u8; 3]; + for (slot, key) in rgb.iter_mut().zip(["red", "green", "blue"]) { + let v = o.iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap_or(&Data::Undefined); + let n = number(v, &format!("color.{key}"))?; + if n.fract() != 0.0 || !(0.0..=255.0).contains(&n) { + return Err(HostError::Range(format!("color.{key} must be a whole number from 0 to 255"))); + } + *slot = u8::try_from(whole(n).unwrap_or(0)).unwrap_or(0); + } + let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); + set_layer(h, a, "layer.setProps", |n| layer_flags(n).3.rgb() == rgb, json!({"color": hex})) +} + +fn layer_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(with_doc(h, doc, |_, st| match st.doc.parent_of(id) { + Some(p) => layer_ref(h, st.uid, p), + None => doc_ref(h, st.uid), + })) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + this_layer(h, a)?; + Ok(text("Layer")) +} + +/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is +/// not counted. +fn layer_z_position(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let at = with_doc(h, doc, |_, st| { + let list = layer_list(&st.doc, st.doc.parent_of(id)); + list.iter().position(|l| *l == id).map(|i| list.len() - i) + }); + at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) +} + +fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) +} + +/// `hasSelectedArtwork = false` deselects the layer's art; `true` adds its visible, unlocked art +/// to the selection. +fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "hasSelectedArtwork")?; + let (doc, id) = this_layer(h, a)?; + let ids = with_doc(h, doc, |_, st| { + let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); + let mut ids: Vec = st.selection.objects.clone(); + if on { + let locks = st.doc.locked_artboards(); + let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); + let mut have: std::collections::HashSet = ids.iter().copied().collect(); + for o in art { + if ids.len() > MAX_LISTED { + break; + } + if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + have.insert(o); + ids.push(o); + } + } + } else { + ids.retain(|o| !inside(o)); + } + ids + }); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); + } + set_selection(h, doc, ids) +} + +fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.isolation == Some(id)))) +} + +fn layer_remove(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": [id.0]})))?; + Ok(Data::Undefined) +} + +/// The layers of `parent` (`None`: the top level), without its ruler guides and art. +fn art_count(d: &Document, parent: Option) -> usize { + d.children(parent).map_or(0, |c| crate::doc::Node::guide_run_start(c)) +} + +/// Moves the layer `id` to `index` of `parent` with `node.move`, unless it is there already. +fn put_layer(h: &Host, doc: Doc, id: NodeId, parent: Option, index: usize) -> Result<()> { + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == parent && i == index) { + return Ok(()); + } + let parent = parent.map_or(Value::Null, |p| json!(p.0)); + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": parent, "index": index})))?; + Ok(()) +} + +/// `zOrder(method)`: the layer goes to the top or the bottom of the layers beside it, or one step. +fn layer_z_order(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let method = match arg(a, 1) { + Data::String(s) => s.as_str(), + _ => "", + }; + let (parent, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + let (parent, i, _) = d.position(id).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let count = art_count(d, parent); + let last = count.saturating_sub(1); + // One step passes the next layer beside it, and the art between them. + let layer_at = |j: &usize| d.children(parent).and_then(|c| c.get(*j)).is_some_and(|n| n.is_layer()); + let to = match method { + "ZOrderMethod.BRINGTOFRONT" => last, + "ZOrderMethod.BRINGFORWARD" => (i + 1..count).find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDBACKWARD" => (floor.min(i)..i).rev().find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDTOBACK" => floor.min(i), + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + Ok((parent, to)) + })?; + put_layer(h, doc, id, parent, index)?; + Ok(Data::Undefined) +} + +/// `move(relativeObject, insertionLocation?)`: the layer goes into another layer (on top of its +/// contents, or at the bottom with `PLACEATEND`), to the top level of a document, or directly +/// above or below another layer. +fn layer_move(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let how = placement_of(arg(a, 2))?; + let target = arg(a, 1); + let parent = if let Some(handle) = handle_of(target, "Document") { + let [run, uid] = handle.as_slice() else { return Err(type_error("Document")) }; + let to = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if matches!(how, Placement::Above | Placement::Below) { + return Err(HostError::Error("a layer goes above or below another layer, not a document".into())); + } + None + } else if handle_of(target, "Layer").is_some() { + let (to, t) = layer_of(h, target)?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + Some(t) + } else if matches!(target, Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } else { + return Err(HostError::Type("a layer's relative object must be a layer or a document".into())); + }; + let (into, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + if let Some(t) = parent + && d.ancestry(t).is_some_and(|a| a.contains(&id)) + && !(t == id && matches!(how, Placement::Above | Placement::Below)) + { + return Err(HostError::Error("a layer cannot go into itself".into())); + } + let (into, beside) = match (how, parent) { + (Placement::Above | Placement::Below, Some(t)) => (d.parent_of(t), Some(t)), + (_, p) => (p, None), + }; + if into.is_some_and(|p| !editable(d, p)) { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + let from = d.position(id); + let here = |p: Option| from.is_some_and(|(q, ..)| q == p); + let count = art_count(d, into) - usize::from(here(into)); + let floor = usize::from(into.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips) && count > 0); + let index = match (how, beside) { + (Placement::Above | Placement::Below, Some(b)) => { + if b == id { + return Ok((into, from.map_or(0, |(_, i, _)| i))); + } + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + if let Some((_, j, _)) = from + && here(into) + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (Placement::Bottom, _) => 0, + _ => count, + }; + Ok((into, index.max(floor))) + })?; + put_layer(h, doc, id, into, index)?; + Ok(arg(a, 0).clone()) +} + +// ---- Layers ---- + +/// The document and the layer (`None`: the top level) a `Layers` object lists. +fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low]))?; + Ok((doc, Some(id))) + } + _ => Err(type_error("Layers")), + } +} + +/// The layers of `parent` (`None`: the top level), top first. +fn layer_list(d: &Document, parent: Option) -> Vec { + let list = match parent { + None => Some(&d.layers), + Some(p) => d.children(Some(p)), + }; + list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() +} + +fn layers_of(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let [high, low] = id_parts(id); + Ok(host_ref("Layers", &[float(h.run), float(doc.uid), high, low])) +} + +fn layers_length(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64))) +} + +fn layers_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(parent.map_or_else(|| doc_ref(h, doc.uid), |p| layer_ref(h, doc.uid, p))) +} + +fn layers_typename(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("Layers")) +} + +fn layers_at(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) +} + +fn layers_by_name(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = layer_list(&st.doc, parent); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn layers_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => layers_by_name(h, a), + Data::Number(_) => match layers_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `layers.add()`: a new layer above every top-level layer, or a sublayer on top of the layer's +/// contents. → the new layer, which is the current one. +fn layers_add(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Some(p) = parent { + let ok = with_doc(h, doc, |_, st| editable(&st.doc, p)); + if !ok { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + } + let r = on_doc(h, doc.uid, true, |h| match parent { + None => command(h, "layer.new", &json!({"top": true})), + Some(p) => command(h, "layer.newSublayer", &json!({"parent": p.0})), + })?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; + Ok(layer_ref(h, doc.uid, NodeId(id))) +} + +/// `layers.removeAll()`: deletes every layer of the collection in one command. A document keeps a +/// layer, so on the top-level layers it throws before anything is deleted. +fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if parent.is_none() { + return Err(HostError::Error("a document needs at least one layer".into())); + } + let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent)); + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- GroupItems, CompoundPathItems and a container's PageItems ---- + +/// The document and the layer, group or compound path (`None`: the whole document) an art +/// collection of `class` lists. +fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let holds = with_doc(h, doc, |_, st| { + st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(type_error(class)), + } +} + +/// The objects of `kind` in `container` (directly), or in the whole document at any depth, in +/// paint order. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result> { + let ids: Vec = match container { + None => { + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => st.doc.node(c).and_then(|n| n.children()).into_iter().flatten().filter(|n| kind.holds(n)).map(|n| n.id).collect(), + }; + Ok(ids) +} + +/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle +/// names the container. +pub(super) fn is_scoped(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 4) +} + +fn collection(h: &Host, kind: Kind, container: Option, uid: u64) -> Data { + match container { + Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1]]), + None => host_ref(kind.class(), &[float(h.run), float(uid)]), + } +} + +fn art_length(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let n = with_doc(h, doc, |_, st| art_list(h, st, kind, c).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) +} + +fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = art_list(h, st, kind, c)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { + match arg(a, 1) { + Data::String(_) => art_by_name(h, a, kind), + Data::Number(_) => match art_at(h, a, kind)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every object the collection lists (those inside another listed one go +/// with it) in one command. A hidden or locked one, or one in a hidden or locked layer or group, +/// stops it before anything is deleted. +fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let all = art_list(h, st, kind, c)?; + let d = &st.doc; + let listed: std::collections::HashSet = all.iter().copied().collect(); + let ids: Vec = + all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); + let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their +/// handle names one ([`is_scoped`]). +pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Any) +} + +pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Any) +} + +pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Any) +} + +pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Any) +} + +pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Any) +} + +fn groups_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Group) +} +fn groups_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Group) +} +fn groups_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Group) +} +fn groups_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Group) +} +fn groups_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Group) +} +fn groups_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Group) +} +fn compounds_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Compound) +} +fn compounds_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Compound) +} +fn compounds_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Compound) +} +fn compounds_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Compound) +} +fn compounds_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Compound) +} +fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Compound) +} + +fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) +} + +pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Any) +} +fn groups_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Group) +} +fn compounds_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Compound) +} + +/// `groupItems.add()`: an empty group on top of the layer's or group's contents (the document's: +/// the current layer's), with `object.newGroup`. → the group. +fn groups_add(h: &Host, a: &[Data]) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), "GroupItems")?; + if let Some(c) = c { + let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if compound { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } + let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + let r = on_doc(h, doc.uid, true, |h| command(h, "object.newGroup", ¶ms))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +fn compounds_add(_: &Host, _: &[Data]) -> Answer { + Err(HostError::Error("CompoundPathItems.add cannot make an empty compound path: a compound path holds at least one path".into())) +} + +// ---- The art collections of a document, a layer, a group and a compound path ---- + +/// The collection of `kind` the object `this` holds: a document's (`Document`), a layer's +/// (`Layer`) or a page item's. +fn held(h: &Host, a: &[Data], kind: Kind) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Document").is_some() { + let doc = doc_of(h, this, "Document")?; + return Ok(collection(h, kind, None, doc.uid)); + } + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(collection(h, kind, Some(id), doc.uid)); + } + let item = item_of(h, this)?; + Ok(collection(h, kind, Some(item.id), item.doc.uid)) +} + +fn held_page_items(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Any) +} + +fn held_groups(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Group) +} + +fn held_compounds(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Compound) +} + +// ---- GroupItem and CompoundPathItem ---- + +fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { + let item = item_of(h, arg(a, 0))?; + let ok = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename) == Some(what)); + if !ok { + return Err(type_error(what)); + } + Ok(item) +} + +/// The layer the object is in. +fn item_layer(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + Ok(with_doc(h, item.doc, |_, st| st.doc.layer_containing(item.id).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +fn group_clipped(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "GroupItem")?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(crate::doc::Node::clips)))) +} + +/// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the +/// clipping mask. The group keeps its id either way. +fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "clipped")?; + let item = this_item_of(h, a, "GroupItem")?; + let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + if now == on { + return Ok(Data::Undefined); + } + if !ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); + } + on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; + Ok(Data::Undefined) +} + +/// The members `layers.rs` adds to `PageItem`'s. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("layer", get(l, item_layer))]) +} + +/// The members a page item class adds to `PageItem`'s. +pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { + match class { + "GroupItem" => { + let mut m = named(vec![ + ("clipped", property(l, group_clipped, group_set_clipped)), + ("pageItems", get(l, held_page_items)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ]); + m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m + } + "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), + _ => Vec::new(), + } +} + +// ---- Document ---- + +fn doc_layers(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Layers", &[float(h.run), float(doc.uid)])) +} + +fn doc_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +/// `activeLayer = layer`: the layer becomes the current one, where new art goes. +fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + let (to, id) = layer_of(h, arg(a, 1))?; + if to.uid != doc.uid { + return Err(HostError::Error("the layer is in another document".into())); + } + let now = with_doc(h, doc, |_, st| st.current_layer()); + if now != Some(id) { + on_doc(h, doc.uid, true, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + } + Ok(Data::Undefined) +} + +fn doc_artboards(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Artboards", &[float(h.run), float(doc.uid)])) +} + +/// The members `layers.rs` adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("layers", get(l, doc_layers)), + ("activeLayer", property(l, doc_active_layer, doc_set_active_layer)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ("artboards", get(l, doc_artboards)), + ]) +} + +// ---- Artboard and Artboards ---- + +/// The document of an artboard. +#[derive(Clone, Copy)] +struct Board { + doc: Doc, +} + +fn board_index(st: &DocState, id: u32) -> Option { + st.doc.artboards.iter().position(|a| a.id == id) +} + +fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> { + let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) }; + let [run, uid, id] = handle.as_slice() else { return Err(type_error("Artboard")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + let index = with_doc(h, doc, |_, st| board_index(st, id)).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + Ok((Board { doc }, index)) +} + +fn board_ref(h: &Host, uid: u64, id: u32) -> Data { + host_ref("Artboard", &[float(h.run), float(uid), f64::from(id)]) +} + +fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { + board_of(h, arg(a, 0)) +} + +/// Reads the artboard `this` names with `f`. +fn read_board(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Artboard, usize) -> Answer) -> Answer { + let (b, i) = this_board(h, a)?; + with_doc(h, b.doc, |_, st| match st.doc.artboards.get(i) { + Some(ab) => f(st, ab, i), + None => Err(HostError::Error(STALE_ARTBOARD.into())), + }) +} + +/// Runs `artboard.setProps` with `props` for the artboard, unless `unchanged` says it has them. +fn set_board(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Artboard) -> bool, props: Value) -> Answer { + let (b, i) = this_board(h, a)?; + let same = with_doc(h, b.doc, |_, st| st.doc.artboards.get(i).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("index".into(), json!(i)); + } + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.setProps", &p))?; + } + Ok(Data::Undefined) +} + +fn board_rect(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, _| Ok(frame(st)?.bounds(h.dom.coords.get(), ab.rect))) +} + +/// A rectangle `[left, top, right, bottom]` a script gave, in document coordinates, checked: finite, +/// inside the canvas, and from 1 to [`super::MAX_SIZE`] points on each side, the sides the artboard +/// commands keep. +fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result { + let Data::Array(v) = d else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let [l, t, r, b] = v.as_slice() else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let n = |d: &Data| super::coordinate(d, what); + let (l, t, r, b) = (n(l)?, n(t)?, n(r)?, n(b)?); + let f = frame(st)?; + let c = h.dom.coords.get(); + let p = f.to_document(c, [l, t]); + let q = f.to_document(c, [r, b]); + let rect = vectorcraft_geom::Rect::new(p.x.min(q.x), p.y.min(q.y), p.x.max(q.x), p.y.max(q.y)); + if q.x <= p.x || q.y <= p.y { + return Err(HostError::Range(format!("{what} must have its right side right of its left side and its bottom below its top"))); + } + if rect.width() < 1.0 || rect.height() < 1.0 { + return Err(HostError::Range(format!("{what} must be at least 1 point wide and tall"))); + } + if rect.width() > super::MAX_SIZE || rect.height() > super::MAX_SIZE { + return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); + } + Ok(rect) +} + +fn board_set_rect(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + let r = with_doc(h, b.doc, |_, st| rect_arg(h, st, arg(a, 1), "artboardRect"))?; + let close = |x: f64, y: f64| (x - y).abs() < 1e-9; + set_board( + h, + a, + |ab| close(ab.rect.x0, r.x0) && close(ab.rect.y0, r.y0) && close(ab.rect.x1, r.x1) && close(ab.rect.y1, r.y1), + json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()}), + ) +} + +fn board_name(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) +} + +/// A new artboard name: not empty, at most [`MAX_TEXT_BYTES`] bytes, and no other artboard's +/// (`except`: the artboard being renamed). → the name, trimmed as `artboard.rename` trims it. +fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result { + let Data::String(name) = d else { return Err(HostError::Type("name must be a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let name = name.trim(); + if name.is_empty() { + return Err(HostError::Range("an artboard's name cannot be empty".into())); + } + if st.doc.artboards.iter().enumerate().any(|(i, ab)| Some(i) != except && ab.name == name) { + return Err(HostError::Error(format!("another artboard is named {name}"))); + } + Ok(name.to_string()) +} + +fn board_set_name(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + let name = with_doc(h, b.doc, |_, st| board_name_arg(st, arg(a, 1), Some(i)))?; + set_board(h, a, |ab| ab.name == name, json!({"name": name})) +} + +fn board_parent(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + Ok(doc_ref(h, b.doc.uid)) +} + +fn board_typename(h: &Host, a: &[Data]) -> Answer { + this_board(h, a)?; + Ok(text("Artboard")) +} + +/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner +/// with Y down. +fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, i| { + let o = st.doc.ruler_origin_for(i); + Ok(super::pair([o.x - ab.rect.x0, o.y - ab.rect.y0])) + }) +} + +fn board_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let p = super::point(arg(a, 1), "rulerOrigin")?; + let (b, i) = this_board(h, a)?; + let (to, now) = with_doc(h, b.doc, |_, st| { + let ab = &st.doc.artboards[i]; + (vectorcraft_geom::Point::new(ab.rect.x0 + p[0], ab.rect.y0 + p[1]), st.doc.ruler_origin_for(i)) + }); + if to.distance(now) > 1e-9 { + on_doc(h, b.doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": i})))?; + } + Ok(Data::Undefined) +} + +fn board_par(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(num(ab.video_ruler_pixel_aspect_ratio))) +} + +fn board_set_par(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "rulerPAR")?; + if !crate::doc::VIDEO_PIXEL_ASPECT_RANGE.contains(&v) { + return Err(HostError::Range("rulerPAR must be from 0.1 to 10".into())); + } + set_board(h, a, |ab| (ab.video_ruler_pixel_aspect_ratio - v).abs() < 1e-12, json!({"videoRulerPixelAspectRatio": v})) +} + +fn board_center(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_center_mark))) +} + +fn board_set_center(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCenter")?; + set_board(h, a, |ab| ab.show_center_mark == v, json!({"showCenterMark": v})) +} + +fn board_cross_hairs(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_cross_hairs))) +} + +fn board_set_cross_hairs(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCrossHairs")?; + set_board(h, a, |ab| ab.show_cross_hairs == v, json!({"showCrossHairs": v})) +} + +fn board_safe_areas(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_video_safe_areas))) +} + +fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showSafeAreas")?; + set_board(h, a, |ab| ab.show_video_safe_areas == v, json!({"showVideoSafeAreas": v})) +} + +fn board_remove(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_doc(h: &Host, a: &[Data]) -> Result { + doc_of(h, arg(a, 0), "Artboards") +} + +fn boards_length(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.artboards.len()) as u64))) +} + +fn boards_parent(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn boards_typename(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("Artboards")) +} + +/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`). +fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { + let n = number(d, what)?; + whole(n) + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < len) + .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) +} + +fn boards_at(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) +} + +fn boards_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + h.charge_call(st.doc.artboards.len() as u64)?; + let ab = st.doc.artboards.iter().find(|ab| ab.name == *name); + ab.map(|ab| board_ref(h, st.uid, ab.id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn boards_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => boards_by_name(h, a), + Data::Number(_) => match boards_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with +/// `artboard.reorder`. → the artboard. +fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { + let doc = boards_doc(h, a)?; + let (r, len, name) = with_doc(h, doc, |_, st| { + let boards = &st.doc.artboards; + h.charge_call(boards.len() as u64)?; + // The first "Artboard N" from one past the count that no artboard has, so names stay unique. + let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); + Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) + })?; + let to = at.map(|d| board_index_arg(d, len + 1, "index")).transpose()?; + let max = whole(super::MAX_ARTBOARDS).and_then(|m| usize::try_from(m).ok()).unwrap_or(0); + if len >= max { + return Err(HostError::Range(format!("a document has at most {max} artboards"))); + } + let id = on_doc(h, doc.uid, true, |h| { + let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = + result_id(&made, "index").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + })?; + Ok(board_ref(h, doc.uid, id)) +} + +/// `artboards.add(artboardRect)`: a new artboard, last in the list. +fn boards_add(h: &Host, a: &[Data]) -> Answer { + add_board(h, a, None) +} + +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. +fn boards_insert(h: &Host, a: &[Data]) -> Answer { + if matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("insert needs an index".into())); + } + add_board(h, a, Some(arg(a, 2))) +} + +fn boards_remove(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); + let i = board_index_arg(arg(a, 1), len, "index")?; + on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64))) +} + +/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the +/// document changes, and no command runs. +fn boards_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); + let i = board_index_arg(arg(a, 1), len, "index")?; + if i != now { + let mut s = h.session.borrow_mut(); + let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); + let id = st.active_artboard; + drop(s); + let mut moved = h.dom.active_artboards.borrow_mut(); + moved.retain(|(u, _)| *u != doc.uid); + if let Some(id) = id { + moved.push((doc.uid, id)); + } + } + Ok(Data::Undefined) +} + +/// The documents whose active artboard the run changed, as `script.run`'s report gives them: +/// `[{document, artboard}]`, each an index, or `None` when there are none. +pub(crate) fn active_artboards(moved: &[(u64, u32)], docs: &[DocState]) -> Option { + let list: Vec = moved + .iter() + .filter_map(|(uid, id)| { + let document = docs.iter().position(|d| d.uid == *uid)?; + let artboard = board_index(&docs[document], *id)?; + Some(json!({"document": document, "artboard": artboard})) + }) + .collect(); + (!list.is_empty()).then_some(Value::Array(list)) +} + +/// The classes of layers, art collections and artboards. +pub(super) fn classes(l: &Link) -> Vec { + let class = super::class; + let mut layer = named(vec![ + ("typename", get(l, layer_typename)), + ("name", property(l, layer_name, layer_set_name)), + ("visible", property(l, layer_visible, layer_set_visible)), + ("locked", property(l, layer_locked, layer_set_locked)), + ("printable", property(l, layer_printable, layer_set_printable)), + ("preview", property(l, layer_preview, layer_set_preview)), + ("dimPlacedImages", property(l, layer_dim, layer_set_dim)), + ("opacity", property(l, layer_opacity, layer_set_opacity)), + ("color", property(l, layer_color, layer_set_color)), + ("parent", get(l, layer_parent)), + ("layers", get(l, layers_of)), + ("pageItems", get(l, held_page_items)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ("zOrderPosition", get(l, layer_z_position)), + ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), + ("isIsolated", get(l, layer_is_isolated)), + ("move", method(l, layer_move)), + ("remove", method(l, layer_remove)), + ("zOrder", method(l, layer_z_order)), + ]); + layer.extend( + ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] + .map(|m| later(l, "Layer", m)), + ); + vec![ + class("Layer", None, layer, None), + class( + "Layers", + None, + named(vec![ + ("typename", get(l, layers_typename)), + ("length", get(l, layers_length)), + ("parent", get(l, layers_parent)), + ("index", method(l, layers_index)), + ("getByName", method(l, layers_by_name)), + ("add", method(l, layers_add)), + ("removeAll", method(l, layers_remove_all)), + ]), + Some(super::function(l, layers_at)), + ), + class( + "GroupItems", + None, + { + let mut m = named(vec![ + ("typename", get(l, groups_typename)), + ("length", get(l, groups_length)), + ("parent", get(l, groups_parent)), + ("index", method(l, groups_index)), + ("getByName", method(l, groups_by_name)), + ("add", method(l, groups_add)), + ("removeAll", method(l, groups_remove_all)), + ]); + m.push(later(l, "GroupItems", "createFromFile")); + m + }, + Some(super::function(l, groups_at)), + ), + class( + "CompoundPathItems", + None, + named(vec![ + ("typename", get(l, compounds_typename)), + ("length", get(l, compounds_length)), + ("parent", get(l, compounds_parent)), + ("index", method(l, compounds_index)), + ("getByName", method(l, compounds_by_name)), + ("add", method(l, compounds_add)), + ("removeAll", method(l, compounds_remove_all)), + ]), + Some(super::function(l, compounds_at)), + ), + class( + "Artboard", + None, + named(vec![ + ("typename", get(l, board_typename)), + ("artboardRect", property(l, board_rect, board_set_rect)), + ("name", property(l, board_name, board_set_name)), + ("parent", get(l, board_parent)), + ("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin)), + ("rulerPAR", property(l, board_par, board_set_par)), + ("showCenter", property(l, board_center, board_set_center)), + ("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs)), + ("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas)), + ("remove", method(l, board_remove)), + ]), + None, + ), + class( + "Artboards", + None, + named(vec![ + ("typename", get(l, boards_typename)), + ("length", get(l, boards_length)), + ("parent", get(l, boards_parent)), + ("index", method(l, boards_index)), + ("getByName", method(l, boards_by_name)), + ("add", method(l, boards_add)), + ("insert", method(l, boards_insert)), + ("remove", method(l, boards_remove)), + ("getActiveArtboardIndex", method(l, boards_active)), + ("setActiveArtboardIndex", method(l, boards_set_active)), + ]), + Some(super::function(l, boards_at)), + ), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..34779c7b5e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2290,6 +2290,9 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), self.documents()) { + report["activeArtboards"] = boards; + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0324e81339..2b3920f3d0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -654,7 +654,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } - assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.views = 1;").contains("Document.views is not available yet")); // A deleted item or an earlier run's document is stale first. let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); assert!(e.contains("Stale page item"), "{e}"); @@ -911,5 +911,338 @@ fn prototype_changes_cannot_forge_a_page_item() { #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); - assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.views;").contains("Document.views is not available yet")); +} + +fn layer_names(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().rev().map(|n| n.name.clone().unwrap_or_default()).collect() +} + +#[test] +fn layers_list_top_first_and_add_makes_the_new_layer_current() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers; vc.log(L.length); vc.log(L.typename); vc.log(L.parent.typename);\ + var n = L.add(); n.name = 'Top'; vc.log(L.length); vc.log(L[0].name); vc.log(d.activeLayer.name);\ + vc.log(L.getByName('Top').zOrderPosition); vc.log(L[1].zOrderPosition); vc.log(n.parent.typename);\ + var sub = L[1].layers.add(); sub.name = 'Sub'; vc.log(L[1].layers.length); vc.log(sub.parent.name);\ + vc.log(L.length); vc.log(L[5] === undefined); vc.log(L[1].pageItems.length); vc.log(L[1].pageItems[0].typename);\ + vc.log(sub.zOrderPosition);", + ); + let expected = [json!(1), json!("Layers"), json!("Document"), json!(2), json!("Top"), json!("Top"), json!(2), json!(1), json!("Document")]; + assert_eq!(out[..9], expected); + // A layer's pageItems hold its art, not its sublayers, and a sublayer's zOrderPosition counts + // only the layers beside it. + assert_eq!(out[9..], [json!(1), json!("Layer 1"), json!(2), json!(true), json!(2), json!("PathItem"), json!(1)]); + assert_eq!(layer_names(&s), ["Top", "Layer 1"]); + // One run is one undo step. + assert_eq!(undo_steps(&s), steps + 1); + let lid = s.active().unwrap().doc.layer_containing(a).unwrap(); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.layers.getByName(5);").contains("give a name")); + assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); +} + +#[test] +fn layer_properties_round_trip_and_reject_bad_values() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0];\ + l.name = 'Art'; l.printable = false; l.preview = false; l.opacity = 40; l.dimPlacedImages = true;\ + l.color = {red: 10, green: 20, blue: 30};\ + vc.log(l.name); vc.log(l.printable); vc.log(l.preview); vc.log(l.opacity); vc.log(l.dimPlacedImages);\ + var c = l.color; vc.log([c.red, c.green, c.blue]); vc.log(l.visible); vc.log(l.locked); vc.log(l.typename);\ + l.visible = false; vc.log(l.visible); l.visible = true; l.locked = true; vc.log(l.locked); l.locked = false;", + ); + let expected = [json!("Art"), json!(false), json!(false), json!(40), json!(true), json!([10, 20, 30]), json!(true), json!(false)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("Layer"), json!(false), json!(true)]); + // Setting the values a layer has adds no undo step. + let steps = undo_steps(&s); + let same = "var l = app.activeDocument.layers[0]; l.name = 'Art'; l.opacity = 40; l.printable = false; l.color = {red: 10, green: 20, blue: 30};"; + run(&mut s, same).unwrap(); + assert_eq!(undo_steps(&s), steps); + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (src, msg) in [ + ("app.activeDocument.layers[0].name = 5;", "name must be a string"), + ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), + ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), + ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), + ("app.activeDocument.layers[0].opacity = NaN;", "finite number"), + ("app.activeDocument.layers[0].visible = 1;", "true or false"), + ("app.activeDocument.layers[0].color = {red: 300, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = {red: 1.5, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = 'red';", "red, green and blue"), + ("app.activeDocument.layers[0].zOrder('up');", "ZOrderMethod"), + ("app.activeDocument.activeLayer = 3;", "not a Layer"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn layer_move_and_z_order_keep_ids() { + let (mut s, _, _) = doc(); + run(&mut s, "var L = app.activeDocument.layers; L.add().name = 'B'; L.add().name = 'C';").unwrap(); + assert_eq!(layer_names(&s), ["C", "B", "Layer 1"]); + let out = log( + &mut s, + "var L = app.activeDocument.layers, c = L[0]; c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(L[2].name); vc.log(c.zOrderPosition);\ + c.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(L[1].name);\ + c.move(L.getByName('B'), ElementPlacement.PLACEBEFORE); vc.log(L[0].name);\ + c.move(L.getByName('B')); vc.log(L.length); vc.log(c.parent.name); vc.log(c.name);\ + c.move(app.activeDocument); vc.log(L.length); vc.log(L[0].name);", + ); + assert_eq!(out, [json!("C"), json!(1), json!("C"), json!("C"), json!(2), json!("B"), json!("C"), json!(3), json!("C")]); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[0]);").contains("into itself")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[1].pageItems);").contains("a layer or a document")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move();").contains("relative object")); +} + +#[test] +fn sublayer_z_order_steps_past_the_next_layer_and_the_art_between() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var P = app.activeDocument.layers[0], x = P.layers.add(); x.name = 'X'; x.zOrder(ZOrderMethod.SENDTOBACK);\ + var y = P.layers.add(); y.name = 'Y'; vc.log([x.zOrderPosition, y.zOrderPosition]);\ + y.zOrder(ZOrderMethod.SENDBACKWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(P.pageItems.length);", + ); + assert_eq!(out, [json!([1, 2]), json!([2, 1, "X"]), json!([1, 2, "Y"]), json!(2)]); + // The last step had no layer to pass, so Y stayed under the art. + let d = &s.active().unwrap().doc; + let p = d.layers.last().unwrap(); + let kids = d.children(Some(p.id)).unwrap(); + assert!(kids[1].is_layer() && !kids[2].is_layer() && !kids[3].is_layer()); +} + +#[test] +fn removed_layers_throw_and_the_last_layer_stays() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.add(); n.layers.add(); n.layers.add(); vc.log(n.layers.length);\ + n.layers.removeAll(); vc.log(n.layers.length); n.remove(); vc.log(L.length);\ + try { n.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..3], [json!(2), json!(0), json!(1)]); + assert!(out[3].as_str().unwrap().contains("Stale layer"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "app.activeDocument.layers[0].remove();").contains("at least one layer")); + assert!(failure(&mut s, "app.activeDocument.layers.removeAll();").contains("at least one layer")); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "Object.getOwnPropertyDescriptor(Layer.prototype, 'name').get.call({});").contains("not a Layer")); +} + +#[test] +fn group_items_list_every_depth_and_clipped_toggles_the_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0]; vc.log(d.groupItems.length); vc.log(g.pageItems.length);\ + var inner = g.groupItems.add(); vc.log(inner.typename); vc.log(inner.pageItems.length);\ + vc.log(d.groupItems.length); vc.log(g.groupItems.length); vc.log(d.layers[0].groupItems.length);\ + vc.log(g.layer.name); vc.log(g.clipped); vc.log(d.compoundPathItems.length);\ + d.layers[0].groupItems.add(); vc.log(d.layers[0].groupItems.length); vc.log(g.pageItems.parent.typename);", + ); + let expected = [json!(1), json!(2), json!("GroupItem"), json!(0), json!(2), json!(1), json!(1), json!("Layer 1"), json!(false), json!(0)]; + assert_eq!(out[..10], expected); + assert_eq!(out[10..], [json!(2), json!("GroupItem")]); + // `clipped` on a group with a path on top makes the topmost path its clipping path. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + run(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = false;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = true; vc.log(g.clipped);"), [json!(true)]); + let st = s.active().unwrap(); + let g = st.doc.node(gid).unwrap(); + assert!(g.clips()); + assert_eq!(g.children().unwrap()[0].id, b); + assert_eq!(undo_steps(&s), steps + 1); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); + assert!(failure(&mut s, "app.activeDocument.compoundPathItems.add();").contains("empty compound path")); + assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); +} + +#[test] +fn group_items_remove_all_refuses_locked_groups() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems.removeAll();").contains("hidden or locked")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("object.setProps", &json!({"ids": [g], "locked": false})).unwrap(); + run(&mut s, "app.activeDocument.groupItems.removeAll();").unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); +} + +#[test] +fn new_group_command_checks_its_parent() { + let (mut s, a, _) = doc(); + let layer = s.active().unwrap().doc.layer_containing(a).unwrap(); + let g = s.execute("object.newGroup", &json!({"parent": layer.0, "index": 0})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(NodeId(g)).map(|(p, i, _)| (p, i)), Some((Some(layer), 0))); + assert!(s.execute("object.newGroup", &json!({"parent": a.0})).unwrap_err().to_string().contains("not a layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be")); + assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be")); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked")); +} + +#[test] +fn artboards_add_insert_rename_and_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(A.length); vc.log(A[0].artboardRect); vc.log(A.typename);\ + var b = A.add([500, 300, 700, 100]); b.name = 'Two'; vc.log(A.length); vc.log(A[1].name); vc.log(b.artboardRect);\ + A.insert([0, -100, 100, -200], 1); vc.log(A[1].artboardRect); vc.log(b.name); vc.log(A.getByName('Two').artboardRect[0]);\ + b.artboardRect = [500, 300, 650, 150]; vc.log(b.artboardRect); b.rulerPAR = 2; vc.log(b.rulerPAR);\ + b.showCenter = true; b.showCrossHairs = true; b.showSafeAreas = true; vc.log([b.showCenter, b.showCrossHairs, b.showSafeAreas]);\ + b.rulerOrigin = [10, 20]; vc.log(b.rulerOrigin); vc.log(b.parent.typename);\ + A.remove(0); vc.log(A.length); b.remove(); vc.log(A.length); try { b.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..4], [json!(1), json!([0, 300, 400, 0]), json!("Artboards"), json!(2)]); + assert_eq!(out[4..7], [json!("Two"), json!([500, 300, 700, 100]), json!([0, -100, 100, -200])]); + assert_eq!(out[7..11], [json!("Two"), json!(500), json!([500, 300, 650, 150]), json!(2)]); + assert_eq!(out[11..16], [json!([true, true, true]), json!([10, 20]), json!("Document"), json!(2), json!(1)]); + assert!(out[16].as_str().unwrap().contains("Stale artboard"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn new_artboards_get_a_name_no_other_artboard_has() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ + vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0).name);\ + vc.log(A.add([800, 300, 900, 100]).name);", + ); + assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); +} + +#[test] +fn artboards_reject_bad_arguments_before_any_change() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]).name = 'Two';").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + for (src, msg) in [ + ("app.activeDocument.artboards.add([0, 0, 10]);", "four numbers"), + ("app.activeDocument.artboards.add('x');", "four numbers"), + ("app.activeDocument.artboards.add([10, 0, 0, 10]);", "right side"), + ("app.activeDocument.artboards.add([0, 0, NaN, -10]);", "finite number"), + ("app.activeDocument.artboards.add([0, 0, 1e300, -10]);", "outside the canvas"), + ("app.activeDocument.artboards.add([0, 0, 0.5, -10]);", "at least 1 point"), + ("app.activeDocument.artboards[0].artboardRect = [0, 0, 10, -0.25];", "at least 1 point"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10], 5);", "index must be"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), + ("app.activeDocument.artboards.remove(2);", "index must be"), + ("app.activeDocument.artboards.remove(-1);", "index must be"), + ("app.activeDocument.artboards[0].name = 'Two';", "another artboard"), + ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), + ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), + ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), + ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), + ("app.activeDocument.artboards.setActiveArtboardIndex(9);", "index must be"), + ("app.activeDocument.artboards.getByName('none');", "Not found"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); + run(&mut s, "app.activeDocument.artboards.remove(1);").unwrap(); + assert!(failure(&mut s, "app.activeDocument.artboards[0].remove();").to_lowercase().contains("artboard")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn set_active_artboard_index_is_reported_without_an_undo_step() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let steps = undo_steps(&s); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(1); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); + // Artboard coordinates follow the active artboard. + let out = log(&mut s, "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(app.activeDocument.artboards[1].artboardRect);"); + assert_eq!(out, [json!([0, 0, 200, 200])]); + let r = run(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1);").unwrap(); + assert!(r.get("activeArtboards").is_none()); +} + +#[test] +fn has_selected_artwork_selects_and_deselects_a_layers_art() { + let (mut s, a, b) = doc(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; vc.log(l.hasSelectedArtwork); l.hasSelectedArtwork = true;\ + vc.log(app.activeDocument.selection.length); vc.log(l.hasSelectedArtwork); vc.log(l.isIsolated);", + ); + assert_eq!(out, [json!(false), json!(2), json!(true), json!(false)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + run(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = false;").unwrap(); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); +} + +#[test] +fn artboards_stop_at_one_hundred() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; for (var i = 1; i < 100; i++) A.add([i * 10, -400, i * 10 + 5, -405]);").unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.artboards.add([0, -500, 10, -510]);").contains("at most 100 artboards")); + assert!(failure(&mut s, "app.activeDocument.artboards.insert([0, -500, 10, -510], 0);").contains("at most 100 artboards")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn every_page_item_has_its_layer_and_members_check_this() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ + vc.log(p.layer.name); vc.log(d.pageItems[0].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", + ); + assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); + for src in [ + "Object.getOwnPropertyDescriptor(Layers.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(GroupItems.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboard.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboards.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Layer.prototype, 'pathItems').get.call({});", + ] { + assert!(failure(&mut s, src).contains("this is not a"), "{src}"); + } + let stale = "var L = app.activeDocument.layers, n = L.add(), c = n.layers, g = n.groupItems; n.remove();"; + for read in ["c.typename", "g.typename", "n.pathItems"] { + assert!(failure(&mut s, &format!("{stale} {read};")).contains("Stale"), "{read}"); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..881cb64d04 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,9 +73,10 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ - DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + "app Application Artboard Artboards CompoundPathItem CompoundPathItems CoordinateSystem Document \ + DocumentArtboardLayout DocumentColorSpace DocumentPresetType DocumentPreviewMode DocumentRasterResolution \ + DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems RulerUnits \ + ZOrderMethod", ), ("Application.", "prototype"), ( @@ -88,21 +89,54 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + "activeLayer activeLayer= artboards close close= compoundPathItems constructor convertCoordinate \ + documentColorSpace groupItems height layers name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), - ("Layer.prototype.", "constructor name typename"), + ( + "Layer.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ + dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ + locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ + textFrames= typename visible visible= zOrder zOrderPosition", + ), + ("Layers.", "prototype"), + ("Layers.prototype.", "add constructor getByName index length parent removeAll typename"), + ("GroupItem.", "prototype"), + ( + "GroupItem.prototype.", + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + ), + ("GroupItems.", "prototype"), + ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"), + ("CompoundPathItem.", "prototype"), + ("CompoundPathItem.prototype.", "constructor pathItems"), + ("CompoundPathItems.", "prototype"), + ("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Artboard.", "prototype"), + ( + "Artboard.prototype.", + "artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \ + showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= typename", + ), + ("Artboards.", "prototype"), + ( + "Artboards.prototype.", + "add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \ + typename", + ), ("PageItems.", "prototype"), ("PageItems.prototype.", "constructor getByName index length parent removeAll typename"), ("PageItem.", "prototype"), ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ - left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \ + left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", @@ -124,9 +158,9 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; +/// and the page item types that have no members of their own. +const BARE_CLASSES: &str = "BlendItem DocumentPreset EnvelopeItem GraphItem IntertwineItem MeshItem PathItem PlacedDocumentItem \ + PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..e8ae5d8a94 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -33,6 +33,7 @@ pub fn poll(app: &mut VectorcraftApp) { app.ui.dialog = None; } script_run::settle_close(app); + let boards = result.as_ref().ok().and_then(|r| r["activeArtboards"].as_array().cloned()).unwrap_or_default(); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. Ok(_) => { @@ -43,6 +44,22 @@ pub fn poll(app: &mut VectorcraftApp) { Err(e) => failed(app, e.to_string()), } app.sync_views(); + show_artboards(app, &boards); +} + +/// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). +fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { + for b in boards { + let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); + let (Some(doc), Some(board)) = (index("document"), index("artboard")) else { continue }; + let count = app.session.documents().get(doc).map_or(0, |d| d.doc.artboards.len()); + if let Some(view) = app.views.get_mut(doc) + && board < count + { + view.artboard = board; + } + } } /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..d74b9e1699 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -114,6 +114,18 @@ fn stop_puts_the_document_back_and_says_so() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn set_active_artboard_index_shows_the_artboard_in_the_view() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.views[0].artboard = 0; + let source = "app.activeDocument.artboards.setActiveArtboardIndex(1);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, 1); +} + #[test] fn a_script_error_goes_to_the_status_bar() { let mut app = app(); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..142683f55a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,9 +807,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the - other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (views, paths, type and the other + classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new + documents, each document's selection, its page items, layers, groups, compound paths and artboards. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..7c4c190230 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2672,10 +2672,61 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. 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. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.views`, `PageItem.blendingMode`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- A document also has `layers`, `activeLayer`, `groupItems`, `compoundPathItems` and `artboards`. + `layers` (https://ai-scripting.docsforadobe.dev/jsobjref/Layers/) and a layer's own `layers` have `length`, `[i]`, + `index(key)`, `getByName(name)`, `add()` and `removeAll()`. On the document, `add()` runs `layer.new` and makes a + layer above every top-level layer; on a layer it runs `layer.newSublayer` and makes a sublayer on top of that + layer's contents. The new layer becomes the current one. `removeAll()` runs `layer.delete`; on the document's + layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs + `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, + `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, + `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into + another layer, to the top level of the document, or directly above or below another layer. Every page item has + `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has + `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, + `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. + `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) + has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`), + `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`), `remove(index)` (runs + `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` + (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, + `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its + properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps + one artboard. + VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. `groupItems`, + `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's + `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold + only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` + are its `pageItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers + beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past + the next layer beside it and any art between them. + `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection, and `false` deselects it. + `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping + path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the + layer's or group's contents, or of the current layer's for the document's collection. + `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop + at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is + `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below + its top and each side from 1 to 3,999,856 points. Artboard names are trimmed, cannot be empty and are unique: a name + another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one + past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. + `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the + change in `activeArtboards` (`[{document, artboard}]`, both indexes). An index outside the list throws a + `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and + `GroupItems.createFromFile` throw an error that says they are not available yet. +- `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: + the current layer), on top of its contents or at `index` (0 is the bottom), as one undo step named Group, and + gives `{id}`. The selection stays as it is. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..29a93c640b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: 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`). Paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 1b13f0ad1eb4fece1a5910fd6d7f8469ebc6c10f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:36:01 -0800 Subject: [PATCH 005/533] Scripts: app gives scripts preferences, matrices and the clipboard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `app.preferences` reads, stores and removes values by key with the type they were set as. Keys that are not VectorCraft preferences are kept with the preferences under `scriptPreferences`, so they last across runs and restarts, and a failed or stopped run puts them back. Keys, values and the store have size limits, a setter refuses a value of the wrong type, and two windows that set different keys keep both when the preferences file is saved. - `ShowExternalJSXWarning` is the warning before a picked script runs. Setting it to true, or removing it, turns the warning on. Setting it to false opens a confirm with No as its default and turns the warning off only after Yes; a run that cannot show a dialog throws and changes nothing. This confirm is VectorCraft's own rule. - `app.getIdentityMatrix`, the `get…Matrix` and `concatenate…Matrix` functions, `invertMatrix`, `isEqualMatrix` and `isSingularMatrix` work on plain `Matrix` records and never change the records passed in. - `app.copy`, `app.cut` and `app.paste` run `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft/src/prefs.rs | 107 ++++- crates/engine/src/lib.rs | 2 +- crates/engine/src/prefs.rs | 16 + crates/engine/src/script/dialogs.rs | 40 +- crates/engine/src/script/dom.rs | 8 + crates/engine/src/script/dom/clipboard.rs | 49 +++ crates/engine/src/script/dom/matrix.rs | 269 ++++++++++++ crates/engine/src/script/dom/preferences.rs | 258 +++++++++++ crates/engine/src/script/mod.rs | 39 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_prefs.rs | 452 ++++++++++++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 10 +- docs/mcp.md | 35 +- docs/target-app-parity.md | 1 + 14 files changed, 1264 insertions(+), 23 deletions(-) create mode 100644 crates/engine/src/script/dom/clipboard.rs create mode 100644 crates/engine/src/script/dom/matrix.rs create mode 100644 crates/engine/src/script/dom/preferences.rs create mode 100644 crates/engine/src/tests/script_dom_prefs.rs diff --git a/apps/vectorcraft/src/prefs.rs b/apps/vectorcraft/src/prefs.rs index c57ab6b582..ae440e87dc 100644 --- a/apps/vectorcraft/src/prefs.rs +++ b/apps/vectorcraft/src/prefs.rs @@ -201,18 +201,7 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se if key == "engine_prefs" && let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key)) { - let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); - for name in names { - match (was.get(name), now.get(name)) { - (a, b) if a == b => {} - (_, Some(v)) => { - theirs.insert(name.clone(), v.clone()); - } - (_, None) => { - theirs.remove(name); - } - } - } + put_changes(was, now, theirs, MERGED_BY_KEY); continue; } match now { @@ -245,6 +234,61 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se Value::Object(out) } +/// Engine preferences that hold values set one key at a time (`app.preferences` in scripts): a +/// save merges them key by key, so two windows that set different keys keep both. +const MERGED_BY_KEY: &[&str] = &["scriptPreferences"]; + +/// Whether `store`, a saved `scriptPreferences`, reads as a store within the limits +/// `app.preferences` keeps; one that does not read is not within them. +fn script_store_fits(store: &serde_json::Map) -> bool { + serde_json::from_value::>(serde_json::Value::Object(store.clone())) + .is_ok_and(|s| vectorcraft_engine::script::dom::preferences::within_limits(&s)) +} + +/// `theirs` with each entry that changed from `was` to `now` set to `now`'s value, or removed when +/// `now` lacks it. The entries named in `by_key` that are maps (or missing) are merged key by key. +fn put_changes( + was: &serde_json::Map, + now: &serde_json::Map, + theirs: &mut serde_json::Map, + by_key: &[&str], +) { + use serde_json::{Map, Value}; + let empty = Map::new(); + let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect(); + for name in names { + let (a, b) = (was.get(name), now.get(name)); + if a == b { + continue; + } + if by_key.contains(&name.as_str()) + && let (Some(a), Some(b)) = (a.map_or(Some(&empty), Value::as_object), b.map_or(Some(&empty), Value::as_object)) + { + let mut inner = match theirs.remove(name) { + Some(Value::Object(m)) => m, + _ => Map::new(), + }; + put_changes(a, b, &mut inner, &[]); + // A merge past the store's limits saves this window's store as it is. + if !script_store_fits(&inner) { + inner = b.clone(); + } + if !inner.is_empty() { + theirs.insert(name.clone(), Value::Object(inner)); + } + continue; + } + match b { + Some(v) => { + theirs.insert(name.clone(), v.clone()); + } + None => { + theirs.remove(name); + } + } + } +} + /// Point the saved current Actions set (`action_set`) at the same set in the merged /// `action_sets` when the merge took the index from one window and the list from another /// ([`find_action_set`]). With no such set, no set is current. @@ -365,6 +409,45 @@ mod tests { assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}})); } + #[test] + fn script_preference_keys_from_two_windows_are_both_saved() { + let base = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}, "gone": {"integer": 1}}}}); + // The other window set `b`; this one set `c`, changed `a` and removed `gone`. + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}, "b": {"string": "x"}, "gone": {"integer": 1}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": false}, "c": {"real": 0.5}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": false}, "b": {"string": "x"}, "c": {"real": 0.5}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + // A window that started with no keys and removed none keeps the other window's. + let base = json!({"engine_prefs": {}}); + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"b": {"string": "x"}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"c": {"real": 0.5}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"b": {"string": "x"}, "c": {"real": 0.5}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + // Removing the last key of either window leaves the field out. + let base = json!({"engine_prefs": {"scriptPreferences": {"a": {"boolean": true}}}}); + let on_disk = base.clone(); + let mine = json!({"engine_prefs": {}}); + assert_eq!(merge_changes(&base, &mine, on_disk), json!({"engine_prefs": {}})); + } + + #[test] + fn script_preference_keys_merged_past_the_limits_save_this_windows_keys() { + use vectorcraft_engine::script::dom::preferences::MAX_KEYS; + let keys = |prefix: &str| -> serde_json::Map { + (0..MAX_KEYS).map(|i| (format!("{prefix}{i}"), json!({"boolean": true}))).collect() + }; + // Each window added a full store of its own keys. + let base = json!({"engine_prefs": {}}); + let on_disk = json!({"engine_prefs": {"scriptPreferences": keys("theirs")}}); + let mine = json!({"engine_prefs": {"scriptPreferences": keys("mine")}}); + assert_eq!(merge_changes(&base, &mine, on_disk), mine); + // A merge within the limits keeps both windows' keys. + let on_disk = json!({"engine_prefs": {"scriptPreferences": {"theirs": {"boolean": true}}}}); + let mine = json!({"engine_prefs": {"scriptPreferences": {"mine": {"integer": 2}}}}); + let want = json!({"engine_prefs": {"scriptPreferences": {"mine": {"integer": 2}, "theirs": {"boolean": true}}}}); + assert_eq!(merge_changes(&base, &mine, on_disk), want); + } + #[test] fn a_setting_both_windows_changed_takes_the_last_saved() { let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}}); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..089b33a038 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -439,7 +439,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; +pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs, ScriptPreference}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 2e0d0f9fe4..439560dfef 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -438,6 +438,21 @@ pub struct Prefs { /// preferences keeps it. #[serde(skip_serializing_if = "Vec::is_empty")] pub import_matches: Vec, + /// The values scripts store with `app.preferences` under keys that are not VectorCraft + /// preferences. Not a Preferences dialog field: it has no [`cmd::prefscmds::PREF_SPECS`] row, + /// and resetting the preferences keeps it. + #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub script_preferences: std::collections::BTreeMap, +} + +/// A value a script stored with `app.preferences`, with the type it was stored as. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ScriptPreference { + Boolean(bool), + Integer(i64), + Real(f64), + String(String), } /// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). @@ -642,6 +657,7 @@ impl Default for Prefs { blend_options: None, perspective_widget: Default::default(), import_matches: vec![], + script_preferences: Default::default(), } } } diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..1687d1c11a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -184,6 +184,13 @@ fn answer(a: &Value) -> Result { } } +/// What the app does when the person answers Yes to a confirm it opens for a script ([`Dialogs::ask`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum OnYes { + /// Turn off the warning before a script picked with File › Scripts › Other Script… runs. + ExternalScriptWarningOff, +} + /// The dialogs of one run: the answers left for a run with nobody to ask, the dialog that waits /// for the person's answer, and the list the report gives. pub(crate) struct Dialogs { @@ -193,6 +200,10 @@ pub(crate) struct Dialogs { can_wait: Rc>, answers: RefCell>, waiting: RefCell>, + /// What Yes to the waiting dialog does, when the app opened it with [`Dialogs::ask`]. + on_yes: Cell>, + /// What the person approved with Yes, until [`Dialogs::take_approved`] takes it. + approved: Cell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, records: RefCell>, @@ -208,6 +219,8 @@ impl Dialogs { can_wait: realm.wait_flag(), answers: RefCell::new(answers.into()), waiting: RefCell::default(), + on_yes: Cell::new(None), + approved: Cell::new(None), failed: RefCell::default(), records: RefCell::default(), record_bytes: Cell::new(0), @@ -246,14 +259,39 @@ impl Dialogs { let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; self.record(d, answer.json()); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + let on_yes = self.on_yes.take(); + // A confirm the app opened returns `undefined` to the call that opened it. + let data = if on_yes.is_some() { Data::Undefined } else { answer.data() }; + if answer == DialogAnswer::Confirm(true) { + self.approved.set(on_yes); + } + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true } + /// Opens `dialog`, a confirm the app shows for the script, whose Yes does `on_yes`; the call + /// that opens it then waits ([`HostError::Wait`]) and returns `undefined`. Only a person answers + /// it, never `script.run`'s `answers`. → false when it cannot open: the run has nobody to ask, + /// or the call comes from a callback, a getter, a conversion or a file `$.evalFile` runs. + pub(crate) fn ask(&self, dialog: ScriptDialog, on_yes: OnYes) -> bool { + if !self.framed || !self.can_wait.get() { + return false; + } + *self.waiting.borrow_mut() = Some(dialog); + self.on_yes.set(Some(on_yes)); + true + } + + /// What the person approved with Yes to a confirm from [`Dialogs::ask`], once. + pub(crate) fn take_approved(&self) -> Option { + self.approved.take() + } + /// The run ends while a dialog waits: the report lists it with the answer `"stop"`. pub(crate) fn stopped(&self) { + self.on_yes.set(None); if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..dd7619ee63 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,10 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod clipboard; +mod matrix; +pub mod preferences; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -1713,6 +1717,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(preferences::app_members()); + application.extend(matrix::app_members(l)); + application.extend(clipboard::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1723,6 +1730,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), }; let mut classes = vec![ class("Application", None, application, None), + preferences::class(l), preset, class( "Documents", diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs new file mode 100644 index 0000000000..7b07587999 --- /dev/null +++ b/crates/engine/src/script/dom/clipboard.rs @@ -0,0 +1,49 @@ +//! `app.copy()`, `app.cut()` and `app.paste()`, as the help page +//! describes them: Edit › Copy, Cut +//! and Paste on the active document, run as `edit.copy`, `edit.cut` and `edit.paste` in the run's +//! transaction. +//! +//! VectorCraft's own rules, which the help page does not state: with nothing selected, or no +//! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and +//! `paste` with no document open throws `No active document`. + +use serde_json::json; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Answer, Host, Link, NO_ACTIVE_DOCUMENT, command, method, named}; + +/// The clipboard functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec<(String, HostMember)> { + named(vec![("copy", method(link, copy)), ("cut", method(link, cut)), ("paste", method(link, paste))]) +} + +/// Runs `id` when the active document has something it acts on. +fn on_selection(h: &Host, id: &str) -> Answer { + let ready = crate::cmd::has_selection_guides_or_artboard_tool(&h.session.borrow()).is_ok(); + if ready { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn copy(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.copy") +} + +fn cut(h: &Host, _: &[Data]) -> Answer { + on_selection(h, "edit.cut") +} + +fn paste(h: &Host, _: &[Data]) -> Answer { + let ready = { + let s = h.session.borrow(); + if s.active().is_none() { + return Err(HostError::Error(NO_ACTIVE_DOCUMENT.into())); + } + !s.clipboard.is_empty() + }; + if ready { + command(h, "edit.paste", &json!({}))?; + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs new file mode 100644 index 0000000000..71065256fb --- /dev/null +++ b/crates/engine/src/script/dom/matrix.rs @@ -0,0 +1,269 @@ +//! The matrix functions of `app`, as the help pages +//! and +//! describe them. A matrix is a plain +//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the +//! `typename` `"Matrix"`; each function gives a new record and leaves the records passed to it as +//! they were. +//! +//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix +//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `concatenateMatrix(m, n)` gives the matrix that applies `m` and then `n`; the other +//! `concatenate…` functions apply `m` and then the rotation, scale or translation they make. +//! - Left-out arguments are 0 for a translation and an angle, and 100 for a horizontal scale; a +//! left-out vertical scale is the horizontal one. +//! - Angles are degrees, positive counterclockwise, and quarter turns are exact. +//! - A matrix whose determinant is 0 is singular, and `invertMatrix` of one throws. +//! - `isEqualMatrix` compares the six values exactly. +//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a +//! `TypeError`; a result with a value too large for a number throws a `RangeError`. + +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Answer, Host, Link, arg, method, named, num, text}; + +/// A matrix's six values: `[a, b, c, d, tx, ty]`. +type Matrix = [f64; 6]; + +const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// The matrix functions of `Application`. +pub(super) fn app_members(link: &Link) -> Vec<(String, HostMember)> { + let l = link; + named(vec![ + ("getIdentityMatrix", method(l, identity)), + ("getTranslationMatrix", method(l, translation)), + ("getScaleMatrix", method(l, scale)), + ("getRotationMatrix", method(l, rotation)), + ("concatenateMatrix", method(l, concatenate)), + ("concatenateTranslationMatrix", method(l, concatenate_translation)), + ("concatenateScaleMatrix", method(l, concatenate_scale)), + ("concatenateRotationMatrix", method(l, concatenate_rotation)), + ("invertMatrix", method(l, invert)), + ("isEqualMatrix", method(l, is_equal)), + ("isSingularMatrix", method(l, is_singular)), + ]) +} + +/// The record for `m`, or a `RangeError` when a value is not finite. +fn record(m: Matrix) -> Answer { + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the matrix has a value too large for a number".into())); + } + let mut items: Vec<(String, Data)> = KEYS.iter().zip(m).map(|(k, v)| ((*k).to_string(), num(v))).collect(); + items.push(("typename".into(), text("Matrix"))); + Ok(Data::Object(items)) +} + +/// The matrix argument `d`. +fn matrix(d: &Data, what: &str) -> std::result::Result { + let bad = || HostError::Type(format!("{what} must be a Matrix")); + let Data::Object(items) = d else { return Err(bad()) }; + let mut m = [0.0; 6]; + for (slot, k) in m.iter_mut().zip(KEYS) { + match items.iter().find(|(n, _)| n == k) { + Some((_, Data::Number(v))) if v.is_finite() => *slot = *v, + _ => return Err(bad()), + } + } + Ok(m) +} + +/// A number argument, `default` when it is left out. +fn number(d: &Data, what: &str, default: f64) -> std::result::Result { + match d { + Data::Undefined => Ok(default), + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The matrix that applies `m` and then `n`. +fn then(m: Matrix, n: Matrix) -> Matrix { + let [a, b, c, d, e, f] = m; + let [a2, b2, c2, d2, e2, f2] = n; + [a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2] +} + +fn translate(dx: f64, dy: f64) -> Matrix { + [1.0, 0.0, 0.0, 1.0, dx, dy] +} + +/// A scale by `sx` and `sy` percent. +fn scaled(sx: f64, sy: f64) -> Matrix { + [sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0] +} + +/// A turn of `degrees` counterclockwise, exact at quarter turns. +fn rotate(degrees: f64) -> Matrix { + let turn = degrees.rem_euclid(360.0); + let (sin, cos) = match turn { + 0.0 => (0.0, 1.0), + 90.0 => (1.0, 0.0), + 180.0 => (0.0, -1.0), + 270.0 => (-1.0, 0.0), + _ => turn.to_radians().sin_cos(), + }; + // `0.0 - sin` rather than `-sin`, so a turn of 0 gives 0 and not -0. + [cos, sin, 0.0 - sin, cos, 0.0, 0.0] +} + +fn translation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(translate(number(arg(a, at), "deltaX", 0.0)?, number(arg(a, at + 1), "deltaY", 0.0)?)) +} + +fn scale_of(a: &[Data], at: usize) -> std::result::Result { + let sx = number(arg(a, at), "scaleX", 100.0)?; + Ok(scaled(sx, number(arg(a, at + 1), "scaleY", sx)?)) +} + +fn rotation_of(a: &[Data], at: usize) -> std::result::Result { + Ok(rotate(number(arg(a, at), "angle", 0.0)?)) +} + +fn identity(_: &Host, _: &[Data]) -> Answer { + record(IDENTITY) +} + +fn translation(_: &Host, a: &[Data]) -> Answer { + record(translation_of(a, 1)?) +} + +fn scale(_: &Host, a: &[Data]) -> Answer { + record(scale_of(a, 1)?) +} + +fn rotation(_: &Host, a: &[Data]) -> Answer { + record(rotation_of(a, 1)?) +} + +fn concatenate(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, matrix(arg(a, 2), "secondMatrix")?)) +} + +fn concatenate_translation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, translation_of(a, 2)?)) +} + +fn concatenate_scale(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, scale_of(a, 2)?)) +} + +fn concatenate_rotation(_: &Host, a: &[Data]) -> Answer { + record(then(matrix(arg(a, 1), "matrix")?, rotation_of(a, 2)?)) +} + +/// A number as `m · 2^e` with `m` 0 or in `[0.5, 1)`, so products and quotients of such numbers +/// keep their value however far they go past the range of an `f64`. +#[derive(Clone, Copy)] +struct Wide { + m: f64, + e: i32, +} + +/// `2^e`, for `e` from -1022 to 1023. +fn pow2(e: i32) -> f64 { + f64::from_bits(u64::from((e + 1023).clamp(1, 2046).unsigned_abs()) << 52) +} + +impl Wide { + /// `x`, a finite number. + fn of(x: f64) -> Self { + if x == 0.0 { + return Self { m: 0.0, e: 0 }; + } + if x.abs() < f64::MIN_POSITIVE { + let w = Self::of(x * pow2(54)); + return Self { m: w.m, e: w.e - 54 }; + } + let bits = x.to_bits(); + let e = i32::try_from((bits >> 52) & 0x7ff).unwrap_or(0) - 1022; + Self { m: f64::from_bits((bits & !(0x7ff << 52)) | (1022 << 52)), e } + } + + /// `m · 2^e`, with `m` any finite number. + fn new(m: f64, e: i32) -> Self { + let w = Self::of(m); + Self { m: w.m, e: w.e.saturating_add(e) } + } + + fn div(self, o: Self) -> Self { + Self::new(self.m / o.m, self.e.saturating_sub(o.e)) + } + + /// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it. + fn value(self) -> f64 { + let (mut m, mut e) = (self.m, self.e); + while e > 1000 && m.is_finite() { + m *= pow2(1000); + e -= 1000; + } + while e < -1000 && m != 0.0 { + m *= pow2(-1000); + e += 1000; + } + m * pow2(e) + } +} + +/// `a·d − b·c` with no product passing the range of a number; its `m` is 0 only when the two +/// products are equal. The products are taken whole with fused multiply-adds (Kahan's method), so +/// a difference that is small next to them keeps its value. +fn products_difference(a: f64, d: f64, b: f64, c: f64) -> Wide { + let [a, b, c, d] = [a, b, c, d].map(Wide::of); + let (ad, bc) = (a.e.saturating_add(d.e), b.e.saturating_add(c.e)); + if b.m == 0.0 || c.m == 0.0 { + return Wide::new(a.m * d.m, ad); + } + if a.m == 0.0 || d.m == 0.0 { + return Wide::new(0.0 - b.m * c.m, bc); + } + // `a·d` and `b·c` both lie in [0.25, 1) times a power of 2; one more than 2^120 times the other + // decides the sign and size alone. + let gap = bc.saturating_sub(ad); + if gap < -120 { + return Wide::new(a.m * d.m, ad); + } + if gap > 120 { + return Wide::new(0.0 - b.m * c.m, bc); + } + let b = b.m * pow2(gap); + let w = b * c.m; + let err = (0.0 - b).mul_add(c.m, w); + Wide::new(a.m.mul_add(d.m, 0.0 - w) + err, ad) +} + +/// The determinant of `m`'s linear part. +fn determinant(m: Matrix) -> Wide { + products_difference(m[0], m[3], m[1], m[2]) +} + +fn singular(m: Matrix) -> bool { + determinant(m).m == 0.0 +} + +fn invert(_: &Host, a: &[Data]) -> Answer { + let m = matrix(arg(a, 1), "matrix")?; + let det = determinant(m); + if det.m == 0.0 { + return Err(HostError::Error("the matrix is singular and cannot be inverted".into())); + } + let [a, b, c, d, e, f] = m; + // Each value is divided by the determinant before it is brought back into the range of a + // number, and the translations are taken whole, so a finite inverse is not lost to an + // intermediate value. Adding 0 turns -0 into 0. + let over = |w: Wide| w.div(det).value() + 0.0; + let plain = |v: f64| over(Wide::of(v)); + record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))]) +} + +fn is_equal(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) +} + +fn is_singular(_: &Host, a: &[Data]) -> Answer { + Ok(Data::Bool(singular(matrix(arg(a, 1), "matrix")?))) +} diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs new file mode 100644 index 0000000000..064f4fa39d --- /dev/null +++ b/crates/engine/src/script/dom/preferences.rs @@ -0,0 +1,258 @@ +//! `app.preferences`, as the help page +//! describes it: values a script reads and stores by key with a getter and a setter for each type. +//! +//! `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`, the warning before a +//! script picked with File › Scripts › Other Script… runs. A script turns it on at once; turning it +//! off waits for the person to answer Yes to a confirm, and throws when the run cannot ask anyone +//! (VectorCraft's own rule). Every other key is kept in +//! [`crate::Prefs::script_preferences`], with the preferences, so it lasts across runs and restarts +//! and a failed or stopped run puts it back as it was. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - A key that was never stored reads as `false`, `0`, `0` or `""`. +//! - A getter of another type converts the stored value as `Boolean`, `Number` or `String` do; +//! `getIntegerPreference` drops the fraction, and gives `0` for a value that is not a number. +//! - A key is a string of 1 to [`MAX_KEY_UNITS`] UTF-16 units without control characters, a string +//! value has at most [`MAX_STRING_BYTES`] bytes, and at most [`MAX_KEYS`] keys and +//! [`MAX_TOTAL_BYTES`] bytes are stored. A set that would pass a limit throws and stores nothing. +//! - A setter's value must have its type: `setIntegerPreference` takes a whole number within +//! ±2^53, and `setRealPreference` a finite number. +//! - Removing a key that is not stored does nothing; removing `ShowExternalJSXWarning` turns the +//! warning back on. + +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{Answer, Host, Link, arg, method, named, num, text, typename_of}; +use crate::ScriptPreference; +use crate::script::dialogs::{DialogKind, OnYes, ScriptDialog}; + +/// The key that stands for the preference `showExternalScriptWarning`. +pub const EXTERNAL_SCRIPT_WARNING: &str = "ShowExternalJSXWarning"; +/// The longest key, in UTF-16 units. +pub const MAX_KEY_UNITS: usize = 256; +/// The longest string value, in bytes. +pub const MAX_STRING_BYTES: usize = 64 * 1024; +/// The most keys stored. +pub const MAX_KEYS: usize = 4096; +/// The most bytes stored, keys and values together; a value that is not a string counts 8. +pub const MAX_TOTAL_BYTES: usize = 1024 * 1024; + +/// The confirm a run shows before a script turns off [`EXTERNAL_SCRIPT_WARNING`]; No is its default. +pub const WARNING_OFF_QUESTION: &str = "The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off?"; +/// The error when a script turns off [`EXTERNAL_SCRIPT_WARNING`] in a run that cannot ask the person. +pub const WARNING_OFF_NEEDS_A_PERSON: &str = + "ShowExternalJSXWarning can be turned off only after the person at the computer agrees, in a run that can show a dialog"; + +/// The largest whole number `setIntegerPreference` takes. +const MAX_INTEGER: f64 = 9_007_199_254_740_992.0; + +/// The `app.preferences` member of `Application`. +pub(super) fn app_members() -> Vec<(String, HostMember)> { + named(vec![("preferences", HostMember::Get(std::rc::Rc::new(|_| Ok(host_ref("Preferences", &[])))))]) +} + +/// The `Preferences` class. +pub(super) fn class(link: &Link) -> HostClass { + let l = link; + HostClass { + name: "Preferences".into(), + parent: None, + members: named(vec![ + ("typename", typename_of("Preferences")), + ("getBooleanPreference", method(l, |h, a| get(h, a, Kind::Boolean))), + ("getIntegerPreference", method(l, |h, a| get(h, a, Kind::Integer))), + ("getRealPreference", method(l, |h, a| get(h, a, Kind::Real))), + ("getStringPreference", method(l, |h, a| get(h, a, Kind::String))), + ("setBooleanPreference", method(l, |h, a| set(h, a, Kind::Boolean))), + ("setIntegerPreference", method(l, |h, a| set(h, a, Kind::Integer))), + ("setRealPreference", method(l, |h, a| set(h, a, Kind::Real))), + ("setStringPreference", method(l, |h, a| set(h, a, Kind::String))), + ("removePreference", method(l, remove)), + ]), + index: None, + construct: None, + } +} + +#[derive(Clone, Copy)] +enum Kind { + Boolean, + Integer, + Real, + String, +} + +/// The key of a call on `app.preferences`: `this` must be that object, and the key a string within +/// the limits. +fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> { + if !matches!(host_ref_parts(arg(a, 0)), Some(("Preferences", _))) { + return Err(HostError::Type("this is not a Preferences object".into())); + } + let Data::String(key) = arg(a, 1) else { return Err(HostError::Type("a preference's key must be a string".into())) }; + if key.is_empty() || key.encode_utf16().count() > MAX_KEY_UNITS { + return Err(HostError::Range(format!("a preference's key must have 1 to {MAX_KEY_UNITS} characters"))); + } + if key.chars().any(char::is_control) { + return Err(HostError::Error("a preference's key cannot hold control characters".into())); + } + Ok(key) +} + +/// The value stored under `key`, if any. +fn stored(h: &Host, key: &str) -> Option { + let s = h.session.borrow(); + if key == EXTERNAL_SCRIPT_WARNING { + return Some(ScriptPreference::Boolean(s.prefs.show_external_script_warning)); + } + s.prefs.script_preferences.get(key).cloned() +} + +/// `Number(text)`: blank text is 0, `0x`, `0o` and `0b` start a whole number in base 16, 8 or 2, +/// and text that is not a number is NaN. +fn text_number(t: &str) -> f64 { + let t = t.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}'); + if t.is_empty() { + return 0.0; + } + let radix = match t.get(..2) { + Some("0x" | "0X") => 16, + Some("0o" | "0O") => 8, + Some("0b" | "0B") => 2, + _ => 0, + }; + if radix != 0 { + let digits = t.get(2..).unwrap_or(""); + let whole = digits.chars().try_fold(0.0_f64, |n, c| c.to_digit(radix).map(|d| n * f64::from(radix) + f64::from(d))); + return whole.filter(|_| !digits.is_empty()).unwrap_or(f64::NAN); + } + match t.strip_prefix(['+', '-']).unwrap_or(t) { + "Infinity" => { + if t.starts_with('-') { + f64::NEG_INFINITY + } else { + f64::INFINITY + } + } + rest if rest.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E' | b'+' | b'-')) => t.parse().unwrap_or(f64::NAN), + _ => f64::NAN, + } +} + +#[allow(clippy::cast_precision_loss)] +fn as_number(v: &ScriptPreference) -> f64 { + match v { + ScriptPreference::Boolean(b) => f64::from(u8::from(*b)), + ScriptPreference::Integer(n) => *n as f64, + ScriptPreference::Real(n) => *n, + ScriptPreference::String(t) => text_number(t), + } +} + +fn get(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?; + let v = stored(h, key); + Ok(match (kind, v) { + (Kind::Boolean, None) => Data::Bool(false), + (Kind::Integer | Kind::Real, None) => num(0.0), + (Kind::String, None) => text(""), + (Kind::Boolean, Some(v)) => Data::Bool(match v { + ScriptPreference::Boolean(b) => b, + ScriptPreference::String(t) => !t.is_empty(), + v => { + let n = as_number(&v); + n != 0.0 && !n.is_nan() + } + }), + (Kind::Real, Some(v)) => num(as_number(&v)), + (Kind::Integer, Some(v)) => { + let n = as_number(&v).trunc(); + num(if n.is_finite() { n } else { 0.0 }) + } + (Kind::String, Some(v)) => text(match v { + ScriptPreference::Boolean(b) => b.to_string(), + ScriptPreference::String(t) => t, + v => vectorcraft_js::number_to_string(as_number(&v)), + }), + }) +} + +/// The bytes `key` and `v` count toward [`MAX_TOTAL_BYTES`]. +fn size(key: &str, v: &ScriptPreference) -> usize { + key.len() + if let ScriptPreference::String(t) = v { t.len() } else { 8 } +} + +/// Whether `store` holds at most [`MAX_KEYS`] keys and [`MAX_TOTAL_BYTES`] bytes. +pub fn within_limits(store: &std::collections::BTreeMap) -> bool { + store.len() <= MAX_KEYS && store.iter().map(|(k, v)| size(k, v)).sum::() <= MAX_TOTAL_BYTES +} + +#[allow(clippy::cast_possible_truncation)] +fn set(h: &Host, a: &[Data], kind: Kind) -> Answer { + let key = key_of(a)?.to_string(); + let v = arg(a, 2); + let value = match (kind, v) { + (Kind::Boolean, Data::Bool(b)) => ScriptPreference::Boolean(*b), + (Kind::Integer, Data::Number(n)) if n.fract() == 0.0 && n.abs() <= MAX_INTEGER => ScriptPreference::Integer(*n as i64), + (Kind::Real, Data::Number(n)) if n.is_finite() => ScriptPreference::Real(*n), + (Kind::String, Data::String(t)) if t.len() <= MAX_STRING_BYTES => ScriptPreference::String(t.clone()), + (Kind::String, Data::String(_)) => return Err(HostError::Range(format!("a preference's text has at most {MAX_STRING_BYTES} bytes"))), + (Kind::Boolean, _) => return Err(HostError::Type("setBooleanPreference needs true or false".into())), + (Kind::Integer, _) => return Err(HostError::Type("setIntegerPreference needs a whole number".into())), + (Kind::Real, _) => return Err(HostError::Type("setRealPreference needs a finite number".into())), + (Kind::String, _) => return Err(HostError::Type("setStringPreference needs a string".into())), + }; + if key == EXTERNAL_SCRIPT_WARNING { + let ScriptPreference::Boolean(on) = value else { + return Err(HostError::Type(format!("{EXTERNAL_SCRIPT_WARNING} is set with setBooleanPreference"))); + }; + return set_warning(h, on); + } + let mut s = h.session.borrow_mut(); + let store = &mut s.prefs.script_preferences; + if store.get(&key) == Some(&value) { + return Ok(Data::Undefined); + } + let total: usize = store.iter().filter(|(k, _)| **k != key).map(|(k, v)| size(k, v)).sum(); + let count = store.len() + usize::from(!store.contains_key(&key)); + if count > MAX_KEYS { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_KEYS} keys"))); + } + if total + size(&key, &value) > MAX_TOTAL_BYTES { + return Err(HostError::Range(format!("app.preferences holds at most {MAX_TOTAL_BYTES} bytes"))); + } + store.insert(key, value); + Ok(Data::Undefined) +} + +/// Sets `showExternalScriptWarning` in the run's preferences: on at once, and off only after the +/// person answers Yes to [`WARNING_OFF_QUESTION`] ([`crate::Session::script_answer`] sets it). With +/// nobody to ask, turning it off throws and changes nothing. Scripts cannot run `prefs.set`; the +/// run's preferences are put back when the run fails and merged into the app's when it ends. +fn set_warning(h: &Host, on: bool) -> Answer { + if on || !h.session.borrow().prefs.show_external_script_warning { + h.session.borrow_mut().prefs.show_external_script_warning = on; + return Ok(Data::Undefined); + } + let question = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) { + return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into())); + } + Err(HostError::Wait) +} + +fn remove(h: &Host, a: &[Data]) -> Answer { + let key = key_of(a)?; + if key == EXTERNAL_SCRIPT_WARNING { + h.session.borrow_mut().prefs.show_external_script_warning = true; + } else if h.session.borrow().prefs.script_preferences.contains_key(key) { + h.session.borrow_mut().prefs.script_preferences.remove(key); + } + Ok(Data::Undefined) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..33b19dd046 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -542,19 +542,35 @@ impl Choices { } /// The preferences after a run: `current`, the session's, which the app may have changed while the -/// run went on, with each preference the run changed from `start` set to the run's value. +/// run went on, with each preference the run changed from `start` set to the run's value. A +/// preference the run emptied, which is then left out of the saved form, is left out of the result. +/// The values scripts store with `app.preferences` are merged the same way one key at a time. fn merged_prefs(start: &crate::Prefs, run: &crate::Prefs, current: &crate::Prefs) -> crate::Prefs { - let (Ok(Value::Object(start)), Ok(Value::Object(run)), Ok(Value::Object(mut out))) = + const SCRIPT_KEYS: &str = "scriptPreferences"; + let (Ok(Value::Object(start_json)), Ok(Value::Object(run_json)), Ok(Value::Object(mut out))) = (serde_json::to_value(start), serde_json::to_value(run), serde_json::to_value(current)) else { return current.clone(); }; - for (key, value) in run { - if start.get(&key) != Some(&value) { + for key in start_json.keys().filter(|k| *k != SCRIPT_KEYS && !run_json.contains_key(*k)) { + out.remove(key); + } + for (key, value) in run_json { + if key != SCRIPT_KEYS && start_json.get(&key) != Some(&value) { out.insert(key, value); } } - serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()) + let mut merged: crate::Prefs = serde_json::from_value(Value::Object(out)).unwrap_or_else(|_| current.clone()); + let script = &mut merged.script_preferences; + for key in start.script_preferences.keys().filter(|k| !run.script_preferences.contains_key(*k)) { + script.remove(key); + } + for (key, value) in &run.script_preferences { + if start.script_preferences.get(key) != Some(value) { + script.insert(key.clone(), value.clone()); + } + } + merged } impl World { @@ -1840,10 +1856,19 @@ impl Session { /// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`] /// goes on from the call. → false when nothing waits, the answer is for another kind of - /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. + /// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. Yes to a confirm the + /// app opened for the script ([`dialogs::Dialogs::ask`]) also does what it asked. pub fn script_answer(&mut self, answer: DialogAnswer) -> bool { let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; - with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) + with_job(k, |j| { + let given = j.host.dialogs.answer(&mut j.realm, answer); + // Between slices the run's preferences are in its working copy. + if let Some(dialogs::OnYes::ExternalScriptWarningOff) = j.host.dialogs.take_approved() { + j.world.choices.prefs.show_external_script_warning = false; + } + given + }) + .unwrap_or(false) } /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..d52d8ae202 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_prefs; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs new file mode 100644 index 0000000000..12edc6d3c8 --- /dev/null +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -0,0 +1,452 @@ +//! The script object model: `app.preferences`, the matrix functions of `app` and `app.copy`, +//! `app.cut` and `app.paste`. + +use serde_json::{Value, json}; + +use crate::script::dom::preferences::{MAX_KEYS, MAX_STRING_BYTES, MAX_TOTAL_BYTES, WARNING_OFF_NEEDS_A_PERSON, WARNING_OFF_QUESTION}; +use crate::script::{DialogAnswer, DialogKind, ScriptDialog}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn stored(s: &Session, key: &str) -> Option { + s.prefs.script_preferences.get(key).cloned() +} + +#[test] +fn show_external_jsx_warning_is_the_external_script_warning() { + let mut s = Session::new(); + assert!(s.prefs.show_external_script_warning); + let journal = s.journal.len(); + let out = log( + &mut s, + "var p = app.preferences; vc.log(p.typename); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));\ + vc.log(p.getIntegerPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!("Preferences"), json!(true), json!(1)]); + // A preference is not a command, so the journal has no entry for the run. + assert_eq!(s.journal.len(), journal); + assert!(s.prefs.script_preferences.is_empty()); + assert!(failure(&mut s, "app.preferences.setIntegerPreference('ShowExternalJSXWarning', 1);").contains("setBooleanPreference")); + // Turned off by the person, a script reads it as off and can turn it back on, or remove it. + s.prefs.show_external_script_warning = false; + let out = log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log(p.getBooleanPreference('ShowExternalJSXWarning')); p.setBooleanPreference('ShowExternalJSXWarning', true);", + ); + assert_eq!(out, vec![json!(false)]); + assert!(s.prefs.show_external_script_warning); + s.prefs.show_external_script_warning = false; + log(&mut s, "app.preferences.removePreference('ShowExternalJSXWarning');"); + assert!(s.prefs.show_external_script_warning); +} + +/// A run with nobody to ask cannot turn the warning off, even with a Yes in `answers`. +#[test] +fn a_run_without_a_person_cannot_turn_the_warning_off() { + let mut s = Session::new(); + let off = "app.preferences.setBooleanPreference('ShowExternalJSXWarning', false);"; + assert!(failure(&mut s, off).contains(WARNING_OFF_NEEDS_A_PERSON)); + assert!(s.prefs.show_external_script_warning); + let r = s.execute("script.run", &json!({"source": off, "name": "t.js", "answers": [{"kind": "confirm", "value": true}]})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains(WARNING_OFF_NEEDS_A_PERSON)), "{r:?}"); + assert!(s.prefs.show_external_script_warning); + let caught = log(&mut s, &format!("try {{ {off} }} catch (e) {{ vc.log(e.message); }}")); + assert_eq!(caught, vec![json!(WARNING_OFF_NEEDS_A_PERSON)]); + assert!(s.prefs.show_external_script_warning); +} + +/// A run in the app, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +const ASK_OFF: &str = "var p = app.preferences; var r = p.setBooleanPreference('ShowExternalJSXWarning', false);\ + vc.log([r === undefined, p.getBooleanPreference('ShowExternalJSXWarning')]);"; + +#[test] +fn yes_to_the_confirm_turns_the_warning_off() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + let want = ScriptDialog { + kind: DialogKind::Confirm, + message: WARNING_OFF_QUESTION.into(), + title: None, + error_icon: false, + no_as_default: true, + preset: String::new(), + }; + assert_eq!(s.script_dialog(), Some(want)); + assert!(s.prefs.show_external_script_warning, "nothing changes while the confirm waits"); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(r["dialogs"][0]["answer"], true); + assert!(!s.prefs.show_external_script_warning); +} + +#[test] +fn turning_the_warning_on_after_yes_keeps_it_on() { + let mut s = Session::new(); + framed( + &mut s, + &format!("{ASK_OFF} p.setBooleanPreference('ShowExternalJSXWarning', true); vc.log(p.getBooleanPreference('ShowExternalJSXWarning'));"), + ); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, false], true]), "the script sees the answer at once"); + assert!(s.prefs.show_external_script_warning, "the script's last write is what the run keeps"); +} + +#[test] +fn no_to_the_confirm_or_stop_leaves_the_warning_on() { + let mut s = Session::new(); + framed(&mut s, ASK_OFF); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + assert!(s.prefs.show_external_script_warning); + framed(&mut s, ASK_OFF); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(!s.script_answer(DialogAnswer::Confirm(true))); + assert!(s.script_pump().unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); + // Yes in a run that then fails is put back with the rest of the run. + framed(&mut s, &format!("{ASK_OFF} throw new Error('stop');")); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert!(pump(&mut s).unwrap().is_err()); + assert!(s.prefs.show_external_script_warning); +} + +/// Asking to show no dialogs does not skip the confirm, and a call from a callback, where no dialog +/// can open, throws. +#[test] +fn the_confirm_cannot_be_skipped() { + let mut s = Session::new(); + framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}")); + assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); + assert!(s.script_answer(DialogAnswer::Confirm(false))); + assert!(pump(&mut s).unwrap().is_ok()); + assert!(s.prefs.show_external_script_warning); + let callback = "[1].forEach(function () { app.preferences.setBooleanPreference('ShowExternalJSXWarning', false); });"; + assert_eq!(run(&mut s, callback).unwrap()["running"], true); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains(WARNING_OFF_NEEDS_A_PERSON), "{e}"); + assert!(s.prefs.show_external_script_warning); +} + +#[test] +fn other_keys_keep_their_type_across_runs_and_a_restart() { + let mut s = Session::new(); + log( + &mut s, + "var p = app.preferences; p.setBooleanPreference('my/flag', true); p.setIntegerPreference('count', -7);\ + p.setRealPreference('ratio', 0.25); p.setStringPreference('name', 'Ünïcode \\u2713');", + ); + assert_eq!(stored(&s, "my/flag"), Some(ScriptPreference::Boolean(true))); + assert_eq!(stored(&s, "count"), Some(ScriptPreference::Integer(-7))); + assert_eq!(stored(&s, "ratio"), Some(ScriptPreference::Real(0.25))); + assert_eq!(stored(&s, "name"), Some(ScriptPreference::String("Ünïcode \u{2713}".into()))); + // The preferences as the app saves them, read into a new session. + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut t = Session::new(); + t.prefs = serde_json::from_str(&saved).unwrap(); + let out = log( + &mut t, + "var p = app.preferences; vc.log(p.getBooleanPreference('my/flag')); vc.log(p.getIntegerPreference('count'));\ + vc.log(p.getRealPreference('ratio')); vc.log(p.getStringPreference('name'));", + ); + assert_eq!(out, vec![json!(true), json!(-7), json!(0.25), json!("Ünïcode \u{2713}")]); +} + +#[test] +fn missing_keys_read_as_empty_values_and_getters_convert() { + let mut s = Session::new(); + let mut out = log( + &mut s, + "var p = app.preferences; vc.log([p.getBooleanPreference('none'), p.getIntegerPreference('none'),\ + p.getRealPreference('none'), p.getStringPreference('none')]);\ + p.setRealPreference('r', -2.75); p.setStringPreference('t', ' 12.5 '); p.setStringPreference('x', 'abc');\ + p.setBooleanPreference('b', true); p.setIntegerPreference('i', 0);\ + vc.log([p.getIntegerPreference('r'), p.getStringPreference('r'), p.getBooleanPreference('r')]);\ + vc.log([p.getRealPreference('t'), p.getIntegerPreference('t'), p.getBooleanPreference('t')]);\ + vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\ + vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\ + var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\ + p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));", + ); + assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN"))); + assert_eq!( + out, + vec![json!([false, 0, 0, ""]), json!([-2, "-2.75", true]), json!([12.5, 12, true]), json!([true, 0]), json!(["true", 1, false, "0"])] + ); +} + +#[test] +fn bad_arguments_throw_and_store_nothing() { + let mut s = Session::new(); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.preferences.setIntegerPreference('k', 1.5);", "whole number"), + ("app.preferences.setIntegerPreference('k', 1e300);", "whole number"), + ("app.preferences.setIntegerPreference('k', '3');", "whole number"), + ("app.preferences.setRealPreference('k', Infinity);", "finite number"), + ("app.preferences.setRealPreference('k', NaN);", "finite number"), + ("app.preferences.setBooleanPreference('k', 1);", "true or false"), + ("app.preferences.setStringPreference('k', 5);", "a string"), + ("app.preferences.setStringPreference(5, 'v');", "key must be a string"), + ("app.preferences.getBooleanPreference();", "key must be a string"), + ("app.preferences.setStringPreference('', 'v');", "1 to 256"), + ("app.preferences.setStringPreference(new Array(258).join('k'), 'v');", "1 to 256"), + ("app.preferences.setStringPreference('a\\u0000b', 'v');", "control characters"), + ("app.preferences.setStringPreference('k', new Array(65538).join('v'));", "at most 65536 bytes"), + ("var f = app.preferences.getBooleanPreference; f.call({}, 'k');", "not a Preferences"), + ("Preferences.prototype.setBooleanPreference('k', true);", "not a Preferences"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.script_preferences.is_empty()); + // A key of exactly 256 characters and a value of exactly the limit are taken. + log(&mut s, "app.preferences.setStringPreference(new Array(257).join('k'), new Array(65537).join('v'));"); + assert_eq!(stored(&s, &"k".repeat(256)), Some(ScriptPreference::String("v".repeat(MAX_STRING_BYTES)))); +} + +#[test] +fn the_store_limits_its_keys() { + let mut s = Session::new(); + for i in 0..MAX_KEYS { + s.prefs.script_preferences.insert(format!("k{i}"), ScriptPreference::Integer(1)); + } + assert!(failure(&mut s, "app.preferences.setIntegerPreference('one more', 1);").contains("at most 4096 keys")); + assert_eq!(s.prefs.script_preferences.len(), MAX_KEYS); + // A key already stored can still change. + log(&mut s, "app.preferences.setIntegerPreference('k0', 2);"); + assert_eq!(stored(&s, "k0"), Some(ScriptPreference::Integer(2))); +} + +#[test] +fn the_store_limits_its_bytes() { + let mut s = Session::new(); + let big = "v".repeat(MAX_STRING_BYTES); + for i in 0..MAX_TOTAL_BYTES / MAX_STRING_BYTES - 1 { + s.prefs.script_preferences.insert(format!("{i:02}"), ScriptPreference::String(big.clone())); + } + let e = failure(&mut s, "app.preferences.setStringPreference('last', new Array(65537).join('v'));"); + assert!(e.contains("at most 1048576 bytes"), "{e}"); + assert_eq!(stored(&s, "last"), None); + // Replacing a stored value counts the new value instead of the old one. + log(&mut s, "app.preferences.setStringPreference('00', new Array(65537).join('w'));"); + assert_eq!(stored(&s, "00"), Some(ScriptPreference::String("w".repeat(MAX_STRING_BYTES)))); +} + +#[test] +fn a_failed_run_puts_the_store_back_and_removing_the_last_key_empties_it() { + let mut s = Session::new(); + log(&mut s, "app.preferences.setIntegerPreference('keep', 1);"); + let e = failure(&mut s, "app.preferences.setIntegerPreference('keep', 2); app.preferences.setRealPreference('new', 1); throw new Error('stop');"); + assert!(e.contains("stop")); + assert_eq!(stored(&s, "keep"), Some(ScriptPreference::Integer(1))); + assert_eq!(stored(&s, "new"), None); + let out = log( + &mut s, + "var p = app.preferences; p.removePreference('missing'); p.removePreference('keep');\ + vc.log(p.getIntegerPreference('keep'));", + ); + assert_eq!(out, vec![json!(0)]); + assert!(s.prefs.script_preferences.is_empty()); +} + +#[test] +fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { + let mut s = Session::new(); + s.prefs.script_preferences.insert("gone".into(), ScriptPreference::Integer(1)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(1)); + s.script_frames = true; + let source = "var p = app.preferences; p.removePreference('gone'); p.setIntegerPreference('mine', 2);\ + for (var i = 0; i < 2000000; i++) {}"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); + s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true)); + s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3)); + while s.script_pump().is_none() {} + let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); + assert_eq!( + keys, + vec![("kept", &ScriptPreference::Integer(3)), ("mine", &ScriptPreference::Integer(2)), ("theirs", &ScriptPreference::Boolean(true))] + ); +} + +#[test] +fn matrix_functions_give_new_records() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.typename, m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + vc.log(v(app.getIdentityMatrix())); vc.log(v(app.getTranslationMatrix(100, 200))); vc.log(v(app.getTranslationMatrix()));\ + vc.log(v(app.getScaleMatrix(60))); vc.log(v(app.getScaleMatrix(50, 200))); vc.log(v(app.getScaleMatrix()));\ + vc.log(v(app.getRotationMatrix(90))); vc.log(v(app.getRotationMatrix(-270))); vc.log(v(app.getRotationMatrix()));", + ); + assert_eq!( + out, + vec![ + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 100, 200]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0.6, 0, 0, 0.6, 0, 0]), + json!(["Matrix", 0.5, 0, 0, 2, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 0, 1, -1, 0, 0, 0]), + json!(["Matrix", 1, 0, 0, 1, 0, 0]), + ] + ); + let r = log(&mut s, "var m = app.getRotationMatrix(30); vc.log([m.mValueA, m.mValueB, m.mValueC, m.mValueD]);"); + let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + assert_eq!(r, vec![json!([c, sn, -sn, c])]); +} + +#[test] +fn concatenation_applies_the_first_matrix_first() { + let mut s = Session::new(); + // As PDF `cm` operators compose (ISO 32000-1, 8.3.4): [x y 1] × M × N. + // M = [2 0 0 3 5 7] then N = [0 1 -1 0 10 20]: (x, y) → (2x + 5, 3y + 7) → (-(3y + 7) + 10, 2x + 5 + 20). + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + var m = {mValueA: 2, mValueB: 0, mValueC: 0, mValueD: 3, mValueTX: 5, mValueTY: 7};\ + var n = {mValueA: 0, mValueB: 1, mValueC: -1, mValueD: 0, mValueTX: 10, mValueTY: 20};\ + var c = app.concatenateMatrix(m, n); vc.log(v(c)); vc.log(v(m)); vc.log(c === m);\ + vc.log(v(app.concatenateTranslationMatrix(m, 1, 2))); vc.log(v(app.concatenateScaleMatrix(m, 50)));\ + vc.log(v(app.concatenateRotationMatrix(m, 90)));\ + vc.log(app.isEqualMatrix(app.concatenateRotationMatrix(m, 90), app.concatenateMatrix(m, app.getRotationMatrix(90))));", + ); + assert_eq!( + out, + vec![ + json!([0, 2, -3, 0, 3, 25]), + json!([2, 0, 0, 3, 5, 7]), + json!(false), + json!([2, 0, 0, 3, 6, 9]), + json!([1, 0, 0, 1.5, 2.5, 3.5]), + json!([0, 2, -3, 0, -7, 5]), + json!(true), + ] + ); +} + +#[test] +fn inverse_singular_and_equal_matrices() { + let mut s = Session::new(); + let out = log( + &mut s, + "var m = app.concatenateTranslationMatrix(app.concatenateRotationMatrix(app.getScaleMatrix(40, 250), 33), 17, -4);\ + var i = app.invertMatrix(m), back = app.concatenateMatrix(m, i), id = app.getIdentityMatrix();\ + var d = [back.mValueA - 1, back.mValueB, back.mValueC, back.mValueD - 1, back.mValueTX, back.mValueTY];\ + vc.log(Math.max.apply(null, d.map(Math.abs)) < 1e-12);\ + vc.log(app.isSingularMatrix(app.getScaleMatrix(0, 100))); vc.log(app.isSingularMatrix(m));\ + vc.log(app.isEqualMatrix(id, app.getRotationMatrix(360))); vc.log(app.isEqualMatrix(id, app.getTranslationMatrix(0, 1e-300)));\ + var tiny = app.getScaleMatrix(1e-198, 1e202), t = app.invertMatrix(tiny);\ + function near(v, w) { return Math.abs(v / w - 1) < 1e-12; }\ + vc.log([app.isSingularMatrix(tiny), near(t.mValueA, 1e200), near(t.mValueD, 1e-200), t.mValueB, t.mValueC]);\ + vc.log(near(app.invertMatrix(app.getScaleMatrix(1e202)).mValueA, 1e-200));\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: 0, mValueTY: 0}; }\ + var wide = mat([1e308, 0, 1e308, 1e-100]), w = app.invertMatrix(wide);\ + vc.log([app.isSingularMatrix(wide), near(w.mValueA, 1e-308), near(w.mValueC, -1e100), near(w.mValueD, 1e100)]);\ + var thin = app.invertMatrix(mat([1e300, 0, 1e300, 5e-24]));\ + vc.log([near(thin.mValueA, 1e-300), near(thin.mValueC, -2e23), near(thin.mValueD, 2e23)]);\ + var close = mat([7207, 7440, 382, 394.34993756070486]), ci = app.invertMatrix(close);\ + vc.log([app.isSingularMatrix(close), app.isSingularMatrix(mat([6, 4, 3, 2])), near(ci.mValueD, 7207 / -8.009237717487849e-11)]);\ + var far = mat([1e-100, 1e-100, 1e-100, 1e-100 + 1e-115]); far.mValueTX = 1e200; far.mValueTY = 1e200;\ + var fi = app.invertMatrix(far); vc.log([Math.abs(fi.mValueTX / -1e300 - 1) < 1e-6, fi.mValueTY]);", + ); + assert_eq!(out[..5], [json!(true), json!(true), json!(false), json!(true), json!(false)]); + assert_eq!(out[5], json!([false, true, true, 0, 0])); + assert_eq!(out[6], json!(true)); + assert_eq!(out[7], json!([false, true, true, true])); + assert_eq!(out[8], json!([true, true, true])); + assert_eq!(out[9], json!([false, true, true])); + assert_eq!(out[10], json!([true, 0])); + let mut wrong = Vec::new(); + for (source, message) in [ + ("app.invertMatrix(app.getScaleMatrix(100, 0));", "singular"), + ("app.getTranslationMatrix(NaN);", "not a finite number"), + ("app.getScaleMatrix('50');", "scaleX must be a finite number"), + ("app.getRotationMatrix(Infinity);", "not a finite number"), + ("app.getRotationMatrix(null);", "angle must be a finite number"), + ("app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1});", "secondMatrix must be a Matrix"), + ( + "app.concatenateMatrix(app.getIdentityMatrix(), {mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: '0', mValueTY: 0});", + "secondMatrix must be a Matrix", + ), + ("app.invertMatrix(5);", "matrix must be a Matrix"), + ("var m = app.getIdentityMatrix(); m.mValueTX = Infinity; app.isSingularMatrix(m);", "not a finite number"), + ("app.concatenateScaleMatrix(app.getScaleMatrix(1e300), 1e300);", "too large"), + ] { + match run(&mut s, source) { + Err(e) if e.to_string().contains(message) => {} + r => wrong.push(format!("{source}: {r:?}")), + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn copy_and_paste_run_as_one_undo_step() { + let mut s = Session::new(); + assert!(failure(&mut s, "app.paste();").contains("No active document")); + log(&mut s, "app.copy(); app.cut();"); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + // Nothing selected and the clipboard empty: nothing happens and no step is added. + log(&mut s, "app.copy(); app.cut(); app.paste();"); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + assert!(s.clipboard.is_empty()); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + let out = log(&mut s, "app.copy(); app.paste(); app.paste(); vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!(3)]); + assert_eq!(s.active().unwrap().history.undo.len(), steps + 1); + // A cut in a run that fails is put back. + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let steps = s.active().unwrap().history.undo.len(); + assert!(failure(&mut s, "app.cut(); throw new Error('stop');").contains("stop")); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); + assert_eq!(s.active().unwrap().history.undo.len(), steps); + log(&mut s, "app.cut();"); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_none()); +} diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..9f3d94535d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -28,6 +28,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; @@ -259,10 +260,17 @@ fn answer_button(ui: &mut egui::Ui, label: &str, default: bool) -> bool { if default { widgets::primary_button_enabled(ui, label, true).clicked() } else { widgets::secondary_button(ui, label).clicked() } } +/// The dialog's message: a script's own text as it is, and the question the app asks before a +/// script turns off the external script warning in the current language. +fn notice_message(d: &Dialog) -> String { + let message = d.str("message"); + if message == WARNING_OFF_QUESTION { crate::i18n::msg(&message) } else { message } +} + fn notice_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { let t = Tokens::get(ui.ctx()); let kind = d.str("kind"); - let message = shown_text(&d.str("message"), true); + let message = shown_text(¬ice_message(d), true); ui.horizontal_top(|ui| { if d.bool("errorIcon") { ui.label(egui::RichText::new("!").font(theme::semibold(22.0)).color(t.error)); diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..b4d8fc9c05 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2676,6 +2676,37 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`, + `getIntegerPreference(key)`, `getRealPreference(key)`, `getStringPreference(key)`, the four matching `set…(key, + value)` and `removePreference(key)`. The key `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`. + Setting it to `true` or removing it turns the warning on. VectorCraft's own rule: setting it to `false` while the + warning is on shows a confirm, with No as its default, and turns the warning off only after Yes; with nobody to ask + (a run with `script.run` outside the app, or a call from a callback of a built-in function) it throws an error that + names `ShowExternalJSXWarning` and changes nothing, and `answers` cannot answer that confirm. Other keys are + stored with the preferences under `scriptPreferences`, with the type they were set as, and are kept across runs and restarts; a run that fails or is stopped puts them back. + VectorCraft's own rules: a key that was never set reads as `false`, `0`, `0` or `""`; a getter of another type + converts the value as `Boolean`, `Number` and `String` do, and `getIntegerPreference` drops the fraction and gives + `0` for a value that is not a number. A key has 1 to 256 characters and no control characters, a string value at + most 65,536 bytes, and the store at most 4,096 keys and 1,048,576 bytes (each value that is not a string counts 8); + `setIntegerPreference` takes a whole number within ±2^53 and `setRealPreference` a finite number. A value of the + wrong type or past a limit throws an error and stores nothing, and removing a key that is not stored does nothing. +- `app.getIdentityMatrix()`, `getTranslationMatrix(deltaX?, deltaY?)` (points), `getScaleMatrix(scaleX?, scaleY?)` + (percent), `getRotationMatrix(angle?)` (degrees, counterclockwise), `concatenateMatrix(matrix, secondMatrix)`, + `concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`, + `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and + `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain + objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each + function gives a new record and leaves the ones passed to it unchanged. A record maps `(x, y)` to + `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own + rules: `concatenateMatrix(m, n)` applies `m` and then `n`, and the other `concatenate…` functions apply the record + and then the transformation they make; a left-out move or angle is 0, a left-out `scaleX` is 100 and a left-out + `scaleY` is `scaleX`; quarter turns are exact; a matrix whose determinant is 0 is singular, and `invertMatrix` of one + throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`, + and a result too large for a number throws a `RangeError`. +- `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run + `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected + `copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws + `No active document`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -2790,7 +2821,9 @@ while the run went on keeps that change. On an uncaught error, a limit or `scrip session go back to their state before the run. A script can write files through the commands it runs, such as export commands. A file written before the run failed stays on disk, and the error names it. A run from the menu shows a warning first, unless you ticked Do not show this warning again or set the preference -`showExternalScriptWarning` to false. +`showExternalScriptWarning` to false. A script asks for it with +`app.preferences.setBooleanPreference("ShowExternalJSXWarning", false)`, which turns the warning off only after you +answer Yes. While a script runs, every other command that changes anything ends with the error `a script is running: stop it or wait for it to finish`. MCP reports that error as JSON-RPC error `-32003`. `script.stop {}` stops the run and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..837e8ef276 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6b2a84304ba9bcc163406631f53dbbe9d2bd3a85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:35:09 -0800 Subject: [PATCH 006/533] Scripts: hasSelectedArtwork keeps the rest of the selection, artboards stay on the canvas - hasSelectedArtwork = false deselects only the layer's art with select.toggle, and true adds its art with select.add, so selected ruler guides and art on other layers stay selected. A layer with nothing to deselect or add runs no command. - A compound path's pathItems report the typename PathItems. - An artboard rectangle with an edge more than 4,000,000 points from the document origin throws before artboard.setProps or artboard.new runs. - script.run's activeArtboards gives each document's active artboard as the run leaves it, also when the chosen artboard was deleted later in the run. - A layer's or group's pageItems, groupItems and compoundPathItems, and the document's groupItems and compoundPathItems, keep their last list while the document is unchanged, so indexed reads in a loop do not rebuild it each time. A new list is charged by the objects it looks at. - object.newGroup's help says index 0 goes directly above the clipping path in a clipping layer or group. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/layers.rs | 106 +++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 76 ++++++++++++++++ docs/mcp.md | 15 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 162 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index dab3a0378c..8d17cc0a72 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "Group", [], None, - "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom; default: on top)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7bfecbb264..fadaeb133d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -94,9 +94,11 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, - /// The documents whose active artboard `setActiveArtboardIndex` changed: each one's uid and - /// the artboard's id. - pub(super) active_artboards: RefCell>, + /// The last list of art one of [`layers`]' collections gave, kept while its document is + /// unchanged. + art: RefCell>, + /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. + pub(super) active_artboards: RefCell>, } impl State { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index a6b165fbef..91c7bc4a03 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -30,13 +30,16 @@ //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report //! lists it in `activeArtboards` for the app to show. +use std::rc::Rc; +use std::sync::Arc; + use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, number, on_doc, - page_items, placement_of, property, set_selection, text, typename, whole, with_doc, + page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -272,36 +275,43 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) } -/// `hasSelectedArtwork = false` deselects the layer's art; `true` adds its visible, unlocked art -/// to the selection. +/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its +/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays, +/// and no command runs when there is nothing to deselect or add. fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let ids = with_doc(h, doc, |_, st| { + let (ids, total) = with_doc(h, doc, |_, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); - let mut ids: Vec = st.selection.objects.clone(); - if on { - let locks = st.doc.locked_artboards(); - let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); - let mut have: std::collections::HashSet = ids.iter().copied().collect(); - for o in art { - if ids.len() > MAX_LISTED { - break; - } - if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { - have.insert(o); - ids.push(o); - } - } - } else { - ids.retain(|o| !inside(o)); + let selected = &st.selection.objects; + if !on { + return (selected.iter().copied().filter(inside).collect::>(), 0); } - ids + let locks = st.doc.locked_artboards(); + let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); + let mut have: std::collections::HashSet = selected.iter().copied().collect(); + let mut ids = Vec::new(); + for o in art { + if selected.len() + ids.len() > MAX_LISTED { + break; + } + if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + have.insert(o); + ids.push(o); + } + } + let total = selected.len() + ids.len(); + (ids, total) }); - if ids.len() > MAX_LISTED { + if total > MAX_LISTED { return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); } - set_selection(h, doc, ids) + if ids.is_empty() { + return Ok(Data::Undefined); + } + let command_id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { @@ -558,17 +568,36 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { } } +/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, +/// and the ids it listed then. +pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); + /// The objects of `kind` in `container` (directly), or in the whole document at any depth, in -/// paint order. -fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result> { +/// paint order. The last list is kept while the document is unchanged, and each new one is charged +/// by the objects it looks at. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + if let Some((uid, doc, k, c, ids)) = &*h.dom.art.borrow() + && *uid == st.uid + && Arc::ptr_eq(doc, &st.doc) + && *k == kind as u8 + && *c == container + { + return Ok(ids.clone()); + } let ids: Vec = match container { None => { let all = page_items(h, st); h.charge_call(all.len() as u64)?; all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() } - Some(c) => st.doc.node(c).and_then(|n| n.children()).into_iter().flatten().filter(|n| kind.holds(n)).map(|n| n.id).collect(), + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } }; + let ids = Rc::new(ids); + *h.dom.art.borrow_mut() = Some((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); Ok(ids) } @@ -709,8 +738,10 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - art_scope(h, arg(a, 0), kind.class())?; - Ok(text(kind.class())) + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + // A compound path's `pathItems` are its `PageItems`: it holds only paths. + let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); + Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -956,6 +987,9 @@ fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result super::MAX_SIZE || rect.height() > super::MAX_SIZE { return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); } + if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| v.abs() > crate::MAX_COORD) { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } Ok(rect) } @@ -1199,26 +1233,24 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { let mut s = h.session.borrow_mut(); let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); - let id = st.active_artboard; drop(s); let mut moved = h.dom.active_artboards.borrow_mut(); - moved.retain(|(u, _)| *u != doc.uid); - if let Some(id) = id { - moved.push((doc.uid, id)); + if !moved.contains(&doc.uid) { + moved.push(doc.uid); } } Ok(Data::Undefined) } /// The documents whose active artboard the run changed, as `script.run`'s report gives them: -/// `[{document, artboard}]`, each an index, or `None` when there are none. -pub(crate) fn active_artboards(moved: &[(u64, u32)], docs: &[DocState]) -> Option { +/// `[{document, artboard}]`, each an index, with the active artboard each document has at the end +/// of the run, or `None` when there are none. +pub(crate) fn active_artboards(moved: &[u64], docs: &[DocState]) -> Option { let list: Vec = moved .iter() - .filter_map(|(uid, id)| { + .filter_map(|uid| { let document = docs.iter().position(|d| d.uid == *uid)?; - let artboard = board_index(&docs[document], *id)?; - Some(json!({"document": document, "artboard": artboard})) + Some(json!({"document": document, "artboard": active_artboard(&docs[document])})) }) .collect(); (!list.is_empty()).then_some(Value::Array(list)) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 2b3920f3d0..f9e42377db 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1077,6 +1077,31 @@ fn group_items_list_every_depth_and_clipped_toggles_the_mask() { assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); } +#[test] +fn a_compound_paths_path_items_are_path_items() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\ + vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename);", + ); + assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); +} + +#[test] +fn art_collections_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[2].typename); vc.log(g.length);\ + p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", + ); + assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); @@ -1193,6 +1218,35 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +#[test] +fn the_report_gives_the_active_artboard_the_run_leaves() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.add([800, 300, 900, 100]);").unwrap(); + // The chosen artboard is deleted later in the run: the report gives the one active at the end. + let r = + run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(2); A.remove(2); vc.log(A.getActiveArtboardIndex());").unwrap(); + let active = r["log"][0].clone(); + assert!(active.as_u64().is_some_and(|i| i < 2), "{r}"); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); +} + +#[test] +fn an_artboard_rectangle_stays_inside_the_canvas() { + let (mut s, _, _) = doc(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + // Each number is within the coordinate range, but the right edge is past the canvas. + for src in [ + "app.activeDocument.artboards[0].artboardRect = [3999950, 0, 4000100, -100];", + "app.activeDocument.artboards.add([-4000100, 0, -3999950, -100]);", + "app.activeDocument.artboards.insert([0, 4000600, 100, 4000500], 0);", + ] { + assert!(failure(&mut s, src).contains("outside the canvas"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn has_selected_artwork_selects_and_deselects_a_layers_art() { let (mut s, a, b) = doc(); @@ -1210,6 +1264,28 @@ fn has_selected_artwork_selects_and_deselects_a_layers_art() { assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); } +#[test] +fn has_selected_artwork_keeps_the_rest_of_the_selection() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // An empty layer has nothing to deselect or add: the selected guide stays. + let steps = undo_steps(&s); + run(&mut s, "var l = app.activeDocument.layers.add(); l.hasSelectedArtwork = false; l.hasSelectedArtwork = true;").unwrap(); + assert_eq!(s.active().unwrap().selection.guides.len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + // Deselecting a layer's art leaves the guide selected, and so does adding it. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = false;").unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.len(), sel.guides.len()), (0, 1)); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&a) && sel.objects.contains(&b)); + assert_eq!(sel.guides.len(), 1); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 7c4c190230..2b6b988f91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2705,27 +2705,32 @@ app through the global object `vc`, and writes to the Script Console and runs ot `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - are its `pageItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past the next layer beside it and any art between them. - `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection, and `false` deselects it. + `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false` + deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer + with nothing to add or deselect runs no command. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection. `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below - its top and each side from 1 to 3,999,856 points. Artboard names are trimmed, cannot be empty and are unique: a name + its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. + Artboard names are trimmed, cannot be empty and are unique: a name another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the - change in `activeArtboards` (`[{document, artboard}]`, both indexes). An index outside the list throws a + change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the + run leaves it). An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. - `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: - the current layer), on top of its contents or at `index` (0 is the bottom), as one undo step named Group, and + the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 + puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. The selection stays as it is. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 29a93c640b..6edddf19b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From 185517dac14d179ab9ec007a2a8b15e5ac33188e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:49:49 -0800 Subject: [PATCH 007/533] Scripts: artboards.insert puts the document back when the reorder fails artboards.add and artboards.insert run artboard.new and artboard.reorder inside one savepoint, as duplicate does for its copy and move. When either command or the selection restore after them fails, the new artboard is removed and the undo history is as it was. --- crates/engine/src/script/dom/layers.rs | 29 ++++++++++++++------------ 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 91c7bc4a03..bd0046a4b4 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1166,7 +1166,7 @@ fn boards_index(h: &Host, a: &[Data]) -> Answer { } /// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with -/// `artboard.reorder`. → the artboard. +/// `artboard.reorder`; when either fails, the document is as it was. → the artboard. fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { let doc = boards_doc(h, a)?; let (r, len, name) = with_doc(h, doc, |_, st| { @@ -1181,18 +1181,21 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { if len >= max { return Err(HostError::Range(format!("a document has at most {max} artboards"))); } - let id = on_doc(h, doc.uid, true, |h| { - let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; - let index = - result_id(&made, "index").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error("the artboard was not made".into()))?; - if let Some(to) = to - && to != index - { - command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; - } - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + let id = super::atomically(h, |h| { + on_doc(h, doc.uid, true, |h| { + let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = result_id(&made, "index") + .and_then(|i| usize::try_from(i).ok()) + .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + }) })?; Ok(board_ref(h, doc.uid, id)) } From fed96731e242d9df4286b258acb1fcd03ea07637 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:10:20 -0800 Subject: [PATCH 008/533] Scripts: Document.placedItems and rasterItems with place, relink, embed and image data Scripts get Document.placedItems and Document.rasterItems, the linked and embedded images of a document, with length, [i], index, getByName and removeAll. PlacedItems.add() gives a PlacedItem whose file, assigned once, places an image linked through file.place. PlacedItem has file, relink(file) (links.relink), embed() (links.embed), matrix and boundingBox. RasterItem has bitsPerChannel, channels, imageColorSpace and transparent, read from the header of the encoded pixels, and colorizedGrayscale, embedded, file, status, matrix and boundingBox. Assigning matrix runs object.transform. The ImageColorSpace and RasterLinkState enumerations are added. A file to place or relink must be a File the script may read, checked as app.open checks its file, of at most 256 MiB, holding an image; its size is read first, and the error does not name a path the script may not read. Reading file of an image linked outside the script's read scope throws Script file access denied. A matrix with a value that is not finite, no area, or a corner outside the canvas throws with nothing changed. After embed() the PlacedItem is stale and rasterItems lists the image under the same id; a missing linked file stays linked and throws. A run keeps at most 1,024 PlacedItems.add() results. contentVariable, trace, colorants, colorize and overprint throw an error that says they are not available yet. --- crates/engine/src/script/dom.rs | 31 +- crates/engine/src/script/dom/images.rs | 672 +++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 415 ++++++++++++ crates/js/src/file_classes.rs | 14 + crates/js/src/host.rs | 6 + crates/js/src/lib.rs | 2 +- docs/mcp.md | 24 + docs/target-app-parity.md | 1 + 9 files changed, 1156 insertions(+), 10 deletions(-) create mode 100644 crates/engine/src/script/dom/images.rs create mode 100644 crates/engine/src/tests/script_dom_images.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..cd96ea46c5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod images; mod save_open; /// The error for a member read or called with no document open. @@ -97,6 +98,8 @@ pub(super) struct State { /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, presets: RefCell>>, + /// What the placed and raster items keep ([`images::State`]). + images: images::State, } impl State { @@ -287,15 +290,22 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result std::result::Result { - let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let Some((class, handle)) = host_ref_parts(d).filter(|(c, _)| ITEM_CLASSES.contains(c)) else { + return Err(HostError::Type("this is not a page item".into())); + }; + let (run, uid, id) = match handle.as_slice() { + [run, uid, high, low] => (*run, *uid, id_of(*high, *low)), + [run, uid, _, _, slot] => (*run, *uid, Some(images::pending_id(h, *run, *uid, *slot)?)), + _ => return Err(HostError::Type("this is not a page item".into())), + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; - if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { return Err(HostError::Error(STALE_ITEM.into())); } Ok(Item { doc, id }) @@ -1593,7 +1603,8 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); - let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); + let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); + let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); let Some(&[run, uid, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); @@ -1807,7 +1818,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1870,6 +1881,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); + document.extend(images::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1933,7 +1945,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| !images::CLASSES.contains(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(images::classes(l)); classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs new file mode 100644 index 0000000000..bf79f77013 --- /dev/null +++ b/crates/engine/src/script/dom/images.rs @@ -0,0 +1,672 @@ +//! Placed and raster art in the script object model: `Document.placedItems` and +//! `Document.rasterItems`, and the members of `PlacedItem` and `RasterItem`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! A `PlacedItem` is an image linked to its file, and a `RasterItem` an image whose pixels are in +//! the document. Placing runs `file.place` with `link`, relinking `links.relink` and embedding +//! `links.embed`, so each joins the run's transaction. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `PlacedItems.add()` gives a placed item with no file. Its `file` may be assigned once, which +//! places the file linked; after that, and on every other placed item, `file` is read-only and +//! `relink(file)` changes it. Every other member of an item with no file throws +//! [`FILE_REQUIRED`]; an item with no file is not in the document and is dropped when the run +//! ends. +//! - A file to place or relink is a `File` the script may read ([`crate::file_access::ScriptGate`]) +//! that holds an image, of at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is. +//! - `PlacedItem.file` throws `Script file access denied`, without the path, when the script may +//! not read the linked file. +//! - `embed()` turns the placed item into a raster item with the same id: the placed item is stale +//! after it, and `rasterItems` lists the raster item. An image whose file is missing throws +//! [`MISSING_LINK`] and stays linked. +//! - `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent` come from the header of the +//! image's encoded pixels; `transparent` is true for an image with an alpha channel or a +//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only +//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file. +//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of +//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a +//! matrix with no area or one that puts a corner of the image outside the canvas is refused. +//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_geom::{Affine, Point}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; + +use super::{ + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, editable, find_doc, + float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a member of a `PlacedItems.add()` result whose `file` was not assigned. +pub const FILE_REQUIRED: &str = "PlacedItem.file is required"; +/// The error of assigning `file` to a placed item that has one. +pub const FILE_READ_ONLY: &str = "PlacedItem.file is read-only: use relink"; +/// The error of embedding an image whose linked file cannot be found. +pub const MISSING_LINK: &str = "Linked image is missing"; +/// The error of placing or relinking a file that is not an image. +pub const NOT_AN_IMAGE: &str = "The file is not an image"; +/// The largest file a script places or relinks, in bytes. +pub const MAX_PLACED_BYTES: u64 = 256 << 20; +/// The most `PlacedItems.add()` results one run keeps. +pub const MAX_PENDING: usize = 1024; +/// The error of the `matrix` of an image drawn distorted. +const DISTORTED: &str = "the image is distorted and has no matrix"; +/// The smallest determinant a `matrix` takes, in square points a square pixel. +const MIN_DETERMINANT: f64 = 1e-12; +/// The members of a `Matrix` record, in the order of an affine matrix's six numbers. +const MATRIX_KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ImageColorSpace", &["CMYK", "DeviceN", "Grayscale", "Indexed", "LAB", "RGB", "Separation"]), + ("RasterLinkState", &["DATAFROMFILE", "DATAMODIFIED", "NODATA"]), +]; + +/// The classes this module defines, in place of the plain page item classes. +pub(super) const CLASSES: &[&str] = &["PlacedItem", "RasterItem"]; + +/// A document's uid, the document as it was, and the ids of its linked and embedded images then. +type Lists = (u64, Arc, Rc>, Rc>); + +/// What a run keeps for placed and raster items: the `PlacedItems.add()` results and the last +/// lists of a document's images. +#[derive(Default)] +pub(super) struct State { + pending: RefCell>, + lists: RefCell>, +} + +/// A `PlacedItems.add()` result: its document, and its image once `file` placed one. +struct Pending { + uid: u64, + bound: Option, +} + +/// The slot of a `PlacedItems.add()` result in this run, from its handle. +fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let stale = || HostError::Error(STALE_ITEM.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let k = whole(slot).and_then(|k| usize::try_from(k).ok()).ok_or_else(stale)?; + let uid = whole(uid).ok_or_else(stale)?; + match h.dom.images.pending.borrow().get(k) { + Some(p) if p.uid == uid => Ok(k), + _ => Err(stale()), + } +} + +/// The id of the image a `PlacedItems.add()` result placed. +pub(super) fn pending_id(h: &Host, run: f64, uid: f64, slot: f64) -> Result { + let k = slot_of(h, run, uid, slot)?; + match h.dom.images.pending.borrow().get(k).and_then(|p| p.bound) { + Some(id) => Ok(id), + None => Err(HostError::Error(FILE_REQUIRED.into())), + } +} + +/// The handle's run, uid and slot when `d` is a `PlacedItems.add()` result. Its handle has five +/// numbers, where a page item's has four. +fn pending_handle(d: &Data) -> Option<[f64; 3]> { + match host_ref_parts(d) { + Some(("PlacedItem", handle)) => match handle.as_slice() { + [run, uid, _, _, slot] => Some([*run, *uid, *slot]), + _ => None, + }, + _ => None, + } +} + +/// The page item handle (run, uid and the two halves of the id) of the image a +/// `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result. +pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, HostError> { + let Some([run, uid, slot]) = pending_handle(d) else { return Ok(None) }; + let [high, low] = super::id_parts(pending_id(h, run, uid, slot)?); + Ok(Some([run, uid, high, low])) +} + +/// The ids of a document's linked (`placed`) or embedded images in paint order. +fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { + let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; + if let Some(l) = &*h.dom.images.lists.borrow() + && l.0 == st.uid + && Arc::ptr_eq(&l.1, &st.doc) + { + return Ok(pick(l)); + } + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + let (mut linked, mut embedded) = (Vec::new(), Vec::new()); + for id in all.iter() { + if let Some(NodeKind::Image(im)) = st.doc.node(*id).map(|n| &n.kind) { + if im.link.is_some() { linked.push(*id) } else { embedded.push(*id) } + } + } + let l = (st.uid, st.doc.clone(), Rc::new(linked), Rc::new(embedded)); + let out = pick(&l); + *h.dom.images.lists.borrow_mut() = Some(l); + Ok(out) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +fn id_value(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) => whole(*n).map(NodeId), + Some(Data::Array(a)) => id_value(a.first()), + _ => None, + } +} + +// ---- PlacedItems and RasterItems ---- + +fn collection(placed: bool) -> &'static str { + if placed { "PlacedItems" } else { "RasterItems" } +} + +fn list_doc(h: &Host, a: &[Data], placed: bool) -> Result { + doc_of(h, arg(a, 0), collection(placed)) +} + +fn list_length(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let n = with_doc(h, doc, |_, st| images(h, st, placed).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn list_at(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + with_doc(h, doc, |_, st| Ok(images(h, st, placed)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn list_by_name(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = images(h, st, placed)?; + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a, placed), + Data::Number(_) => match list_at(h, a, placed)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or +/// one in a hidden or locked layer or group, stops it before anything is deleted. +fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { + let doc = list_doc(h, a, placed)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = images(h, st, placed)?; + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +/// `PlacedItems.add()`: a placed item with no file yet, which assigning `file` places. +fn placed_add(h: &Host, a: &[Data]) -> Answer { + let doc = list_doc(h, a, true)?; + let mut pending = h.dom.images.pending.borrow_mut(); + if pending.len() >= MAX_PENDING { + return Err(HostError::Range(format!("a run makes at most {MAX_PENDING} placed items with PlacedItems.add"))); + } + pending.push(Pending { uid: doc.uid, bound: None }); + Ok(host_ref("PlacedItem", &[float(h.run), float(doc.uid), 0.0, 0.0, float(pending.len() as u64 - 1)])) +} + +macro_rules! both { + ($($placed:ident, $raster:ident => $f:ident;)*) => { + $( + fn $placed(h: &Host, a: &[Data]) -> Answer { + $f(h, a, true) + } + fn $raster(h: &Host, a: &[Data]) -> Answer { + $f(h, a, false) + } + )* + }; +} + +both! { + placed_length, raster_length => list_length; + placed_at, raster_at => list_at; + placed_by_name, raster_by_name => list_by_name; + placed_index, raster_index => list_index; + placed_remove_all, raster_remove_all => list_remove_all; +} + +fn placed_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, true)?.uid)) +} + +fn raster_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, list_doc(h, a, false)?.uid)) +} + +fn doc_placed(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("PlacedItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_raster(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("RasterItems", &[float(h.run), float(doc.uid)])) +} + +// ---- files ---- + +/// Whether the script's commands may read `path` now ([`crate::file_access::ScriptGate`]). +fn may_read(h: &Host, path: &str) -> bool { + let documents = h.session.borrow().documents().iter().filter_map(|d| d.path.clone()).collect(); + let gate = h.disk.borrow().gate(documents); + crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok() +} + +/// The real path of the `File` `d` gives as an image to place or relink: one the script may read +/// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of +/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no +/// error names the path. +fn image_path(h: &Host, d: &Data, what: &str) -> Result { + let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; + if path.len() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(super::super::files::PATH_TOO_LONG.into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + let real = h.disk.borrow().open_target(path).map_err(|m| HostError::Error(m.into()))?; + let meta = std::fs::metadata(&real).map_err(|_| HostError::Error(super::super::files::NOT_FOUND.into()))?; + if !meta.is_file() { + return Err(HostError::Error(super::super::files::NOT_REGULAR.into())); + } + if meta.len() > MAX_PLACED_BYTES { + return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); + } + let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); + // What the file holds, read the way `file.place` reads it, before the document changes. + let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?; + if field(&info, "pixelWidth").is_none() { + return Err(HostError::Error(NOT_AN_IMAGE.into())); + } + Ok(path) +} + +// ---- PlacedItem ---- + +/// The item `this` names when it is a `cls` (`PlacedItem` or `RasterItem`). +fn this_of(h: &Host, a: &[Data], cls: &str) -> Result { + match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0)), + _ => Err(HostError::Type(format!("this is not a {cls}"))), + } +} + +/// Reads the image of the `cls` `this` names with `f`. +fn read_image(h: &Host, a: &[Data], cls: &str, f: impl FnOnce(&DocState, &crate::doc::Node, &crate::doc::ImageObject) -> Answer) -> Answer { + let item = this_of(h, a, cls)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => match &n.kind { + NodeKind::Image(im) => f(st, n, im), + _ => Err(HostError::Error(STALE_ITEM.into())), + }, + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn placed_file(h: &Host, a: &[Data]) -> Answer { + if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + return Ok(Data::Null); + } + } + let path = read_image(h, a, "PlacedItem", |_, _, im| Ok(text(im.link.as_ref().map(|l| l.path.clone()).unwrap_or_default())))?; + let Data::String(path) = path else { return Ok(Data::Null) }; + if !may_read(h, &path) { + return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); + } + Ok(file_ref(&path)) +} + +/// `file = File`: places the file, linked, for a `PlacedItems.add()` result that has none. +fn placed_set_file(h: &Host, a: &[Data]) -> Answer { + let Some([run, uid, slot]) = pending_handle(arg(a, 0)) else { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PlacedItem") { + this_of(h, a, "PlacedItem")?; + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + return Err(HostError::Type("this is not a PlacedItem".into())); + }; + let k = slot_of(h, run, uid, slot)?; + if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) { + return Err(HostError::Error(FILE_READ_ONLY.into())); + } + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let path = image_path(h, arg(a, 1), "PlacedItem.file")?; + let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?; + let ids: Vec = match field(&placed, "ids") { + Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(), + _ => Vec::new(), + }; + let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids"))); + let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); + match id.filter(|id| linked(*id)) { + Some(id) => { + if let Some(p) = h.dom.images.pending.borrow_mut().get_mut(k) { + p.bound = Some(id); + } + Ok(Data::Undefined) + } + None => { + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids})))?; + } + Err(HostError::Error(NOT_AN_IMAGE.into())) + } + } +} + +/// `relink(file)`: `links.relink` of the item to the image in `file`. +fn placed_relink(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let path = image_path(h, arg(a, 1), "relink's file")?; + edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?; + Ok(Data::Undefined) +} + +/// `embed()`: `links.embed` of the item, which becomes a raster item. +fn placed_embed(h: &Host, a: &[Data]) -> Answer { + let item = this_of(h, a, "PlacedItem")?; + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(MISSING_LINK.into())); + } + let r = edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?; + let embedded = match field(&r, "embedded") { + Some(Data::Array(ids)) => ids.iter().any(|d| id_value(Some(d)) == Some(item.id)), + _ => false, + }; + if !embedded { + return Err(HostError::Error(MISSING_LINK.into())); + } + Ok(Data::Undefined) +} + +// ---- both ---- + +/// `matrix`: the image's pixels to script coordinates. +fn matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |st, n, im| { + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + let f = frame(st)?; + let [a0, b0, c0, d0, e0, f0] = im.xf.as_coeffs(); + let m = match h.dom.coords.get() { + Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0], + Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top], + }; + let mut items = vec![("typename".to_string(), text("Matrix"))]; + items.extend(MATRIX_KEYS.iter().zip(m).map(|(k, v)| (k.to_string(), num(v)))); + Ok(Data::Object(items)) + }) +} + +/// The six numbers of the `Matrix` record `d`, `mValueA` to `mValueTY`, each finite. +fn matrix_value(d: &Data) -> Result<[f64; 6], HostError> { + let mut m = [0.0; 6]; + for (k, out) in MATRIX_KEYS.iter().zip(m.iter_mut()) { + *out = match field(d, k) { + Some(Data::Number(n)) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("matrix must be a Matrix with a finite {k}"))), + }; + } + Ok(m) +} + +/// Whether `m` gives a pixel an area of at least [`MIN_DETERMINANT`]. +fn area_of(m: Affine) -> bool { + let det = m.determinant(); + !det.is_nan() && det.abs() >= MIN_DETERMINANT +} + +/// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. +/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted +/// image is refused before anything changes; the matrix the image has already changes nothing. +fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { + let m = matrix_value(arg(a, 1))?; + let item = this_of(h, a, cls)?; + let delta = with_doc(h, item.doc, |_, st| { + let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else { + return Err(HostError::Error(STALE_ITEM.into())); + }; + if n.is_distorted_image() { + return Err(HostError::Error(DISTORTED.into())); + } + let f = frame(st)?; + let target = Affine::new(match h.dom.coords.get() { + Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], + Coords::Artboard => [m[0], m[1], m[2], m[3], m[4] + f.left, m[5] + f.top], + }); + if !area_of(target) { + return Err(HostError::Range("the matrix gives the image no area".into())); + } + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + let limit = crate::MAX_COORD * 2.0; + let corners = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].map(|(x, y)| target * Point::new(x, y)); + if corners.iter().any(|p| !(p.x.abs() <= limit && p.y.abs() <= limit)) { + return Err(HostError::Range("the matrix puts the image outside the canvas".into())); + } + let old = im.xf; + if old.as_coeffs().iter().zip(target.as_coeffs()).all(|(o, t)| (o - t).abs() <= 1e-9) { + return Ok(None); + } + if !area_of(old) { + return Err(HostError::Error("the image has no area to transform".into())); + } + Ok(Some((target * old.inverse()).as_coeffs())) + })?; + if let Some(d) = delta { + edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?; + } + Ok(Data::Undefined) +} + +/// `boundingBox`: the pixel rectangle at one point a pixel, `[left, top, right, bottom]`. +fn bounding_box(h: &Host, a: &[Data], cls: &str) -> Answer { + read_image(h, a, cls, |_, _, im| { + let (w, ht) = (f64::from(im.width), f64::from(im.height)); + Ok(Data::Array(match h.dom.coords.get() { + Coords::Document => vec![num(0.0), num(ht), num(w), num(0.0)], + Coords::Artboard => vec![num(0.0), num(0.0), num(w), num(ht)], + })) + }) +} + +fn placed_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "PlacedItem") +} + +fn raster_matrix(h: &Host, a: &[Data]) -> Answer { + matrix(h, a, "RasterItem") +} + +fn placed_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "PlacedItem") +} + +fn raster_set_matrix(h: &Host, a: &[Data]) -> Answer { + set_matrix(h, a, "RasterItem") +} + +fn placed_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "PlacedItem") +} + +fn raster_box(h: &Host, a: &[Data]) -> Answer { + bounding_box(h, a, "RasterItem") +} + +// ---- RasterItem ---- + +/// The header of the raster item's encoded pixels. +fn header(h: &Host, a: &[Data], f: impl FnOnce(&craft_image_codecs::RasterInspection) -> Data) -> Answer { + read_image(h, a, "RasterItem", |st, _, im| { + let blob = st.doc.images.get(&im.key).ok_or_else(|| HostError::Error("the image's pixels are not in the document".into()))?; + match craft_image_codecs::inspect_raster(&blob.bytes) { + Ok(Some(i)) => Ok(f(&i)), + _ => Err(HostError::Error("the image's header does not describe its pixels".into())), + } + }) +} + +fn raster_bits(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.bits_per_sample))) +} + +fn raster_channels(h: &Host, a: &[Data]) -> Answer { + header(h, a, |i| num(f64::from(i.channels))) +} + +fn raster_transparent(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + header(h, a, |i| Data::Bool(matches!(i.color_type, T::GrayAlpha | T::Rgba | T::CmykAlpha) || i.transparent_index.is_some())) +} + +fn raster_color_space(h: &Host, a: &[Data]) -> Answer { + use craft_image_codecs::RasterColorType as T; + let space = header(h, a, |i| { + text(match i.color_type { + T::Bitmap | T::Gray | T::GrayAlpha => "ImageColorSpace.Grayscale", + T::Rgb | T::Rgba => "ImageColorSpace.RGB", + T::Cmyk | T::CmykAlpha => "ImageColorSpace.CMYK", + T::Indexed => "ImageColorSpace.Indexed", + T::Lab => "ImageColorSpace.LAB", + T::Other => "", + }) + })?; + match space { + Data::String(s) if s.is_empty() => Err(HostError::Error("the image's header does not describe its color space".into())), + d => Ok(d), + } +} + +fn raster_colorized(h: &Host, a: &[Data]) -> Answer { + read_image(h, a, "RasterItem", |st, n, im| { + let gray = st.doc.images.get(&im.key).is_some_and(|b| b.gray_source().is_some()); + Ok(Data::Bool(gray && n.extras().colorize.is_some())) + }) +} + +fn raster_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Bool(true)) +} + +/// `embedded = true` changes nothing; a raster item cannot be linked by assigning `false`. +fn raster_set_embedded(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + match arg(a, 1) { + Data::Bool(true) => Ok(Data::Undefined), + Data::Bool(false) => Err(HostError::Error("a raster item cannot be linked by setting embedded to false".into())), + _ => Err(HostError::Type("embedded must be true or false".into())), + } +} + +fn raster_file(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(Data::Null) +} + +fn raster_status(h: &Host, a: &[Data]) -> Answer { + this_of(h, a, "RasterItem")?; + Ok(text("RasterLinkState.NODATA")) +} + +/// `Document.placedItems` and `Document.rasterItems`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("placedItems", get(l, doc_placed)), ("rasterItems", get(l, doc_raster))]) +} + +/// The collections, `PlacedItem` and `RasterItem`, after `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let placed_list = named(vec![ + ("typename", typename_of("PlacedItems")), + ("length", get(l, placed_length)), + ("parent", get(l, placed_parent)), + ("index", method(l, placed_index)), + ("getByName", method(l, placed_by_name)), + ("removeAll", method(l, placed_remove_all)), + ("add", method(l, placed_add)), + ]); + let raster_list = named(vec![ + ("typename", typename_of("RasterItems")), + ("length", get(l, raster_length)), + ("parent", get(l, raster_parent)), + ("index", method(l, raster_index)), + ("getByName", method(l, raster_by_name)), + ("removeAll", method(l, raster_remove_all)), + ]); + let mut placed = named(vec![ + ("file", property(l, placed_file, placed_set_file)), + ("relink", method(l, placed_relink)), + ("embed", method(l, placed_embed)), + ("matrix", property(l, placed_matrix, placed_set_matrix)), + ("boundingBox", get(l, placed_box)), + ]); + placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + let mut raster = named(vec![ + ("bitsPerChannel", get(l, raster_bits)), + ("channels", get(l, raster_channels)), + ("colorizedGrayscale", get(l, raster_colorized)), + ("embedded", property(l, raster_embedded, raster_set_embedded)), + ("file", get(l, raster_file)), + ("imageColorSpace", get(l, raster_color_space)), + ("matrix", property(l, raster_matrix, raster_set_matrix)), + ("status", get(l, raster_status)), + ("transparent", get(l, raster_transparent)), + ("boundingBox", get(l, raster_box)), + ]); + raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + vec![ + class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), + class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), + class("PlacedItem", Some("PageItem"), placed, None), + class("RasterItem", Some("PageItem"), raster, None), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 436d74cf75..a1b22fc087 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_images; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs new file mode 100644 index 0000000000..6b3f3d3cac --- /dev/null +++ b/crates/engine/src/tests/script_dom_images.rs @@ -0,0 +1,415 @@ +//! Placed and raster items in the script object model: placing a file with `PlacedItems.add()`, +//! relinking, embedding, the encoded image's header, and the file checks. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script and an `outside` folder the +/// script may not read, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-images-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A `w`×`h` 8-bit gray PNG. +fn gray_png(w: u32, h: u32) -> Vec { + let raw = vec![128u8; (w * h) as usize]; + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, raw).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +fn js_path(p: &Path) -> String { + p.to_string_lossy().replace('\\', "\\\\").replace('\'', "\\'") +} + +/// A session with one 400 × 300 pt document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The images of the active document: (id, linked path). +fn images(s: &Session) -> Vec<(NodeId, Option)> { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.id, im.link.as_ref().map(|l| l.path.clone()))); + } + }); + out +} + +/// Places `path` linked (`link`) with the engine's own command, outside any script. +fn place(s: &mut Session, path: &Path, link: bool) -> NodeId { + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": link})).unwrap(); + NodeId(r["ids"][0].as_u64().unwrap()) +} + +#[test] +fn placed_add_file_links_one_image() { + let base = folder("add"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(40, 20)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); vc.log(p.file); vc.log(d.placedItems.length);\ + var m = ''; try {{ p.width; }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); vc.log(d.placedItems.length); vc.log(p.typename); vc.log(p.file.name);\ + vc.log(p.width); vc.log(d.placedItems[0].file.name); vc.log(d.rasterItems.length);\ + try {{ p.file = new File('{}'); }} catch (e) {{ m = e.message; }} vc.log(m);", + js_path(&png), + js_path(&png) + ), + ); + assert_eq!(out[..3], [json!(null), json!(0), json!("PlacedItem.file is required")]); + assert_eq!(out[3..9], [json!(1), json!("PlacedItem"), json!("a.png"), json!(40), json!("a.png"), json!(0)]); + assert_eq!(out[9], json!("PlacedItem.file is read-only: use relink")); + let imgs = images(&s); + assert_eq!(imgs.len(), 1); + assert_eq!(imgs[0].1.as_deref().map(Path::new), Some(png.as_path())); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_file_refuses_bad_values_without_changing_the_document() { + let base = folder("bad"); + std::fs::write(base.join("main/notes.txt"), "hello").unwrap(); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let big = std::fs::File::create(base.join("main/big.png")).unwrap(); + big.set_len((256 << 20) + 1).unwrap(); + drop(big); + let mut s = session(); + let cases = [ + ("'a.png'", "must be a File"), + ("{}", "must be a File"), + (&format!("new File('{}')", js_path(&base.join("main/notes.txt"))), "not an image"), + (&format!("new File('{}')", js_path(&base.join("outside/b.png"))), "Script file access denied"), + (&format!("new File('{}')", js_path(&base.join("main/big.png"))), "larger than 256 MiB"), + (&format!("new File('{}')", js_path(&base.join("main/none.png"))), "does not exist"), + (&format!("new Folder('{}')", js_path(&base.join("main"))), "must be a File"), + ]; + for (value, message) in cases { + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = {value};")); + assert!(e.contains(message), "{value}: {e}"); + assert!(!e.contains("outside"), "{value}: {e}"); + assert!(images(&s).is_empty(), "{value}"); + assert_eq!(undo_steps(&s), 0, "{value}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_plain_object_shaped_like_a_file_is_not_one() { + let base = folder("forged"); + std::fs::write(base.join("outside/b.png"), gray_png(4, 4)).unwrap(); + let mut s = session(); + let forged = js_path(&base.join("outside/b.png")); + let e = failure(&mut s, &base, &format!("var f = {{}}; f['\\u0000fileRef'] = '{forged}'; app.activeDocument.placedItems.add().file = f;")); + assert!(e.contains("not plain data"), "{e}"); + assert!(images(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_forged_or_altered_file_does_not_change_the_path() { + let base = folder("forged-proto"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let forged = js_path(&c); + let make = format!( + "var f = Object.create(File.prototype); f.__vcPath = '{forged}';\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});\ + Object.defineProperty(f, 'path', {{value: '{forged}', enumerable: true}});" + ); + for target in ["app.activeDocument.placedItems.add().file = f;", "app.activeDocument.placedItems[0].relink(f);"] { + if target.contains("relink") { + place(&mut s, &a, true); + } + let e = failure(&mut s, &base, &format!("{make} {target}")); + assert!(e.contains("must be a File") && !e.contains("c.png"), "{target}: {e}"); + } + let id = images(&s)[0].0; + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let alter = format!( + "f.__vcPath = '{forged}'; Object.defineProperty(f, '__vcPath', {{value: '{forged}'}});\ + Object.defineProperty(f, 'fsName', {{value: '{forged}', enumerable: true}});" + ); + let out = log( + &mut s, + &base, + &format!( + "var f = new File('{}'); {alter} var p = app.activeDocument.placedItems.add(); p.file = f; vc.log(p.file.name);\ + f = new File('{}'); {alter} p.relink(f); vc.log(p.file.name);", + js_path(&b), + js_path(&a) + ), + ); + assert_eq!(out, vec![json!("b.png"), json!("a.png")]); + let paths: Vec<_> = images(&s).into_iter().map(|(_, p)| p).collect(); + assert_eq!(paths.len(), 2); + assert!(paths.iter().all(|p| p.as_deref().map(Path::new) == Some(a.as_path())), "{paths:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_placed_items_add_result_is_a_relative_object() { + let base = folder("relative"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + let first = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, q = d.placedItems[0], p = d.placedItems.add(), m = '';\ + try {{ q.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m = e.message; }} vc.log(m);\ + p.file = new File('{}'); q.move(p, ElementPlacement.PLACEBEFORE);", + js_path(&b) + ), + ); + assert_eq!(out, vec![json!("PlacedItem.file is required")]); + let order: Vec = images(&s).into_iter().map(|(id, _)| id).collect(); + assert_eq!(order.len(), 2); + assert_eq!(order[1], first, "{order:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_file_that_is_not_an_image_is_refused_before_placing() { + let base = folder("text"); + let notes = base.join("main/notes.txt"); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!("try {{ app.activeDocument.placedItems.add().file = new File('{}'); }} catch (e) {{ vc.log(e.message); }}", js_path(¬es)), + ); + assert_eq!(out, vec![json!("The file is not an image")]); + assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, |c| c.len()), 0); + assert_eq!(undo_steps(&s), 0); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_items_add_is_bounded() { + let base = folder("pending"); + let mut s = session(); + let e = failure(&mut s, &base, "var p = app.activeDocument.placedItems; for (var i = 0; i < 1025; i++) p.add();"); + assert!(e.contains("at most 1024"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relink_denied_path_preserves_old_link() { + let base = folder("relink"); + let (a, b, c) = (base.join("main/a.png"), base.join("main/b.png"), base.join("outside/c.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + std::fs::write(&c, gray_png(30, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&c))); + assert!(e.contains("Script file access denied") && !e.contains("c.png"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + let before = undo_steps(&s); + let out = log(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0]; p.relink(new File('{}')); vc.log(p.file.name);", js_path(&b))); + assert_eq!(out, vec![json!("b.png")]); + assert_eq!(images(&s), vec![(id, Some(b.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn embed_reclassifies_and_stales_wrapper() { + let base = folder("embed"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0]; p.embed(); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);\ + vc.log(d.placedItems.length); var r = d.rasterItems[0]; vc.log(r.typename);\ + vc.log(r.embedded); vc.log(r.file); vc.log(r.status === RasterLinkState.NODATA); r.embedded = true;\ + try { r.embedded = false; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[..6], [json!("Stale page item"), json!(0), json!("RasterItem"), json!(true), json!(null), json!(true)]); + assert!(out[6].as_str().unwrap().contains("cannot be linked"), "{out:?}"); + assert_eq!(images(&s), vec![(id, None)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn missing_link_embed_reports_error() { + let base = folder("missing"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + std::fs::remove_file(&a).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems[0].embed();"); + assert!(e.contains("Linked image is missing"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn raster_metadata_uses_encoded_header_not_rgb_fallback() { + let base = folder("meta"); + let (g, c) = (base.join("main/g.png"), base.join("main/c.png")); + std::fs::write(&g, gray_png(6, 4)).unwrap(); + std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap(); + let mut s = session(); + place(&mut s, &g, false); + place(&mut s, &c, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems, t = [];\ + for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\ + vc.log(t); vc.log(r[0].boundingBox); vc.log(r[1].imageColorSpace === ImageColorSpace.RGB); var m = r[1].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", + ); + assert_eq!(out[0], json!([["ImageColorSpace.Grayscale", 1, 8, false, false], ["ImageColorSpace.RGB", 4, 8, true, false]])); + assert_eq!(out[1], json!([0, 4, 6, 0])); + assert_eq!(out[2], json!(true)); + let m = out[3].as_array().unwrap(); + assert_eq!(m[0], json!("Matrix")); + assert!(m[1].as_f64().unwrap() > 0.0 && m[2].as_f64().unwrap() < 0.0, "{m:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_assignment_transforms_the_image() { + let base = folder("matrix"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, false); + let before = undo_steps(&s); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], m = r.matrix;\ + m.mValueA = 0; m.mValueB = 2; m.mValueC = -3; m.mValueD = 0; m.mValueTX = 50; m.mValueTY = 60; r.matrix = m;\ + var n = r.matrix; vc.log([n.mValueA, n.mValueB, n.mValueC, n.mValueD, n.mValueTX, n.mValueTY]); r.matrix = n;", + ); + let got: Vec = out[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + for (g, w) in got.iter().zip([0.0, 2.0, -3.0, 0.0, 50.0, 60.0]) { + assert!((g - w).abs() < 1e-6, "{got:?}"); + } + let xf = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf.as_coeffs(), + _ => panic!("not an image"), + }; + assert!((xf[1] + 2.0).abs() < 1e-6 && (xf[2] + 3.0).abs() < 1e-6, "{xf:?}"); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0]; r.matrix = r.matrix;"); + assert_eq!(undo_steps(&s), before + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_matrix_refuses_bad_values_without_changing_the_image() { + let base = folder("matrix-bad"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + let xf = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf, + _ => panic!("not an image"), + }; + let (was, before) = (xf(&s), undo_steps(&s)); + let cases = [ + ("m.mValueA = NaN;", "mValueA is not a finite number"), + ("m.mValueTY = -Infinity;", "mValueTY is not a finite number"), + ("m.mValueB = '1';", "finite mValueB"), + ("delete m.mValueTX;", "finite mValueTX"), + ("m = 5;", "finite mValueA"), + ("m.mValueA = 0; m.mValueD = 0;", "no area"), + ("m.mValueA = 1e300;", "outside the canvas"), + ("m.mValueTX = 9e6;", "outside the canvas"), + ("m.mValueA = 1e6;", "outside the canvas"), + ]; + for (change, message) in cases { + let e = failure(&mut s, &base, &format!("var p = app.activeDocument.placedItems[0], m = p.matrix; {change} p.matrix = m;")); + assert!(e.contains(message), "{change}: {e}"); + assert_eq!(xf(&s), was, "{change}"); + assert_eq!(undo_steps(&s), before, "{change}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_file_getter_hides_out_of_scope_link() { + let base = folder("hide"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn stale_and_foreign_placed_items_are_refused() { + let base = folder("stale"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems[0], m = []; p.remove();\ + try { p.relink(null); } catch (e) { m.push(e.message); }\ + try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\ + try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]); + assert!(s.active().unwrap().doc.node(id).is_none()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index e46fd9f77d..f36fa28f2c 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -1133,6 +1133,20 @@ pub(crate) fn reset_current(i: &mut Interp) -> JsResult<()> { Ok(()) } +/// The [`crate::Data`] that stands for a `File` of `path` ([`FILE_REF_KEY`]), in the platform's +/// form. A member of a host class ([`crate::HostClass`]) gives one to hand the script a new `File`. +pub fn file_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +impl Interp { + /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). + pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult { + let proto = classes(self)?.file_proto; + instance(self, proto, Value::str(path)) + } +} + /// Adds `File` and `Folder` to the global object, their work done by the host functions in /// `items` ([`crate::Realm::define_file_classes`]). pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index a639dbd0cb..061486b380 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -362,6 +362,12 @@ impl Interp { Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { self.write_host_ref(&Data::Object(items))? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => { + match items.as_slice() { + [(_, Data::String(path))] => self.write_file_ref(path)?, + _ => Value::Undefined, + } + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 45f6aa61e4..84a6401f55 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,7 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use file_classes::{FILE_REF_KEY, file_ref_path}; +pub use file_classes::{FILE_REF_KEY, file_ref, file_ref_path}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/docs/mcp.md b/docs/mcp.md index 6de9cf9859..0da6d93d43 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2726,6 +2726,30 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. +- `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked + images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, + in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every + other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` + (`links.embed`), `matrix` and `boundingBox`. A `RasterItem` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/) + has `bitsPerChannel`, `channels`, `imageColorSpace` and `transparent`, read from the header of its encoded pixels, + and `colorizedGrayscale`, `embedded`, `file`, `status`, `matrix` and `boundingBox`. The enumeration values are + strings such as `"ImageColorSpace.Grayscale"` and `"RasterLinkState.NODATA"` + (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). VectorCraft's own rules: `file` is assigned + once, on a `placedItems.add()` result, and is read-only after (`PlacedItem.file is read-only: use relink`). A file + to place or relink must be a `File` the script may read, checked as `app.open` checks its file, of at most + 256 MiB, holding an image; its size is read before its contents, and anything else throws an error with nothing + changed (`Script file access denied` names no path). Reading `file` of an image whose file the script may not read + throws `Script file access denied`. After `embed()` the object is stale and `rasterItems` has the image under the + same id; an image whose file is missing throws `Linked image is missing` and stays linked. `RasterItem.file` is + `null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true + for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY` + that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning + `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of + the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the + end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0f5208319d..636c828ea4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Tracing, rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From dd35352874a29bb8358b5a06c5353b040a6665a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 16:12:11 -0800 Subject: [PATCH 009/533] Scripts: an embedded image's held PlacedItem stays stale and the raster item is a new object A read of a host class on another branch of the same family with the same handle makes a new object instead of switching the held object's class. A class and its ancestors and descendants still share one object, so a placed image read through placedItems and through pageItems is the same object, and each branch's held object keeps its identity on later reads. After p.embed() or links.embed, reading rasterItems or pageItems gives a new RasterItem object, and the PlacedItem object the script held throws Stale page item. --- crates/engine/src/tests/script_dom.rs | 7 +- crates/engine/src/tests/script_dom_images.rs | 18 +++++ crates/js/src/host_classes.rs | 69 +++++++++++++++----- crates/js/src/host_tests.rs | 24 +++++++ crates/js/src/interp.rs | 6 +- docs/mcp.md | 4 +- 6 files changed, 105 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..5bf276e3b9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -619,7 +619,7 @@ fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { } #[test] -fn a_held_image_stays_the_same_object_when_it_is_embedded() { +fn a_held_image_is_stale_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); let photo = dir.file("photo.png"); super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); @@ -629,11 +629,12 @@ fn a_held_image_stays_the_same_object_when_it_is_embedded() { &mut s, &format!( "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ - var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + var j = app.activeDocument.pageItems[0], m = ''; try {{ i.typename; }} catch (e) {{ m = e.message; }}\ + vc.log([i === j, m, j.typename, j instanceof RasterItem, i instanceof PlacedItem]);", id.0 ), ); - assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); + assert_eq!(out, vec![json!("PlacedItem"), json!([false, "Stale page item", "RasterItem", true, true])]); } #[test] diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 6b3f3d3cac..a498a0244c 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -278,6 +278,24 @@ fn embed_reclassifies_and_stales_wrapper() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn embed_gives_raster_item_a_new_object() { + let base = folder("embed-new"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], q = d.pageItems[0]; vc.log(p === q); p.embed();\ + var r = d.rasterItems[0]; vc.log(p === r); vc.log(r.typename); vc.log(d.pageItems[0] === r); var m = '';\ + try { p.name; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(true), json!(false), json!("RasterItem"), json!(true), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn missing_link_embed_reports_error() { let base = folder("missing"); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..67a44b9872 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -9,8 +9,9 @@ //! of a host class from its own data. A class's prototype and constructor are frozen. While a //! script holds the object for a class and handle, each read of that class and handle gives the //! same object. Classes that descend from the same class without a parent share their objects: a -//! read of another of them with the same handle gives the object the script holds, now of the -//! class that read names. +//! read of an ancestor or descendant of the held object's class with the same handle gives the +//! object the script holds, now of the class that read names. A read of a class on another branch +//! gives a new object, and the held object keeps its class. //! //! Every member function gets the object it is called on (`this`) as its first argument, or //! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a @@ -72,6 +73,20 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The class's parent, as an index into the realm's classes. + parent: Option, +} + +/// Whether class `a` is class `b` or descends from it, both indexes into `classes`. +fn descends(classes: &[Entry], a: u32, b: u32) -> bool { + let mut at = Some(a); + while let Some(c) = at { + if c == b { + return true; + } + at = classes.get(c as usize).and_then(|e| e.parent); + } + false } impl Entry { @@ -83,8 +98,9 @@ impl Entry { /// A family of classes ([`Entry::family`]) and the bits of a handle. type MadeKey = (u32, Box<[u64]>); -/// The object made for each family of classes and handle ([`Interp::host_objects`]). -pub(crate) type Made = std::collections::HashMap; +/// The objects made for each family of classes and handle ([`Interp::host_objects`]), one for each +/// branch of the family a read named, oldest first. +pub(crate) type Made = std::collections::HashMap>; /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. @@ -99,7 +115,10 @@ fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey /// Drops the entries of `made` whose objects the last collection freed. pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { - made.retain(|key, id| is_made(heap, classes, *id, key)); + made.retain(|key, ids| { + ids.retain(|id| is_made(heap, classes, *id, key)); + !ids.is_empty() + }); } /// The [`Data`] that stands for the object of host class `class` with `handle`. @@ -142,10 +161,24 @@ impl Interp { let (proto, family) = (entry.proto, entry.family); let class = u32::try_from(class).unwrap_or(u32::MAX); let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); - if let Some(&id) = self.host_objects.get(&made) - && is_made(&self.heap, &self.host_classes, id, &made) - { - // An object of another class of the family becomes one of `class`. + // The held object of `class` itself, or else the newest of an ancestor or descendant class, + // which becomes one of `class`. An object of a class on another branch of the family keeps + // its class, and a read of `class` with no such object gives a new object. + let mut found = None; + for &id in self.host_objects.get(&made).map(Vec::as_slice).unwrap_or_default() { + if !is_made(&self.heap, &self.host_classes, id, &made) { + continue; + } + let Class::Host(h) = &self.object(id)?.class else { continue }; + if h.class == class { + found = Some(id); + break; + } + if descends(&self.host_classes, h.class, class) || descends(&self.host_classes, class, h.class) { + found = Some(id); + } + } + if let Some(id) = found { let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class @@ -159,7 +192,13 @@ impl Interp { let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); - self.host_objects.insert(made, id); + if let Some(ids) = self.host_objects.get_mut(&made) { + let (heap, classes) = (&self.heap, &self.host_classes); + ids.retain(|&old| old != id && is_made(heap, classes, old, &made)); + ids.push(id); + } else { + self.host_objects.insert(made, vec![id]); + } Ok(Value::Object(id)) } @@ -223,10 +262,10 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_class) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((at, e)) => (e.proto, e.family, u32::try_from(at).ok()), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; @@ -236,7 +275,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_class }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..13aa5f8560 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -661,6 +661,30 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +#[test] +fn a_read_of_a_class_on_another_branch_gives_a_new_object() { + let mut r = realm(1_000_000); + let class = |name: &str, parent: Option<&str>| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: Vec::new(), + index: None, + construct: None, + }; + let get: HostFunction = Rc::new(|a| match a.get(1) { + Some(Data::String(name)) => Ok(host_ref(name, &[1.0])), + _ => Ok(Data::Null), + }); + let mut maker = class("Maker", None); + maker.members.push(("get".into(), HostMember::Method(get))); + let classes = vec![class("Base", None), class("Left", Some("Base")), class("Right", Some("Base")), class("Leaf", Some("Left")), maker]; + r.define_host_classes(classes, vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + let script = "function get(n) { return maker.get(n); } var l = get('Left'), b = get('Base'), f = get('Leaf'); var r = get('Right'); \ + [l === b, b === f, f instanceof Leaf, r === l, r instanceof Right, l instanceof Leaf, get('Leaf') === l, \ + get('Right') === r, get('Base') === r].join()"; + assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into())); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..2ee18f4cc1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -257,9 +257,9 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. pub(crate) write_hosted: bool, - /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of - /// the same one give the same object. It is not a root: an entry whose object was collected is - /// dropped after each collection. + /// The objects made for each family of classes and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an object that was collected is dropped + /// after each collection. pub(crate) host_objects: crate::host_classes::Made, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, diff --git a/docs/mcp.md b/docs/mcp.md index 0da6d93d43..1c4b23e213 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2659,8 +2659,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws - `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the - same object when the image is embedded: the next read gives that object, now a `RasterItem`. The + `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. When a placed image is embedded, an + object a script holds for it is stale, and the next read gives a new `RasterItem` object. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. From 15153de8491f7f58b64447dbb5570fbaf1e9d394 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:56:25 -0800 Subject: [PATCH 010/533] Scripts: members not available yet on placed and raster items check the item first Reading or assigning PlacedItem.trace or contentVariable, or RasterItem.colorants, colorize, contentVariable, overprint or trace, now throws Stale page item for a removed or embedded item and PlacedItem.file is required for an unbound PlacedItems.add() result, as the PageItem members already do, before the not available yet error. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/tests/script_dom_images.rs | 21 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cd96ea46c5..18a394c125 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -170,7 +170,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "PlacedItem" | "RasterItem" => { item_of(&h, arg(&a, 0))?; } _ => {} diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index a498a0244c..674d098eb5 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -431,3 +431,24 @@ fn stale_and_foreign_placed_items_are_refused() { assert!(s.active().unwrap().doc.node(id).is_none()); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn members_not_available_yet_check_the_image_first() { + let base = folder("later"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace; } catch (e) { m.push(e.message); }\ + p.embed(); try { p.trace; } catch (e) { m.push(e.message); }\ + var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\ + r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} From dc7d5ccfd77f9ec869b6cbb23fc03ca37d0d26ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:29:28 -0800 Subject: [PATCH 011/533] Tests: the script host name tables list the placed and raster item names PlacedItem and RasterItem leave the bare classes, and the tables list Document.placedItems and rasterItems, the PlacedItems, RasterItems, PlacedItem and RasterItem members, and the ImageColorSpace and RasterLinkState enumerations. PlacedItem.file= and relink read the image file they are given, so they stay inside the document. --- .../tests/it/script_host_vs_scriptcheck.rs | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a0794be35c..931023a427 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,7 +44,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given. +/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given, +/// and `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -77,7 +78,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems PlacedItem PlacedItems RasterItem RasterItems RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( @@ -99,8 +100,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= placedItems rasterItems \ + rulerOrigin rulerOrigin= rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -117,6 +118,19 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("PlacedItems.", "prototype"), + ("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("PlacedItem.", "prototype"), + ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace trace="), + ("RasterItems.", "prototype"), + ("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"), + ("RasterItem.", "prototype"), + ( + "RasterItem.prototype.", + "bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \ + contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \ + trace trace= transparent", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -145,12 +159,16 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of placed and raster items. + ("", "ImageColorSpace RasterLinkState"), + ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), + ("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ + PlacedDocumentItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's From 88a6ed5fe8815c439f8e0e4e0b50e49d59a82d26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:48:12 -0800 Subject: [PATCH 012/533] Scripts: a run's Copy or Cut is offered to other apps when the run ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A script that copies with app.copy() or app.cut(), or with edit.copy, edit.cut, artboard.copy or artboard.cut through vc.run (also inside command.batch or an action), and ends with the clipboard still holding what it copied, now has copied: true in its report. The desktop app then offers the clipboard to other apps as Edit › Copy does, for runs in the app and for runs automation takes to their end at once. - Session counts each Copy or Cut that fills the clipboard and marks the clipboard as holding a copy; a clipboard.import... command clears the mark. A Copy that leaves the clipboard empty is not counted. - command.batch, a plugin call and a script command that fails put the count and the mark back with the clipboard, so a rolled-back Copy is not reported. - docs/mcp.md and the script.run params text describe copied. --- crates/engine/src/cmd/clipboard/flavours.rs | 11 ++++ crates/engine/src/cmd/edit.rs | 1 + crates/engine/src/cmd/fileio/batch.rs | 2 + crates/engine/src/cmd/panelcmds.rs | 1 + crates/engine/src/cmd/plugin_call.rs | 6 +++ crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/lib.rs | 4 ++ crates/engine/src/script/dom/clipboard.rs | 5 +- crates/engine/src/script/mod.rs | 26 +++++++-- crates/engine/src/session/documents.rs | 2 + crates/engine/src/tests/script_dom_prefs.rs | 22 ++++++++ crates/ui-egui/src/app/commands.rs | 11 ++-- crates/ui-egui/src/script_runs.rs | 7 ++- crates/ui-egui/src/tests/script_run.rs | 60 +++++++++++++++++++++ docs/mcp.md | 10 +++- 15 files changed, 157 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 680e2902c8..bf900adcf1 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -385,6 +385,16 @@ impl Session { self.prefs.copy_as_svg && !self.clipboard_svg_refused() } + /// After a Copy or Cut has filled the clipboard: counts it in [`Session::copies`] when it put + /// something there, and marks the clipboard as holding a copy ([`Session::clipboard_copied`]). + pub(crate) fn note_copy(&mut self) { + let filled = !self.clipboard.is_empty(); + if filled { + self.copies = self.copies.wrapping_add(1); + } + self.clipboard_copied = filled; + } + /// Replace the clipboard with `clip`, centred on `p`'s `center` (default: the first /// artboard's centre) → the number of objects. pub(super) fn load_clipboard(&mut self, mut clip: Clipboard, p: &Value) -> Result { @@ -400,6 +410,7 @@ impl Session { } let count = clip.nodes.len(); self.clipboard = clip; + self.clipboard_copied = false; Ok(count) } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bf9ff59c14..973330320b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1129,6 +1129,7 @@ fn copy(s: &mut Session, p: &Value) -> Result { } clip.guides = guides; s.clipboard = clip; + s.note_copy(); Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..e517f69ca4 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -21,6 +21,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { super::super::edit::settle_interaction(s)?; } let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); + let (clipboard_copied, copies) = (s.clipboard_copied, s.copies); // The documents as they are now, whole: what a failed step brings back. Their art, history, // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); @@ -43,6 +44,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { s.active = active; s.sync_front_profiles(); (s.paint, s.fill_active, s.draw_mode, s.draw_inside, s.clipboard, s.untitled_counter, s.explicit_undo_group) = saved; + (s.clipboard_copied, s.copies) = (clipboard_copied, copies); s.pending_paint = None; return Err(e); } diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..4db890c297 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -380,6 +380,7 @@ pub(crate) fn artboard_copy(s: &mut Session, p: &Value, cut: bool) -> Result, clipboard: crate::Clipboard, + clipboard_copied: bool, + copies: u64, untitled_counter: u32, explicit_undo_group: Option>, prefs: crate::Prefs, @@ -553,6 +555,8 @@ impl Saved { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, + copies: s.copies, untitled_counter: s.untitled_counter, explicit_undo_group: s.explicit_undo_group.clone(), prefs: s.prefs.clone(), @@ -577,6 +581,8 @@ impl Saved { s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; s.clipboard = self.clipboard; + s.clipboard_copied = self.clipboard_copied; + s.copies = self.copies; s.untitled_counter = self.untitled_counter; s.explicit_undo_group = self.explicit_undo_group; s.prefs = self.prefs; diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..22608a78dc 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, copied?: true (the run ran a Copy or Cut and the clipboard still holds what it put there), log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 089b33a038..35730579e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -61,6 +61,10 @@ pub struct Session { pub fill_active: bool, /// Internal clipboard: the copied objects and the document resources they use. pub clipboard: Clipboard, + /// How many times Copy or Cut has put art, guides or artboards on [`Self::clipboard`]. + pub(crate) copies: u64, + /// [`Self::clipboard`] holds what the last Copy or Cut put there, not what an import put there. + pub(crate) clipboard_copied: bool, /// Executed commands (for actions and debugging), the most recent ones kept ([`Journal`]). pub journal: Journal, /// About the most memory the undo steps of all the open documents may keep together diff --git a/crates/engine/src/script/dom/clipboard.rs b/crates/engine/src/script/dom/clipboard.rs index 7b07587999..874660a623 100644 --- a/crates/engine/src/script/dom/clipboard.rs +++ b/crates/engine/src/script/dom/clipboard.rs @@ -5,7 +5,10 @@ //! //! VectorCraft's own rules, which the help page does not state: with nothing selected, or no //! document open, `copy` and `cut` do nothing; with the clipboard empty `paste` does nothing; and -//! `paste` with no document open throws `No active document`. +//! `paste` with no document open throws `No active document`. `paste` takes the session's +//! clipboard, not art another app copied since. A run that finishes after a Copy or Cut, by any +//! command, with the clipboard still holding what it copied, reports `copied`, and the desktop app +//! then offers the clipboard to other apps. use serde_json::json; use vectorcraft_js::{Data, HostError, HostMember}; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 33b19dd046..54a114068b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -466,6 +466,7 @@ struct World { draw_mode: DrawMode, draw_inside: Option, clipboard: Clipboard, + clipboard_copied: bool, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -590,6 +591,7 @@ impl World { draw_mode: s.draw_mode, draw_inside: s.draw_inside, clipboard: s.clipboard.clone(), + clipboard_copied: s.clipboard_copied, untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -613,6 +615,7 @@ impl World { swap(&mut self.draw_mode, &mut s.draw_mode); swap(&mut self.draw_inside, &mut s.draw_inside); swap(&mut self.clipboard, &mut s.clipboard); + swap(&mut self.clipboard_copied, &mut s.clipboard_copied); swap(&mut self.untitled_counter, &mut s.untitled_counter); swap(&mut self.menu, &mut s.menu); swap(&mut self.last_solid, &mut s.last_solid); @@ -650,7 +653,8 @@ pub(crate) struct Savepoint { fill_active: bool, draw_mode: DrawMode, draw_inside: Option, - clipboard: Option, + /// The clipboard, [`Session::clipboard_copied`] and [`Session::copies`]. + clipboard: Option<(Clipboard, bool, u64)>, untitled_counter: u32, menu: cmd::menucmds::MenuState, last_solid: crate::Color, @@ -684,7 +688,7 @@ impl Savepoint { fill_active: s.fill_active, draw_mode: s.draw_mode, draw_inside: s.draw_inside, - clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| s.clipboard.clone()), + clipboard: CAN_FAIL_AFTER_COPYING.contains(&id).then(|| (s.clipboard.clone(), s.clipboard_copied, s.copies)), untitled_counter: s.untitled_counter, menu: s.menu.clone(), last_solid: s.last_solid, @@ -734,8 +738,10 @@ impl Savepoint { s.fill_active = self.fill_active; s.draw_mode = self.draw_mode; s.draw_inside = self.draw_inside; - if let Some(clipboard) = self.clipboard { + if let Some((clipboard, copied, copies)) = self.clipboard { s.clipboard = clipboard; + s.clipboard_copied = copied; + s.copies = copies; } s.untitled_counter = self.untitled_counter; s.menu = self.menu; @@ -771,6 +777,8 @@ struct Host { log: RefCell>, log_bytes: Cell, written: RefCell, + /// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action. + copied: Cell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -1257,6 +1265,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; + let copies = s.copies; crate::file_access::start_recording_writes(); // The command reads and writes only where the script's own files may, and the open documents' files. let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); @@ -1270,6 +1279,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value match r { Ok(v) => { note_ids(s); + if s.copies != copies { + host.copied.set(true); + } let (mut objects, mut bytes) = (0, 0); for st in &s.docs { match before.iter().find(|(uid, ..)| *uid == st.uid) { @@ -2054,6 +2066,7 @@ impl Session { log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), written: RefCell::new(Written::default()), + copied: Cell::new(false), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -2315,6 +2328,13 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + // The run ran a Copy or Cut, and the clipboard still holds what one put there. + if host.copied.get() + && self.clipboard_copied + && let Some(o) = report.as_object_mut() + { + o.insert("copied".into(), json!(true)); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..6abd2a88dd 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -50,6 +50,8 @@ impl Session { paint: PaintDefaults::default(), fill_active: true, clipboard: Clipboard::default(), + copies: 0, + clipboard_copied: false, journal: Journal::default(), history_budget: crate::default_history_budget(), histories_seen: None, diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 12edc6d3c8..548f0cee07 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -450,3 +450,25 @@ fn copy_and_paste_run_as_one_undo_step() { log(&mut s, "app.cut();"); assert!(s.active().unwrap().doc.node(NodeId(a)).is_none()); } + +#[test] +fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() { + let mut s = Session::new(); + s.clipboard_copied = true; + s.note_copy(); + assert_eq!(s.copies, 0); + assert!(!s.clipboard_copied); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + assert_eq!(s.copies, 1); + assert!(s.clipboard_copied); + // A batch that copies and then fails puts the count back with the clipboard. + s.execute("clipboard.importSvg", &json!({"svg": ""})).unwrap(); + assert!(!s.clipboard_copied); + let batch = json!({"commands": [{"command": "edit.copy", "params": {}}, {"command": "no.such", "params": {}}]}); + assert!(s.execute("command.batch", &batch).is_err()); + assert_eq!(s.copies, 1); + assert!(!s.clipboard_copied); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..3bc5ecc26f 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -262,7 +262,7 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } - let copied = r.is_ok() && self.publish_copy(id); + let copied = r.as_ref().is_ok_and(|v| self.publish_copy(id, v)); self.sync_views(); self.refresh_replace_font_warning(false); // File › Revert replaces the document in its tab, keeps the tab's view and starts the tool afresh. @@ -328,10 +328,11 @@ impl VectorcraftApp { r } - /// After a Copy or Cut `id` that ran: offer what it copied to other apps - /// ([`Self::publish_clipboard`]) → whether `id` is one. - fn publish_copy(&mut self, id: &str) -> bool { - let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut"); + /// After a Copy or Cut `id` that ran, or a script run to its end (`reply` without `running`) + /// that reports `copied`: offer what it copied to other apps ([`Self::publish_clipboard`]) → + /// whether it did. + fn publish_copy(&mut self, id: &str, reply: &Value) -> bool { + let copy = matches!(id, "edit.copy" | "edit.cut" | "artboard.copy" | "artboard.cut") || (id == "script.run" && reply["copied"] == true); if copy { self.publish_clipboard(matches!(id, "edit.cut" | "artboard.cut")); } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..64c8198d2e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -35,10 +35,15 @@ pub fn poll(app: &mut VectorcraftApp) { script_run::settle_close(app); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. - Ok(_) => { + Ok(report) => { if !crate::panels::actions::after_journaled_edit(app) { app.status(format!("Ran {name}")); } + // What the script's Copy or Cut left on the clipboard is offered to other apps, as + // Edit › Copy does. + if report["copied"] == true { + app.publish_clipboard(false); + } } Err(e) => failed(app, e.to_string()), } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..d08e3bb4bb 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -640,6 +640,66 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +#[test] +fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.clipboard_out = None; + let draw = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": draw })).unwrap().unwrap(); + finish(&mut app); + assert!(app.clipboard_out.is_none(), "a run without a Copy offers nothing"); + let copy = "vc.run('select.all', {}); app.copy();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": copy })).unwrap().unwrap(); + finish(&mut app); + assert!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains("'});"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": import })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(app.clipboard_out.is_none()); + // An import in a batch that fails and is rolled back leaves the copied clipboard to be offered. + let rolled_back = "app.copy(); try { vc.run('command.batch', {commands: [{command: 'clipboard.importSvg', params: {svg: ''}}, {command: 'no.such', params: {}}]}); } \ + catch (e) {}"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": rolled_back })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(app.clipboard_out.is_some()); + // A run that copies and then fails leaves the clipboard and what other apps were offered alone. + app.clipboard_out = None; + let fails = "app.cut(); throw new Error('stop');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": fails })).unwrap().unwrap(); + finish(&mut app); + assert!(app.clipboard_out.is_none()); + assert_eq!(objects(&app), 1); + // A Copy with nothing selected copies nothing, and other apps keep what they were offered. + let empty = "vc.run('select.none', {}); app.copy();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": empty })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.ui.status, "Ran script"); + assert!(app.clipboard_out.is_none()); + // A run that automation takes to its end at once offers its Copy too. + app.session.script_frames = false; + let reply = app.run("script.run", json!({ "source": copy, "name": "t.js" })).unwrap(); + assert_eq!(reply["copied"], true); + assert!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains(" Date: Sat, 21 Nov 2026 18:51:00 -0800 Subject: [PATCH 013/533] Scripts: PlacedItem.file checks the script's own read scope, not open documents Reading file of a placed image linked to a file outside the script's read scope throws Script file access denied even when that file is also open as a document, whose file the script's commands may read. --- crates/engine/src/script/dom/images.rs | 6 +++--- crates/engine/src/tests/script_dom_images.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index bf79f77013..dc5417c318 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -289,10 +289,10 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer { // ---- files ---- -/// Whether the script's commands may read `path` now ([`crate::file_access::ScriptGate`]). +/// Whether the script may read `path` now by its own read scope and the read roots +/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read. fn may_read(h: &Host, path: &str) -> bool { - let documents = h.session.borrow().documents().iter().filter_map(|d| d.path.clone()).collect(); - let gate = h.disk.borrow().gate(documents); + let gate = h.disk.borrow().gate(Vec::new()); crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok() } diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 674d098eb5..1c1a78d864 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -411,6 +411,20 @@ fn image_file_getter_hides_out_of_scope_link() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { + let base = folder("hidedoc"); + let b = base.join("outside/secret.png"); + std::fs::write(&b, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &b, true); + // The linked file is also the file of an open document, which the script's commands may read. + s.doc_mut().unwrap().path = Some(b.to_string_lossy().into_owned()); + let e = failure(&mut s, &base, "vc.log(app.activeDocument.placedItems[0].file.fsName);"); + assert!(e.contains("Script file access denied") && !e.contains("secret"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn stale_and_foreign_placed_items_are_refused() { let base = folder("stale"); From 0af60ffc379f8599bf95bc70ba7f374b5f249a1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:03:34 -0800 Subject: [PATCH 014/533] Scripts: the confirm before the external script warning turns off is translated MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The question a run asks before a script sets ShowExternalJSXWarning to false has a row in every complete-message catalog, with a test that each of them translates it. - Russian and Ukrainian name File › Scripts › Other Script… as another script rather than another writing system. - A preference key's limit is stated as a length of 1 to 256 UTF-16 code units, the count the code checks, in the error and in docs/mcp.md; a test covers keys of characters outside the Basic Multilingual Plane. - The host name check lists Preferences, the matrix functions and app.copy, cut and paste; the preference setters and removePreference carry the checker's preferences id. --- crates/engine/src/script/dom/preferences.rs | 4 +++- crates/engine/src/tests/script_dom_prefs.rs | 6 +++++- .../tests/it/script_host_vs_scriptcheck.rs | 19 +++++++++++++++---- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 3 ++- crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 11 +++++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 3 ++- crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 5 +++-- 30 files changed, 64 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index 064f4fa39d..e1c25e387e 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -90,7 +90,9 @@ fn key_of(a: &[Data]) -> std::result::Result<&str, HostError> { } let Data::String(key) = arg(a, 1) else { return Err(HostError::Type("a preference's key must be a string".into())) }; if key.is_empty() || key.encode_utf16().count() > MAX_KEY_UNITS { - return Err(HostError::Range(format!("a preference's key must have 1 to {MAX_KEY_UNITS} characters"))); + return Err(HostError::Range(format!( + "a preference's key must have a length of 1 to {MAX_KEY_UNITS} (UTF-16 code units, as `length` counts)" + ))); } if key.chars().any(char::is_control) { return Err(HostError::Error("a preference's key cannot hold control characters".into())); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 548f0cee07..d8bb4dd77d 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -226,6 +226,8 @@ fn bad_arguments_throw_and_store_nothing() { ("app.preferences.getBooleanPreference();", "key must be a string"), ("app.preferences.setStringPreference('', 'v');", "1 to 256"), ("app.preferences.setStringPreference(new Array(258).join('k'), 'v');", "1 to 256"), + // 129 characters outside the Basic Multilingual Plane are 258 UTF-16 code units. + ("app.preferences.setStringPreference(new Array(130).join('\\uD83D\\uDE00'), 'v');", "1 to 256"), ("app.preferences.setStringPreference('a\\u0000b', 'v');", "control characters"), ("app.preferences.setStringPreference('k', new Array(65538).join('v'));", "at most 65536 bytes"), ("var f = app.preferences.getBooleanPreference; f.call({}, 'k');", "not a Preferences"), @@ -238,9 +240,11 @@ fn bad_arguments_throw_and_store_nothing() { } assert!(wrong.is_empty(), "{wrong:#?}"); assert!(s.prefs.script_preferences.is_empty()); - // A key of exactly 256 characters and a value of exactly the limit are taken. + // A key of exactly 256 code units and a value of exactly the limit are taken. log(&mut s, "app.preferences.setStringPreference(new Array(257).join('k'), new Array(65537).join('v'));"); assert_eq!(stored(&s, &"k".repeat(256)), Some(ScriptPreference::String("v".repeat(MAX_STRING_BYTES)))); + log(&mut s, "app.preferences.setStringPreference(new Array(129).join('\\uD83D\\uDE00'), 'v');"); + assert_eq!(stored(&s, &"\u{1F600}".repeat(128)), Some(ScriptPreference::String("v".into()))); } #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..df796262af 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,12 +37,19 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Preferences.prototype.setBooleanPreference", "app.preferences.setBooleanPreference(k, true);", "preferences"), + ("Preferences.prototype.setIntegerPreference", "app.preferences.setIntegerPreference(k, 1);", "preferences"), + ("Preferences.prototype.setRealPreference", "app.preferences.setRealPreference(k, 0.5);", "preferences"), + ("Preferences.prototype.setStringPreference", "app.preferences.setStringPreference(k, s);", "preferences"), + ("Preferences.prototype.removePreference", "app.preferences.removePreference(k);", "preferences"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// documents; `Document.saveAs` and `close` throw "not available yet". Reading a preference changes +/// nothing, and the matrix functions return new records. `app.copy` and `app.cut` fill VectorCraft's +/// clipboard, which the desktop app offers to other apps after the run as Edit › Copy does. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -75,14 +82,18 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems Preferences RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \ + concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents getIdentityMatrix \ + getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix paste \ + preferences selection typename", ), + ("Preferences.", "prototype"), + ("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"), ("DocumentPreset.", "prototype"), ( "DocumentPreset.prototype.", diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..88452d82bc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6437,6 +6437,7 @@ digits Malayalam Malaiàlam @msg a drag or an undo group is open; finish it before running a script hi ha un arrossegament o un grup de desfer obert; acabeu-lo abans d'executar un script @msg the script left a document that cannot be kept l'script ha deixat un document que no es pot conservar @msg the script is no longer in the Scripts folder l'script ja no és a la carpeta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? L'script demana desactivar l'avís que es mostra abans que s'executi un script triat amb Fitxer › Scripts › Un altre script… Els scripts triats després s'executarien sense l'avís. Voleu desactivar l'avís? Some scripts were not listed Alguns scripts no s'han llistat The Scripts folder cannot be read No es pot llegir la carpeta Scripts Loading scripts… S’estan carregant els scripts… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..d9f3c1fa55 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5245,6 +5245,7 @@ imageTrace Outline Obrys @msg a drag or an undo group is open; finish it before running a script je otevřené tažení nebo skupina kroků zpět; před spuštěním skriptu ji dokončete @msg the script left a document that cannot be kept skript zanechal dokument, který nelze zachovat @msg the script is no longer in the Scripts folder skript už není ve složce Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skript žádá o vypnutí upozornění, které se zobrazí před spuštěním skriptu vybraného příkazem Soubor › Skripty › Jiný skript… Později vybrané skripty by se pak spouštěly bez něj. Vypnout upozornění? Some scripts were not listed Některé skripty nebyly uvedeny The Scripts folder cannot be read Složku Scripts nelze přečíst Loading scripts… Načítání skriptů… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..cd7f60bfcc 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -63,6 +63,7 @@ @msg a drag or an undo group is open; finish it before running a script en trækning eller en fortrydelsesgruppe er åben; afslut den, før du kører et script @msg the script left a document that cannot be kept scriptet efterlod et dokument, der ikke kan beholdes @msg the script is no longer in the Scripts folder scriptet ligger ikke længere i mappen Scripter +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Scriptet beder om at slå advarslen fra, som vises, før et script, der er valgt med Filer › Scripter › Andet script…, køres. Scripter, der vælges senere, ville så køre uden den. Vil du slå advarslen fra? @msg the script's run is no longer available scriptets kørsel er ikke længere tilgængelig @msg a failed command changed undo steps that could not be put back, so the script was stopped en mislykket kommando ændrede fortrydelsestrin, der ikke kunne genskabes, så scriptet blev stoppet @msg a recovery copy could not be written, so the script was not run en gendannelseskopi kunne ikke skrives, så scriptet blev ikke kørt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..eed3f358c7 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4830,6 +4830,7 @@ theme Appearance Erscheinungsbild @msg a drag or an undo group is open; finish it before running a script ein Ziehvorgang oder eine Rückgängig-Gruppe ist offen; schließen Sie sie ab, bevor Sie ein Skript ausführen @msg the script left a document that cannot be kept das Skript hat ein Dokument hinterlassen, das nicht behalten werden kann @msg the script is no longer in the Scripts folder das Skript befindet sich nicht mehr im Ordner „Scripts“ +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Das Skript möchte die Warnung ausschalten, die angezeigt wird, bevor ein mit „Datei › Skripte › Anderes Skript…“ gewähltes Skript ausgeführt wird. Später gewählte Skripte würden dann ohne sie ausgeführt. Warnung ausschalten? Some scripts were not listed Einige Skripte wurden nicht aufgeführt The Scripts folder cannot be read Der Ordner „Scripts“ kann nicht gelesen werden Loading scripts… Skripte werden geladen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..cd7b98a516 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2634,6 +2634,7 @@ axis Both Και τα δύο @msg a drag or an undo group is open; finish it before running a script είναι ανοιχτή μια μεταφορά ή ομάδα αναίρεσης· ολοκληρώστε την πριν εκτελέσετε σενάριο @msg the script left a document that cannot be kept το σενάριο άφησε ένα έγγραφο που δεν μπορεί να διατηρηθεί @msg the script is no longer in the Scripts folder το σενάριο δεν βρίσκεται πλέον στον φάκελο Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Το σενάριο ζητά να απενεργοποιηθεί η προειδοποίηση που εμφανίζεται πριν εκτελεστεί ένα σενάριο που επιλέχθηκε με Αρχείο › Δέσμες ενεργειών › Άλλο σενάριο… Τα σενάρια που θα επιλεγούν αργότερα θα εκτελούνται τότε χωρίς αυτήν. Να απενεργοποιηθεί η προειδοποίηση; Some scripts were not listed Ορισμένα σενάρια δεν εμφανίζονται στη λίστα The Scripts folder cannot be read Δεν είναι δυνατή η ανάγνωση του φακέλου Scripts Loading scripts… Φόρτωση σεναρίων… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..a22748a73d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4909,6 +4909,7 @@ axis Both Ambos @msg a drag or an undo group is open; finish it before running a script hay un arrastre o un grupo de deshacer abierto; termínelo antes de ejecutar un script @msg the script left a document that cannot be kept el script dejó un documento que no se puede conservar @msg the script is no longer in the Scripts folder el script ya no está en la carpeta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? El script pide desactivar la advertencia que se muestra antes de que se ejecute un script elegido con Archivo › Scripts › Otro script… Los scripts elegidos después se ejecutarían sin ella. ¿Desactivar la advertencia? Some scripts were not listed Algunos scripts no se han incluido en la lista The Scripts folder cannot be read No se puede leer la carpeta Scripts Loading scripts… Cargando scripts… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..e35bc338b3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5150,6 +5150,7 @@ imageTrace Outline Ääriviiva @msg a drag or an undo group is open; finish it before running a script vetäminen tai kumousryhmä on kesken; viimeistele se ennen komentosarjan suorittamista @msg the script left a document that cannot be kept komentosarja jätti asiakirjan, jota ei voi säilyttää @msg the script is no longer in the Scripts folder komentosarja ei ole enää Scripts-kansiossa +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Komentosarja pyytää poistamaan käytöstä varoituksen, joka näytetään ennen kuin komennolla Tiedosto › Komentosarjat › Muu komentosarja… valittu komentosarja suoritetaan. Myöhemmin valitut komentosarjat suoritettaisiin silloin ilman sitä. Poistetaanko varoitus käytöstä? Some scripts were not listed Kaikkia komentosarjoja ei ole lueteltu The Scripts folder cannot be read Scripts-kansiota ei voi lukea Loading scripts… Ladataan komentosarjoja… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..cf94949ece 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4891,6 +4891,7 @@ axis Both Les deux @msg a drag or an undo group is open; finish it before running a script un glissement ou un groupe d’annulation est ouvert ; terminez-le avant d’exécuter un script @msg the script left a document that cannot be kept le script a laissé un document qui ne peut pas être conservé @msg the script is no longer in the Scripts folder le script ne se trouve plus dans le dossier Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Le script demande à désactiver l’avertissement affiché avant l’exécution d’un script choisi avec Fichier › Scripts › Autre script… Les scripts choisis ensuite s’exécuteraient alors sans lui. Désactiver l’avertissement ? Some scripts were not listed Certains scripts ne sont pas répertoriés The Scripts folder cannot be read Impossible de lire le dossier Scripts Loading scripts… Chargement des scripts… diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..053d291e17 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7583,6 +7583,7 @@ arrowhead Feather पंख @msg a drag or an undo group is open; finish it before running a script कोई ड्रैग या पूर्ववत समूह खुला है; स्क्रिप्ट चलाने से पहले उसे पूरा करें @msg the script left a document that cannot be kept स्क्रिप्ट ने ऐसा दस्तावेज़ छोड़ा है जिसे रखा नहीं जा सकता @msg the script is no longer in the Scripts folder स्क्रिप्ट अब Scripts फ़ोल्डर में नहीं है +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? स्क्रिप्ट उस चेतावनी को बंद करना चाहती है जो फ़ाइल › स्क्रिप्ट्स › अन्य स्क्रिप्ट… से चुनी गई स्क्रिप्ट चलने से पहले दिखाई जाती है। इसके बाद चुनी गई स्क्रिप्ट्स उसके बिना चलेंगी। चेतावनी बंद करें? Some scripts were not listed कुछ स्क्रिप्ट सूचीबद्ध नहीं की गईं The Scripts folder cannot be read Scripts फ़ोल्डर पढ़ा नहीं जा सकता Loading scripts… स्क्रिप्ट लोड हो रही हैं… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..0253ef4aa3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5762,6 +5762,7 @@ imageTrace Outline Körvonal @msg a drag or an undo group is open; finish it before running a script húzás vagy visszavonási csoport van folyamatban; fejezze be a parancsfájl futtatása előtt @msg the script left a document that cannot be kept a parancsfájl olyan dokumentumot hagyott hátra, amely nem tartható meg @msg the script is no longer in the Scripts folder a parancsfájl már nincs a Scripts mappában +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? A parancsfájl ki szeretné kapcsolni azt a figyelmeztetést, amely a Fájl › Szkriptek › Másik szkript… paranccsal kiválasztott parancsfájl futása előtt jelenik meg. A később kiválasztott parancsfájlok ezután nélküle futnának. Kikapcsolja a figyelmeztetést? Some scripts were not listed Néhány szkript nem szerepel a listában The Scripts folder cannot be read A Scripts mappa nem olvasható Loading scripts… Szkriptek betöltése… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..a5ef5115d8 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -63,6 +63,7 @@ @msg a drag or an undo group is open; finish it before running a script seretan atau grup urungkan sedang terbuka; selesaikan sebelum menjalankan skrip @msg the script left a document that cannot be kept skrip meninggalkan dokumen yang tidak dapat dipertahankan @msg the script is no longer in the Scripts folder skrip tidak lagi berada di folder Skrip +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skrip meminta untuk mematikan peringatan yang ditampilkan sebelum skrip yang dipilih dengan Berkas › Skrip › Skrip lain… dijalankan. Skrip yang dipilih kemudian akan berjalan tanpa peringatan itu. Matikan peringatan? @msg the script's run is no longer available proses skrip tidak lagi tersedia @msg a failed command changed undo steps that could not be put back, so the script was stopped perintah yang gagal mengubah langkah urungkan yang tidak dapat dikembalikan, sehingga skrip dihentikan @msg a recovery copy could not be written, so the script was not run salinan pemulihan tidak dapat ditulis, sehingga skrip tidak dijalankan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c3404d2489 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4968,6 +4968,7 @@ axis Both Entrambi @msg a drag or an undo group is open; finish it before running a script è aperto un trascinamento o un gruppo di annullamento; completalo prima di eseguire uno script @msg the script left a document that cannot be kept lo script ha lasciato un documento che non può essere conservato @msg the script is no longer in the Scripts folder lo script non è più nella cartella Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Lo script chiede di disattivare l'avviso mostrato prima che venga eseguito uno script scelto con File › Script › Altro script… Gli script scelti in seguito verrebbero quindi eseguiti senza avviso. Disattivare l'avviso? Some scripts were not listed Alcuni script non sono stati elencati The Scripts folder cannot be read Impossibile leggere la cartella Scripts Loading scripts… Caricamento degli script… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..713ec6687d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5794,6 +5794,7 @@ variable-list-end {0}, {1} {0}、{1} @msg a drag or an undo group is open; finish it before running a script ドラッグまたは取り消しグループが開いています。スクリプトを実行する前に完了してください @msg the script left a document that cannot be kept スクリプトが保持できないドキュメントを残しました @msg the script is no longer in the Scripts folder スクリプトは Scripts フォルダーにもうありません +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? スクリプトが、ファイル › スクリプト › その他のスクリプト… で選んだスクリプトを実行する前に表示される警告をオフにしようとしています。オフにすると、以後に選んだスクリプトは警告なしで実行されます。警告をオフにしますか? Some scripts were not listed 一部のスクリプトは一覧に表示されていません The Scripts folder cannot be read Scripts フォルダーを読み込めません Loading scripts… スクリプトを読み込み中… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ba497492da 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8463,6 +8463,7 @@ imageTrace Outline კონტური @msg a drag or an undo group is open; finish it before running a script ღიაა გადათრევა ან გაუქმების ჯგუფი; დაასრულეთ სკრიპტის გაშვებამდე @msg the script left a document that cannot be kept სკრიპტმა დატოვა დოკუმენტი, რომლის შენახვა შეუძლებელია @msg the script is no longer in the Scripts folder სკრიპტი აღარ არის Scripts საქაღალდეში +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? სკრიპტი ითხოვს იმ გაფრთხილების გამორთვას, რომელიც ჩანს ბრძანებით ფაილი › სკრიპტები › სხვა სკრიპტი… არჩეული სკრიპტის გაშვებამდე. შემდეგ არჩეული სკრიპტები მის გარეშე გაეშვება. გამოირთოს გაფრთხილება? Some scripts were not listed ზოგიერთი სკრიპტი არ არის ჩამოთვლილი The Scripts folder cannot be read Scripts საქაღალდის წაკითხვა შეუძლებელია Loading scripts… სკრიპტების ჩატვირთვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..d408d91cd9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5723,6 +5723,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg a drag or an undo group is open; finish it before running a script 드래그 또는 실행 취소 그룹이 열려 있습니다. 스크립트를 실행하기 전에 완료하세요 @msg the script left a document that cannot be kept 스크립트가 유지할 수 없는 문서를 남겼습니다 @msg the script is no longer in the Scripts folder 스크립트가 더 이상 Scripts 폴더에 없습니다 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 스크립트가 파일 › 스크립트 › 다른 스크립트…로 선택한 스크립트를 실행하기 전에 표시되는 경고를 끄려고 합니다. 그러면 이후에 선택한 스크립트는 경고 없이 실행됩니다. 경고를 끌까요? Some scripts were not listed 일부 스크립트가 나열되지 않았습니다 The Scripts folder cannot be read Scripts 폴더를 읽을 수 없습니다 Loading scripts… 스크립트 불러오는 중… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..b048ba2e6b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -63,6 +63,7 @@ @msg a drag or an undo group is open; finish it before running a script er is nog een sleepbeweging of een groep voor ongedaan maken open; rond die af voordat je een script uitvoert @msg the script left a document that cannot be kept het script heeft een document achtergelaten dat niet kan worden behouden @msg the script is no longer in the Scripts folder het script staat niet meer in de map Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Het script vraagt de waarschuwing uit te zetten die wordt getoond voordat een script wordt uitgevoerd dat is gekozen met Bestand › Scripts › Ander script… Scripts die later worden gekozen, worden dan zonder waarschuwing uitgevoerd. Waarschuwing uitzetten? @msg the script's run is no longer available de uitvoering van het script is niet meer beschikbaar @msg a failed command changed undo steps that could not be put back, so the script was stopped een mislukte opdracht heeft stappen voor ongedaan maken gewijzigd die niet konden worden teruggezet, dus is het script gestopt @msg a recovery copy could not be written, so the script was not run er kon geen herstelkopie worden geschreven, dus is het script niet uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..3e6d6901df 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5073,6 +5073,7 @@ imageTrace Outline Kontur @msg a drag or an undo group is open; finish it before running a script otwarte jest przeciąganie lub grupa cofania; zakończ je przed uruchomieniem skryptu @msg the script left a document that cannot be kept skrypt pozostawił dokument, którego nie można zachować @msg the script is no longer in the Scripts folder skryptu nie ma już w folderze Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skrypt prosi o wyłączenie ostrzeżenia wyświetlanego przed uruchomieniem skryptu wybranego poleceniem Plik › Skrypty › Inny skrypt… Skrypty wybrane później byłyby wtedy uruchamiane bez niego. Wyłączyć ostrzeżenie? Some scripts were not listed Niektóre skrypty nie zostały wyświetlone The Scripts folder cannot be read Nie można odczytać folderu Scripts Loading scripts… Wczytywanie skryptów… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..9c58266b69 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6112,6 +6112,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a drag or an undo group is open; finish it before running a script há um arraste ou um grupo de desfazer aberto; conclua-o antes de executar um script @msg the script left a document that cannot be kept o script deixou um documento que não pode ser mantido @msg the script is no longer in the Scripts folder o script não está mais na pasta Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? O script pede para desativar o aviso mostrado antes de executar um script escolhido em Arquivo › Scripts › Outro Script… Os scripts escolhidos depois seriam executados sem ele. Desativar o aviso? Some scripts were not listed Alguns scripts não foram listados The Scripts folder cannot be read Não é possível ler a pasta Scripts Loading scripts… Carregando scripts… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..26be93af2d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2740,7 +2740,7 @@ file-filter Templates Шаблоны Other Layers Другие слои Other Libraries Другие библиотеки Other Library… Другая библиотека… - Other Script… Другая письменность… + Other Script… Другой скрипт… Out of Gamut Warning Предупреждение о выходе из цветового охвата Out of Web Color Warning Предупреждение о цвете, не поддерживаемом web Out Tangent Handles Маркеры исходящей касательной @@ -4944,6 +4944,7 @@ axis Both Оба @msg a drag or an undo group is open; finish it before running a script открыто перетаскивание или группа отмены; завершите их перед запуском скрипта @msg the script left a document that cannot be kept скрипт оставил документ, который нельзя сохранить @msg the script is no longer in the Scripts folder скрипт больше не находится в папке Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скрипт просит отключить предупреждение, которое показывается перед запуском скрипта, выбранного командой Файл › Сценарии › Другой скрипт… Выбранные позже скрипты будут запускаться без него. Отключить предупреждение? Some scripts were not listed Некоторые сценарии не показаны The Scripts folder cannot be read Не удалось прочитать папку Scripts Loading scripts… Загрузка сценариев… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..539e4538df 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4806,6 +4806,7 @@ axis Both Båda @msg a drag or an undo group is open; finish it before running a script en dragning eller ångragrupp är öppen; avsluta den innan du kör ett skript @msg the script left a document that cannot be kept skriptet lämnade ett dokument som inte kan behållas @msg the script is no longer in the Scripts folder skriptet finns inte längre i mappen Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Skriptet vill stänga av varningen som visas innan ett skript som valts med Fil › Skript › Annat skript… körs. Skript som väljs senare skulle då köras utan den. Stänga av varningen? Some scripts were not listed Vissa skript visas inte i listan The Scripts folder cannot be read Mappen Scripts kan inte läsas Loading scripts… Läser in skript… diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..d0495d9cdb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -717,6 +717,17 @@ fn compound_shape_no_area_warning_is_translated() { } } +/// The confirm a run shows before a script turns off the external script warning, which the message +/// scan doesn't read, is translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn script_warning_off_question_is_translated() { + let question = vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, question), question, "{code}"); + } +} + /// The Save PDF dialog's Save Summary… button and `ui.pdfSummary.save`'s error when no such /// dialog is open. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..daf4e1c36e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4666,6 +4666,7 @@ axis Both Her İkisi @msg a drag or an undo group is open; finish it before running a script bir sürükleme veya geri alma grubu açık; betiği çalıştırmadan önce tamamlayın @msg the script left a document that cannot be kept betik, saklanamayan bir belge bıraktı @msg the script is no longer in the Scripts folder betik artık Scripts klasöründe değil +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Komut dosyası, Dosya › Komut dosyaları › Diğer Komut Dosyası… ile seçilen bir komut dosyası çalışmadan önce gösterilen uyarıyı kapatmak istiyor. Daha sonra seçilen komut dosyaları bu durumda uyarı olmadan çalışır. Uyarı kapatılsın mı? Some scripts were not listed Bazı komut dosyaları listelenmedi The Scripts folder cannot be read Scripts klasörü okunamıyor Loading scripts… Betikler yükleniyor… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..5cbd4ef024 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2748,7 +2748,7 @@ file-filter Templates Шаблони Other Layers Інші шари Other Libraries Інші бібліотеки Other Library… Інша бібліотека… - Other Script… Інша писемність… + Other Script… Інший скрипт… Out of Gamut Warning Попередження про вихід із колірного охоплення Out of Web Color Warning Попередження про колір, що не підтримується web Out Tangent Handles Маркери вихідної дотичної @@ -4952,6 +4952,7 @@ axis Both Обидві @msg a drag or an undo group is open; finish it before running a script відкрито перетягування або групу скасування; завершіть їх перед запуском скрипта @msg the script left a document that cannot be kept скрипт залишив документ, який не можна зберегти @msg the script is no longer in the Scripts folder скрипт більше не міститься в папці Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скрипт просить вимкнути попередження, яке показується перед запуском скрипту, вибраного командою Файл › Сценарії › Інший скрипт… Вибрані пізніше скрипти тоді запускатимуться без нього. Вимкнути попередження? Some scripts were not listed Деякі сценарії не показано The Scripts folder cannot be read Не вдалося прочитати папку Scripts Loading scripts… Завантаження сценаріїв… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..f2def46d53 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5430,6 +5430,7 @@ theme Appearance Giao diện @msg a drag or an undo group is open; finish it before running a script đang có thao tác kéo hoặc nhóm hoàn tác; hãy hoàn thành trước khi chạy tập lệnh @msg the script left a document that cannot be kept tập lệnh để lại một tài liệu không thể giữ @msg the script is no longer in the Scripts folder tập lệnh không còn trong thư mục Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Tập lệnh yêu cầu tắt cảnh báo hiển thị trước khi chạy một tập lệnh được chọn bằng Tệp › Script › Script khác… Các tập lệnh được chọn sau đó sẽ chạy mà không có cảnh báo. Tắt cảnh báo? Some scripts were not listed Một số tập lệnh không được liệt kê The Scripts folder cannot be read Không thể đọc thư mục Scripts Loading scripts… Đang tải tập lệnh… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..a90fa539c6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5459,6 +5459,7 @@ imageTrace Outline 轮廓 @msg a drag or an undo group is open; finish it before running a script 拖动或撤销组尚未结束;请在运行脚本前完成 @msg the script left a document that cannot be kept 脚本留下了无法保留的文档 @msg the script is no longer in the Scripts folder 脚本已不在 Scripts 文件夹中 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 脚本请求关闭在运行通过“文件 › 脚本 › 其他脚本…”选择的脚本前显示的警告。关闭后,之后选择的脚本将在没有警告的情况下运行。要关闭警告吗? Some scripts were not listed 部分脚本未列出 The Scripts folder cannot be read 无法读取 Scripts 文件夹 Loading scripts… 正在载入脚本… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..6df3af8b96 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2805,6 +2805,7 @@ file-filter Templates 範本 @msg a drag or an undo group is open; finish it before running a script 拖曳或還原群組尚未結束;請在執行指令碼前完成 @msg the script left a document that cannot be kept 指令碼留下了無法保留的文件 @msg the script is no longer in the Scripts folder 指令碼已不在 Scripts 資料夾中 +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? 指令碼要求關閉在執行透過 檔案 › 指令碼 › 其他指令碼… 選擇的指令碼前顯示的警告。關閉後,之後選擇的指令碼將在沒有警告的情況下執行。要關閉警告嗎? Some scripts were not listed 部分指令碼未列出 The Scripts folder cannot be read 無法讀取 Scripts 資料夾 Loading scripts… 正在載入指令碼… diff --git a/docs/mcp.md b/docs/mcp.md index b7ac4fd981..6ce10d6a50 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2697,8 +2697,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot stored with the preferences under `scriptPreferences`, with the type they were set as, and are kept across runs and restarts; a run that fails or is stopped puts them back. VectorCraft's own rules: a key that was never set reads as `false`, `0`, `0` or `""`; a getter of another type converts the value as `Boolean`, `Number` and `String` do, and `getIntegerPreference` drops the fraction and gives - `0` for a value that is not a number. A key has 1 to 256 characters and no control characters, a string value at - most 65,536 bytes, and the store at most 4,096 keys and 1,048,576 bytes (each value that is not a string counts 8); + `0` for a value that is not a number. A key has a `length` of 1 to 256 UTF-16 code units (a character outside + the Basic Multilingual Plane, such as an emoji, counts 2) and no control characters, a string value at most + 65,536 bytes, and the store at most 4,096 keys and 1,048,576 bytes (each value that is not a string counts 8); `setIntegerPreference` takes a whole number within ±2^53 and `setRealPreference` a finite number. A value of the wrong type or past a limit throws an error and stores nothing, and removing a key that is not stored does nothing. - `app.getIdentityMatrix()`, `getTranslationMatrix(deltaX?, deltaY?)` (points), `getScaleMatrix(scaleX?, scaleY?)` From f0a1e6398f0a1cdb2da853085e79b28ffd02a258 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:04:35 -0800 Subject: [PATCH 015/533] Scripts: image removeAll keeps art on a locked artboard; setters check the item first placedItems.removeAll() and rasterItems.removeAll() checked only whether each image and its layers and groups were shown and unlocked, then passed the ids to edit.clear, which deletes named objects without checking artboard locks. Both now throw "cannot delete objects on a locked artboard" with the image ids and delete nothing, as pageItems.removeAll() does. Assigning matrix read the value before the item, so a stale image or an add() result without a file threw the matrix error. Assigning file to an add() result that was placed and then embedded threw "PlacedItem.file is read-only: use relink". Both now check the item first and throw "Stale page item" or "PlacedItem.file is required". A File that a host class member returns now charges its new path string to the script heap, in the same reservation as the File object. docs/gaps.md G6 and the M13 row in docs/roadmap.md list the placed and raster image classes; docs/mcp.md states the removeAll and setter rules. --- crates/engine/src/script/dom/images.rs | 21 +++++--- crates/engine/src/tests/script_dom_images.rs | 56 ++++++++++++++++++++ crates/js/src/file_classes.rs | 17 ++++-- crates/js/src/host_tests.rs | 18 +++++++ docs/gaps.md | 3 +- docs/mcp.md | 5 +- docs/roadmap.md | 2 +- 7 files changed, 110 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index dc5417c318..25aaaaa0ad 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -40,8 +40,9 @@ use vectorcraft_geom::{Affine, Point}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, editable, find_doc, - float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, with_doc, + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, + editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, + with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -218,19 +219,26 @@ fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer { } /// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or -/// one in a hidden or locked layer or group, stops it before anything is deleted. +/// one in a hidden or locked layer or group, stops it before anything is deleted, and so does one on +/// a locked artboard. fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer { let doc = list_doc(h, a, placed)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = images(h, st, placed)?; let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -374,6 +382,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { }; let k = slot_of(h, run, uid, slot)?; if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) { + this_of(h, a, "PlacedItem")?; return Err(HostError::Error(FILE_READ_ONLY.into())); } let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -469,8 +478,8 @@ fn area_of(m: Affine) -> bool { /// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted /// image is refused before anything changes; the matrix the image has already changes nothing. fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { - let m = matrix_value(arg(a, 1))?; let item = this_of(h, a, cls)?; + let m = matrix_value(arg(a, 1))?; let delta = with_doc(h, item.doc, |_, st| { let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else { return Err(HostError::Error(STALE_ITEM.into())); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 1c1a78d864..594582e9f9 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -425,6 +425,62 @@ fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { let _ = std::fs::remove_dir_all(base); } +/// Assigning `file` or `matrix` checks the item before the value: an `add()` result with no file +/// throws `PlacedItem.file is required`, and one that was embedded throws `Stale page item`. +#[test] +fn assignments_check_the_item_before_the_value() { + let base = folder("receiver"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, n = d.placedItems.add(), p = d.placedItems.add(), m = [];\ + try {{ n.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + p.file = new File('{0}'); p.embed();\ + try {{ p.file = new File('{0}'); }} catch (e) {{ m.push(e.message); }}\ + try {{ p.matrix = null; }} catch (e) {{ m.push(e.message); }}\ + try {{ d.rasterItems[0].matrix = null; }} catch (e) {{ m.push(e.name); }}\ + vc.log(m);", + js_path(&a) + ), + ); + assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "Stale page item", "TypeError"])]); + let _ = std::fs::remove_dir_all(base); +} + +/// `removeAll()` deletes no image when one is on a locked artboard, in both collections. +#[test] +fn remove_all_keeps_images_on_a_locked_artboard() { + let base = folder("locked-board"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + let linked = place(&mut s, &a, true); + let embedded = place(&mut s, &a, false); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, &base, "app.activeDocument.placedItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", linked.0)), "{e}"); + let e = failure(&mut s, &base, "app.activeDocument.rasterItems.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", embedded.0)), "{e}"); + assert_eq!(images(&s).len(), 2); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.placedItems.removeAll(); d.rasterItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn stale_and_foreign_placed_items_are_refused() { let base = folder("stale"); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index b6bf5a3388..cb5d838b3f 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -195,10 +195,20 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { + new_instance(i, proto, fs, false) +} + +/// [`instance`], which also charges the heap for the string of `fs` when `charge_path` is set, for +/// a path string made for the new object alone. +fn new_instance(i: &mut Interp, proto: ObjId, fs: Value, charge_path: bool) -> JsResult { let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; i.rooted(&[fs, line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?; + let path_bytes = string_bytes(path.len()); + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + path_bytes)?; + if charge_path { + i.heap.bytes = i.heap.bytes.saturating_add(path_bytes); + } let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { set_slot(i, o, ERROR, Value::str(""))?; @@ -1153,10 +1163,11 @@ pub fn file_ref(path: &str) -> crate::Data { } impl Interp { - /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). + /// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). The new string + /// of the path is charged to the heap, as [`crate::Data::String`] is when it is written. pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult { let proto = classes(self)?.file_proto; - instance(self, proto, Value::str(path)) + new_instance(self, proto, Value::str(path), true) } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 13aa5f8560..c7190dc726 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -685,6 +685,24 @@ fn a_read_of_a_class_on_another_branch_gives_a_new_object() { assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into())); } +/// The path of a `File` a member of a host class gives is charged to the heap. +#[test] +fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() { + let bytes_after = |len: usize| { + let mut r = realm(1_000_000); + let current: HostFunction = Rc::new(|_| Ok(Data::String("d".into()))); + r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap(); + let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len)))); + let members = vec![("file".to_string(), HostMember::Method(file))]; + let maker = HostClass { name: "Maker".into(), parent: None, members, index: None, construct: None }; + r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap(); + assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true))); + r.interp().heap.bytes + }; + let (short, long) = (bytes_after(1), bytes_after(100_000)); + assert!(long >= short + 2 * 99_999, "{short} {long}"); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..fc32f5b719 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and + `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 98735f67e2..27b004237d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2751,7 +2751,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point - a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the + a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete + objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the + item before the value, so a stale item throws `Stale page item` and an `add()` result without a file throws + `PlacedItem.file is required` whatever the value. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..1e4ca34d9b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`PlacedItem` and `RasterItem`); the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 91bd652bd707accb87e902f3f53169311c305a20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:43:47 -0800 Subject: [PATCH 016/533] Docs: placed image file assignment places the image on an add() result Assigning `file` to a `placedItems.add()` result without a file checks the file and places the image; only assigning `matrix` to such a result throws `PlacedItem.file is required`. A stale item throws `Stale page item` for both setters. --- docs/mcp.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 27b004237d..72826fb91d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2753,9 +2753,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the - item before the value, so a stale item throws `Stale page item` and an `add()` result without a file throws - `PlacedItem.file is required` whatever the value. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the - end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. + item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` + result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks + the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a + file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not + available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global From 75cb9572678ceb7e142754e5fbd21db0f071b1eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 16:02:13 -0800 Subject: [PATCH 017/533] Scripts: Document.rasterize and Document.imageCapture with their option classes Document.rasterize(sourceArt, clipBounds?, options?) replaces one page item or a list of them with an embedded image in one undo step and gives the new RasterItem; the source objects go stale. Document.imageCapture( imageFile, clipBounds?, options?) writes a PNG of all the visible art, on the artboards or off them, or of the area clipBounds names. new RasterizeOptions() and new ImageCaptureOptions() start with the defaults the help pages give, and the enumerations AntiAliasingMethod and RasterizationColorModel hold their values. Every option goes to the command explicitly, so the document's raster effects settings do not change the result. object.rasterize takes ids, to rasterize those objects instead of the selection while keeping the selection less the replaced art, and clipBounds, which cuts the image to a rectangle that must reach the art itself. Its result adds imageId, the image inside the clip group when clippingMask makes one. VectorCraft's own rules: clipBounds is [left, top, right, bottom] in the script's coordinates and is never reordered; imageCapture writes a PNG and needs a .png name; transparency wins over backgroundBlack and over matte; padding takes 0 to 1,000 points and both resolutions 72 to 2400 ppi; an image over 64 megapixels or 32,768 pixels a side throws before anything is drawn. imageCapture writes only where the script's File objects may, and never over an open document's file or a file one of them links, wherever the linking image or placed document is stored. convertSpotColors, convertTextToOutlines and includeLayers set to true, and Document.windowCapture, throw an error that says they are not available yet. --- crates/engine/src/cmd/links.rs | 12 + crates/engine/src/cmd/menucmds.rs | 75 ++- crates/engine/src/script/dom.rs | 5 +- .../engine/src/script/dom/raster_capture.rs | 388 +++++++++++++ crates/engine/src/tests.rs | 1 + .../engine/src/tests/script_raster_capture.rs | 537 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 8 + docs/mcp.md | 34 ++ docs/target-app-parity.md | 1 + 9 files changed, 1053 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/raster_capture.rs create mode 100644 crates/engine/src/tests/script_raster_capture.rs diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 29da4d0524..febe0946de 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -194,6 +194,18 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } +/// The link of every linked image and placed document of `d`, wherever it is stored, brush art +/// included, with the plate files of an image placed from a DCS file. +pub(crate) fn linked_files_with_plates(d: &Document) -> Vec<(LinkInfo, Vec)> { + groups(d, None) + .into_iter() + .map(|g| { + let plates = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); + (g.link, plates) + }) + .collect() +} + /// The linked images and placed documents of `d` by file and content, wherever they are stored /// (only `ids` when given), in [`Document::visit_stored`] order. An object whose id an object /// visited before it has (art being edited on a layer and its definition) counts once, by its diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index aa330e11ea..f339f7b96f 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, none inside another, each unlocked in unlocked layers and groups; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -894,7 +894,21 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p .collect(); // What the art draws, its geometry effects applied. let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); - let b = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?.inflate(pad, pad); + let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; + let mut b = drawn.inflate(pad, pad); + if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { + let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; + if x1 <= x0 || y1 <= y0 { + return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); + } + let clip_rect = Rect::new(x0, y0, x1, y1); + // The rectangle must reach the art itself, not only the padding around it. + let on_art = drawn.intersect(clip_rect); + if on_art.width() <= 0.0 || on_art.height() <= 0.0 { + return Err(bad(cmd, "clipBounds does not overlap the art")); + } + b = b.intersect(clip_rect); + } let scale = ppi / 72.0; // Snap to whole pixels. let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); @@ -934,9 +948,51 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p Ok(Rasterized { blob, alpha, width: img.width, height: img.height, xf, clip, warning }) } +/// The objects `ids` names for Rasterize, in paint order: each an object of the active document, +/// listed once, none inside another listed one, and neither it nor a layer or group it is in +/// locked. +fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { + let ids = super::checked_ids_param(s, p, "ids", cmd)?; + let d = &s.doc()?.doc; + let mut listed = HashSet::with_capacity(ids.len()); + for id in &ids { + if !listed.insert(*id) { + return Err(bad(cmd, format!("id {} is listed twice", id.0))); + } + } + for id in &ids { + // The layers and groups from the top down to the object itself. + let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; + if d.node(*id).is_some_and(|n| n.is_layer()) { + return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); + } + let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); + if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); + } + if let Some(outer) = up.iter().find(|a| *a != id && listed.contains(*a)) { + return Err(bad(cmd, format!("id {} is inside id {}, which is listed too", id.0, outer.0))); + } + if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); + } + } + Ok(vectorcraft_doc::Selection { objects: ids, ..Default::default() }.in_paint_order(d)) +} + +/// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its +/// clip group. +fn image_in(node: &Node) -> NodeId { + match &node.kind { + NodeKind::Group { children, .. } => children.iter().find(|c| matches!(c.kind, NodeKind::Image(_))).map_or(node.id, |c| c.id), + _ => node.id, + } +} + fn rasterize(s: &mut Session, p: &Value) -> Result { const C: &str = "object.rasterize"; - let roots = selected_roots(s)?; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = if given { rasterize_sources(s, p, C)? } else { selected_roots(s)? }; let st = s.doc()?; let nodes: Vec = roots.iter().filter_map(|id| st.doc.node(*id).cloned()).collect(); let image = rasterize_art(&st.doc, nodes, p, C, true)?; @@ -944,16 +1000,21 @@ fn rasterize(s: &mut Session, p: &Value) -> Result { if roots.is_empty() { return Err(bad(C, "nothing selected")); } - let id = s.edit("Rasterize", |d, sel| { + let (id, image_id) = s.edit("Rasterize", |d, sel| { let threaded = super::threads::frames(d); let node = image.into_node(d); + let image_id = image_in(&node); let id = d.wrap(&roots, |_| node)?; // Rasterized frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); - sel.set([id]); - Ok(id) + if given { + sel.prune(d); + } else { + sel.set([id]); + } + Ok((id, image_id)) })?; - let mut out = json!({ "id": id.0, "width": w, "height": h }); + let mut out = json!({ "id": id.0, "imageId": image_id.0, "width": w, "height": h }); if let Some(w) = warning { out["warning"] = json!(w); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e6252bd774..478dbca2c5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod raster_capture; mod save_open; /// The error for a member read or called with no document open. @@ -1813,7 +1814,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(raster_capture::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1876,6 +1877,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); + document.extend(raster_capture::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1941,6 +1943,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); classes.extend(save_open::classes(l)); + classes.extend(raster_capture::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs new file mode 100644 index 0000000000..a75f1a1c4a --- /dev/null +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -0,0 +1,388 @@ +//! Rasterizing art and capturing it as an image in the script object model: `Document.rasterize`, +//! `Document.imageCapture` and their option classes, as the help pages +//! , +//! , +//! and +//! describe. +//! +//! `rasterize` runs `object.rasterize` with the source art's ids, and `imageCapture` runs +//! `document.export` of an area of the page, inside the run's transaction. Every option is given to +//! the command, at the help page's default when the script leaves it out, so the document's raster +//! effects settings do not change the result. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as +//! `geometricBounds` gives them; the right edge must be right of the left one and the bottom edge +//! below the top one, and the numbers are never swapped. +//! - `rasterize` takes one page item or a list of at most [`super::MAX_LISTED`] of them, all of +//! this document, none listed twice, inside another listed one or a path of a compound path, and +//! none locked or in a locked layer or group. It keeps the selection, less the art it replaces, +//! and gives the new `RasterItem`: with `clippingMask`, the image inside its clip group. +//! `transparency` wins over `backgroundBlack`. `convertSpotColors`, `convertTextToOutlines` and +//! `includeLayers` true throw an error that says they are not available yet. +//! - `imageCapture` writes a PNG, and the file's name must end with `.png`. Without `clipBounds` it +//! captures the bounds of all the visible art, on the artboards or off them. With +//! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with +//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 +//! to 255. The file is written only where the script's `File` objects may write, and never over +//! an open document's file or a file one of them links. +//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is +//! drawn; the resolution is never lowered to make it fit. +//! - `windowCapture` throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_geom::Rect; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, command, coordinate, current, frame, given, item_of, item_ref, later, method, + named, num, on_doc, text, this_doc, with_doc, +}; + +/// The lowest resolution the option classes take, in pixels per inch. +pub const MIN_RESOLUTION: f64 = 72.0; +/// The highest resolution the option classes take, in pixels per inch. +pub const MAX_RESOLUTION: f64 = 2400.0; +/// The most room `RasterizeOptions.padding` adds around the art, in points. +pub const MAX_PADDING: f64 = 1000.0; +/// The error of a source art object from another document. +pub const OTHER_DOCUMENT: &str = "The source art must be in this document"; + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = + &[("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), ("RasterizationColorModel", &["BITMAP", "DEFAULTCOLORMODEL", "GRAYSCALE"])]; + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`). +fn member<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + let members = ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m); + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A finite number from `lo` to `hi`. +fn number_in(d: &Data, what: &str, lo: f64, hi: f64) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => { + if (lo..=hi).contains(n) { + Ok(*n) + } else { + Err(HostError::Range(format!("{what} must be from {lo} to {hi}"))) + } + } + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// The fields of the options object `d` of `class`, or `None` when the script gave none. +fn options<'a>(d: &'a Data, class: &str) -> std::result::Result, HostError> { + match given(d) { + None | Some(Data::Null) => Ok(None), + Some(Data::Object(items)) if items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class)) => Ok(Some(items)), + Some(_) => Err(HostError::Type(format!("the options must be a {class} object"))), + } +} + +/// `clipBounds`, `[left, top, right, bottom]` in the run's script coordinates, as a rectangle in +/// document coordinates; `None` when the script gave none. +fn clip_bounds(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let a = match given(d) { + None | Some(Data::Null) => return Ok(None), + Some(Data::Array(a)) if a.len() == 4 => a, + Some(_) => return Err(HostError::Type("clipBounds must be an array of four numbers [left, top, right, bottom]".into())), + }; + let mut n = [0.0; 4]; + for (o, d) in n.iter_mut().zip(a) { + *o = coordinate(d, "clipBounds")?; + } + let f = with_doc(h, doc, |_, st| frame(st))?; + let c = h.dom.coords.get(); + let (p0, p1) = (f.to_document(c, [n[0], n[1]]), f.to_document(c, [n[2], n[3]])); + if p1.x <= p0.x || p1.y <= p0.y { + return Err(HostError::Range("clipBounds must have its right edge right of its left edge and its bottom edge below its top edge".into())); + } + Ok(Some(Rect::new(p0.x, p0.y, p1.x, p1.y))) +} + +/// Throws when an image of `region` at `ppi` would be more than 64 megapixels or longer than the +/// renderer draws on a side, before anything is drawn. +fn check_size(region: Rect, ppi: f64) -> std::result::Result<(), HostError> { + let scale = ppi / 72.0; + let (w, h) = ((region.width() * scale).round().max(1.0), (region.height() * scale).round().max(1.0)); + let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE); + if w * h > crate::cmd::menucmds::MAX_PIXELS || w > side || h > side { + return Err(HostError::Range(format!( + "the image would be {w} × {h} pixels; images are limited to 64 megapixels and {side} pixels a side: lower the resolution or the bounds" + ))); + } + Ok(()) +} + +// ---- Rasterize ---- + +/// `object.rasterize`'s params for the `RasterizeOptions` fields `items` (`None`: the defaults), +/// with every option given. +fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result, HostError> { + let (mut anti_alias, mut black, mut clear, mut clip, mut model, mut padding, mut ppi) = ("art", false, false, false, "document", 0.0, 300.0); + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("RasterizeOptions.{k}"); + match k.as_str() { + "antiAliasingMethod" => { + anti_alias = match member(v, "AntiAliasingMethod", &what)? { + "None" => "none", + "TYPEOPTIMIZED" => "type", + _ => "art", + } + } + "backgroundBlack" => black = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "clippingMask" => clip = boolean(v, &what)?, + "colorModel" => { + model = match member(v, "RasterizationColorModel", &what)? { + "BITMAP" => "bitmap", + "GRAYSCALE" => "grayscale", + _ => "document", + } + } + "padding" => padding = number_in(v, &what, 0.0, MAX_PADDING)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "convertSpotColors" | "convertTextToOutlines" | "includeLayers" if boolean(v, &what)? => { + return Err(HostError::Error(format!("{what} is not available yet"))); + } + _ => {} + } + } + let background = if clear { + "transparent" + } else if black { + "black" + } else { + "white" + }; + let mut p = Map::new(); + p.insert("ppi".into(), json!(ppi)); + p.insert("background".into(), json!(background)); + p.insert("antiAlias".into(), json!(anti_alias)); + p.insert("padding".into(), json!(padding)); + p.insert("colorModel".into(), json!(model)); + p.insert("clippingMask".into(), json!(clip)); + Ok(p) +} + +/// The ids of the source art `d` names for `rasterize` in the document `doc`: one page item, or a +/// list of them. The command checks that none is listed twice, inside another or locked. +fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match d { + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + Data::Undefined | Data::Null => return Err(HostError::Type("rasterize needs the source art, a page item or a list of them".into())), + d => vec![d], + }; + if list.is_empty() { + return Err(HostError::Error("rasterize needs at least one page item".into())); + } + h.charge_call(16 * list.len() as u64)?; + let mut ids = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error(OTHER_DOCUMENT.into())); + } + ids.push(item.id.0); + } + Ok(ids) +} + +/// `document.rasterize(sourceArt, clipBounds?, options?)`: `object.rasterize` of the source art, +/// which the image replaces in one undo step. → the new `RasterItem`. +fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = sources(h, doc, arg(a, 1))?; + let clip = clip_bounds(h, doc, arg(a, 2))?; + let mut p = rasterize_params(options(arg(a, 3), "RasterizeOptions")?)?; + p.insert("ids".into(), json!(ids)); + if let Some(r) = clip { + p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); + } + let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + let image = match &r { + Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("imageId", Data::Number(n)) => super::whole(*n), + _ => None, + }), + _ => None, + }; + let image = image.ok_or_else(|| HostError::Error("the image was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(item_ref(h, st, crate::NodeId(image))) +} + +// ---- Image capture ---- + +/// A channel of `matteColor`: a finite number from 0 to 255. +fn channel(items: &[(String, Data)], key: &str) -> std::result::Result { + let d = items.iter().find(|(k, _)| k == key).map_or(&Data::Undefined, |(_, v)| v); + let n = number_in(d, &format!("ImageCaptureOptions.matteColor.{key}"), 0.0, 255.0)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = n.round() as u8; + Ok(byte) +} + +/// The capture's resolution and `document.export`'s `background` and `antiAlias` for the +/// `ImageCaptureOptions` fields `items` (`None`: the defaults). +fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f64, String, &'static str), HostError> { + let (mut anti_alias, mut matte, mut clear, mut ppi) = (false, false, false, 150.0); + let mut color = [255u8; 3]; + for (k, v) in items.unwrap_or_default() { + if matches!(v, Data::Undefined) { + continue; + } + let what = format!("ImageCaptureOptions.{k}"); + match k.as_str() { + "antiAliasing" => anti_alias = boolean(v, &what)?, + "matte" => matte = boolean(v, &what)?, + "transparency" => clear = boolean(v, &what)?, + "resolution" => ppi = number_in(v, &what, MIN_RESOLUTION, MAX_RESOLUTION)?, + "matteColor" => { + let Data::Object(c) = v else { return Err(HostError::Type(format!("{what} must be an RGBColor"))) }; + color = [channel(c, "red")?, channel(c, "green")?, channel(c, "blue")?]; + } + _ => {} + } + } + let background = if clear { + "transparent".to_string() + } else if matte { + format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2]) + } else { + "white".to_string() + }; + Ok((ppi, background, if anti_alias { "art" } else { "none" })) +} + +/// The files a capture must not write over: the open documents' files and the files their linked +/// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns +/// and brushes included), with a DCS image's plate files, by their real paths. A link's stored path +/// and its relative path are each taken from its document's folder, as opening the document reads +/// them. +fn sources_on_disk(h: &Host) -> Vec { + let s = h.session.borrow(); + let mut paths: Vec = Vec::new(); + for st in s.documents() { + paths.extend(st.path.clone()); + let document = st.path.as_deref(); + for (link, plates) in crate::cmd::links::linked_files_with_plates(&st.doc) { + for stored in std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).chain(plates.iter().map(String::as_str)) { + if std::path::Path::new(stored).is_absolute() { + paths.push(stored.to_string()); + } + paths.extend(crate::cmd::fileio::document_path(stored, document).ok()); + } + } + } + paths.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect() +} + +/// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the +/// art inside `clipBounds`, or of all the visible art. +fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = vectorcraft_js::file_ref_path(arg(a, 1)).ok_or_else(|| HostError::Type("imageCapture needs a File".into()))?; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + if !name.ends_with(".png") || name.len() <= ".png".len() { + return Err(HostError::Error("imageCapture writes a PNG file: give it a name that ends with .png".into())); + } + let clip = clip_bounds(h, doc, arg(a, 2))?; + let (ppi, background, anti_alias) = capture_settings(options(arg(a, 3), "ImageCaptureOptions")?)?; + let region = match clip { + Some(r) => r, + None => with_doc(h, doc, |_, st| crate::cmd::fileio::export_art_bounds(&st.doc, "png")) + .ok_or_else(|| HostError::Error("the document has no visible art to capture".into()))?, + }; + check_size(region, ppi)?; + let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; + let canonical = std::fs::canonicalize(&real).ok(); + if canonical.is_some_and(|c| sources_on_disk(h).contains(&c)) { + return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); + } + let p = json!({ + "path": crate::cmd::findfiles::plain(real).to_string_lossy(), + "format": "png", + "rect": [region.x0, region.y0, region.width(), region.height()], + "ppi": ppi, + "background": background, + "antiAlias": anti_alias, + "includeArtboardFill": false, + }); + h.disk.borrow_mut().exact = true; + let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); + h.disk.borrow_mut().exact = false; + r?; + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + let mut members = named(vec![("rasterize", method(l, doc_rasterize)), ("imageCapture", method(l, doc_image_capture))]); + members.push(later(l, "Document", "windowCapture")); + members +} + +/// The fields a new options object starts with. +type Starts = fn() -> Vec<(&'static str, Data)>; + +fn rasterize_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasingMethod", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("clippingMask", Data::Bool(false)), + ("colorModel", text("RasterizationColorModel.DEFAULTCOLORMODEL")), + ("convertSpotColors", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("includeLayers", Data::Bool(false)), + ("padding", num(0.0)), + ("resolution", num(300.0)), + ("transparency", Data::Bool(false)), + ] +} + +fn capture_starts() -> Vec<(&'static str, Data)> { + let white = Data::Object(vec![ + ("typename".to_string(), text("RGBColor")), + ("red".to_string(), num(255.0)), + ("green".to_string(), num(255.0)), + ("blue".to_string(), num(255.0)), + ]); + vec![ + ("antiAliasing", Data::Bool(false)), + ("matte", Data::Bool(false)), + ("matteColor", white), + ("resolution", num(150.0)), + ("transparency", Data::Bool(false)), + ] +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives. +pub(super) fn classes(link: &Link) -> Vec { + let all: [(&'static str, Starts); 2] = [("RasterizeOptions", rasterize_starts), ("ImageCaptureOptions", capture_starts)]; + all.into_iter() + .map(|(name, starts)| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + let mut items = vec![("typename".to_string(), text(name))]; + items.extend(starts().into_iter().map(|(k, v)| (k.to_string(), v))); + Ok(Data::Object(items)) + }); + HostClass { name: name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }) + .collect() +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b2db53b71f..d808439701 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_raster_capture; mod script_run; mod script_save_open; mod scripts; diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs new file mode 100644 index 0000000000..3385c4dd5c --- /dev/null +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -0,0 +1,537 @@ +//! Rasterizing and capturing art from a script: `Document.rasterize`, `Document.imageCapture`, +//! `RasterizeOptions`, `ImageCaptureOptions` and `object.rasterize` with `ids` and `clipBounds`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// Fills the objects `ids` with `color` and takes their strokes off. +fn paint(s: &mut Session, ids: &[NodeId], color: &str) { + let ids: Vec = ids.iter().map(|i| i.0).collect(); + s.execute("paint.setFill", &json!({"ids": ids, "color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": ids, "none": true})).unwrap(); +} + +/// A 400 × 300 pt document with two rectangles without strokes: `a` at (10, 20) 30 × 40 pt, `b` at +/// (100, 100) 50 × 50 pt. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + paint(&mut s, &[a, b], "#ff0000"); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The size of each embedded image of the active document, in pixels. +fn images(s: &Session) -> Vec<(u32, u32)> { + let mut out = Vec::new(); + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(i) = &n.kind { + out.push((i.width, i.height)); + } + }); + out +} + +/// A script that selects `b` and rasterizes `a` (the first and second page items). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[0], b = d.pageItems[1]; b.name = 'b'; d.selection = [b];"; + +#[test] +fn script_rasterize_explicit_sources_preserves_selection() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); vc.log(d.selection.length); vc.log(d.selection[0].name === 'b');\ + try {{ a.name; }} catch (e) {{ vc.log(e.message); }} vc.log(d.pageItems.length);" + ), + ); + assert_eq!(out, [json!("RasterItem"), json!(1), json!(true), json!("Stale page item"), json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + assert_eq!(st.selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), undo + 1, "one undo step"); +} + +#[test] +fn script_rasterize_defaults_override_document_raster_settings() { + let (mut s, ..) = doc(); + s.execute("document.rasterEffectsSettings", &json!({"resolution": 72, "background": "transparent"})).unwrap(); + log(&mut s, &format!("{RASTERIZE_A} d.rasterize(a);")); + // 30 × 40 pt at 300 ppi, snapped out to whole pixels (at 72 ppi it would be about 30 × 40). + let [(w, h)] = images(&s)[..] else { panic!("one image: {:?}", images(&s)) }; + assert!((125..=126).contains(&w) && (167..=168).contains(&h), "300 ppi, the help page's default, not the document's 72: {w} × {h}"); + let (mut s, ..) = doc(); + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 144; o.padding = 5; d.rasterize(a, undefined, o);")); + assert_eq!(images(&s), vec![(80, 100)], "40 × 50 pt with the padding, at 144 ppi"); +} + +#[test] +fn script_rasterize_options_have_the_help_page_defaults() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var o = new RasterizeOptions(); vc.log([o.typename, o.antiAliasingMethod, o.backgroundBlack, o.clippingMask, o.colorModel, \ + o.convertSpotColors, o.convertTextToOutlines, o.includeLayers, o.padding, o.resolution, o.transparency]);\ + var c = new ImageCaptureOptions(); vc.log([c.typename, c.antiAliasing, c.matte, c.matteColor.red, c.matteColor.green, \ + c.matteColor.blue, c.resolution, c.transparency]); vc.log([AntiAliasingMethod.TYPEOPTIMIZED, RasterizationColorModel.BITMAP]);", + ); + let rasterize = json!([ + "RasterizeOptions", + "AntiAliasingMethod.ARTOPTIMIZED", + false, + false, + "RasterizationColorModel.DEFAULTCOLORMODEL", + false, + false, + false, + 0, + 300, + false + ]); + assert_eq!(out[0], rasterize); + assert_eq!(out[1], json!(["ImageCaptureOptions", false, false, 255, 255, 255, 150, false])); + assert_eq!(out[2], json!(["AntiAliasingMethod.TYPEOPTIMIZED", "RasterizationColorModel.BITMAP"])); +} + +#[test] +fn script_rasterize_clip_mask_returns_image_child() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.clippingMask = true; var r = d.rasterize([a], null, o); vc.log([r.typename, r.parent.typename]);" + ), + ); + assert_eq!(out, [json!(["RasterItem", "GroupItem"])]); +} + +#[test] +fn script_rasterize_clip_bounds_cut_the_image() { + let (mut s, ..) = doc(); + // The left half of `a`: x 10 to 25, and its whole height (y 280 to 240, Y up). + log(&mut s, &format!("{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; d.rasterize(a, [10, 280, 25, 240], o);")); + assert_eq!(images(&s), vec![(15, 40)]); +} + +#[test] +fn script_rasterize_disposes_several_sources_in_one_step() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + let out = log(&mut s, "var d = app.activeDocument; var r = d.rasterize([d.pageItems[1], d.pageItems[0]]); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(1)]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none() && st.doc.node(b).is_none()); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// Each bad call throws and leaves the document as it was, with no undo step. +fn refused(s: &mut Session, source: &str, message: &str) { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(s); + let e = failure(s, source); + assert!(e.contains(message), "{source}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc) || *before == *s.active().unwrap().doc, "{source} changed the document"); + assert_eq!(undo_steps(s), undo, "{source} added an undo step"); +} + +#[test] +fn script_rasterize_rejects_other_documents_art() { + let (mut s, ..) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + refused(&mut s, "app.documents[0].rasterize(app.documents[1].pageItems[0]);", "The source art must be in this document"); +} + +#[test] +fn script_rasterize_rejects_listed_twice() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[0]]);", "listed twice"); +} + +#[test] +fn script_rasterize_rejects_locked_art() { + let (mut s, ..) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); +} + +#[test] +fn script_rasterize_rejects_art_inside_listed_art() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + refused(&mut s, "var d = app.activeDocument; d.rasterize([d.pageItems[0], d.pageItems[1]]);", "which is listed too"); +} + +#[test] +fn script_rasterize_rejects_a_compound_path_member() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The page items are the compound path, then its two paths. + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[1]);", "part of a compound path"); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);"); + assert_eq!(out, [json!("RasterItem")], "the compound path itself is rasterized"); +} + +#[test] +fn script_rasterize_rejects_stale_and_missing_sources() { + let (mut s, ..) = doc(); + refused(&mut s, "var d = app.activeDocument, a = d.pageItems[0]; a.remove(); d.rasterize(a);", "Stale page item"); + refused(&mut s, "app.activeDocument.rasterize([]);", "at least one page item"); + refused(&mut s, "app.activeDocument.rasterize();", "needs the source art"); + refused(&mut s, "app.activeDocument.rasterize(5);", "not a page item"); + let many = "var d = app.activeDocument, l = []; for (var i = 0; i < 10001; i++) l.push(d.pageItems[0]); d.rasterize(l);"; + refused(&mut s, many, "at most 10000 objects"); +} + +#[test] +fn script_rasterize_rejects_bad_options() { + let (mut s, ..) = doc(); + let cases = [ + ("var o = new RasterizeOptions(); o.resolution = 71;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = 2401;", "from 72 to 2400"), + ("var o = new RasterizeOptions(); o.resolution = NaN;", "finite number"), + ("var o = new RasterizeOptions(); o.resolution = Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.padding = 1001;", "from 0 to 1000"), + ("var o = new RasterizeOptions(); o.padding = -Infinity;", "finite number"), + ("var o = new RasterizeOptions(); o.antiAliasingMethod = 'smooth';", "AntiAliasingMethod value"), + ("var o = new RasterizeOptions(); o.colorModel = AntiAliasingMethod.None;", "RasterizationColorModel value"), + ("var o = new RasterizeOptions(); o.clippingMask = 1;", "true or false"), + ("var o = new RasterizeOptions(); o.convertTextToOutlines = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.includeLayers = true;", "not available yet"), + ("var o = new RasterizeOptions(); o.convertSpotColors = true;", "not available yet"), + ("var o = new ImageCaptureOptions();", "RasterizeOptions object"), + ("var o = {resolution: 300};", "RasterizeOptions object"), + ]; + for (options, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; {options} d.rasterize(d.pageItems[0], undefined, o);"), message); + } +} + +#[test] +fn script_rasterize_rejects_bad_clip_bounds() { + let (mut s, ..) = doc(); + let cases = [ + ("[25, 280, 10, 240]", "right edge right of its left edge"), + ("[10, 240, 25, 280]", "bottom edge below its top edge"), + ("[10, 280, 25]", "four numbers"), + ("[10, 280, 25, NaN]", "finite number"), + ("[10, 280, 25, 1e300]", "outside the canvas"), + ("[300, 20, 350, 10]", "does not overlap the art"), + ("'all'", "four numbers"), + ]; + for (bounds, message) in cases { + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[0], {bounds});"), message); + } + // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. + refused( + &mut s, + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[0], [42, 280, 48, 240], o);", + "does not overlap the art", + ); +} + +#[test] +fn script_rasterize_rejects_an_image_past_the_size_limit() { + let (mut s, ..) = doc(); + let source = "var d = app.activeDocument, b = d.pageItems[1]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let e = failure(&mut s, source); + assert!(e.contains("too large"), "{e}"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); +} + +#[test] +fn object_rasterize_with_ids_keeps_the_selection_and_names_the_image() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let r = s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72, "clippingMask": true})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.selection.objects, vec![b]); + let (id, image) = (NodeId(r["id"].as_u64().unwrap()), NodeId(r["imageId"].as_u64().unwrap())); + assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. })); + assert!(matches!(st.doc.node(image).unwrap().kind, NodeKind::Image(_))); + assert_eq!(st.doc.parent_of(image), Some(id)); + let r = s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(r["id"], r["imageId"], "without a clip group the image is the new object"); + assert_eq!(s.active().unwrap().selection.objects, vec![NodeId(r["id"].as_u64().unwrap())], "the selection is rasterized as before"); +} + +// ---- imageCapture ---- + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-capture-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// [`doc`] in a session whose scripts keep their data folders in `base`, and the data folder, where +/// scripts may write. +fn capture_doc(base: &Path) -> (Session, PathBuf) { + let (mut s, ..) = doc(); + s.attach_script_data(base.join("settings/Script Data")); + let dir = PathBuf::from(script(&mut s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()); + (s, dir) +} + +/// Runs `main/main.jsx` in `base` with the text `text`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + // Reading `Folder.userData` makes the data folder, where the script may write. + std::fs::write(&main, format!("Folder.userData; {text}").as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn script(s: &mut Session, base: &Path, text: &str) -> Vec { + run_file(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].as_array().cloned().unwrap_or_default() +} + +fn file_failure(s: &mut Session, base: &Path, text: &str) -> String { + run_file(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +/// The PNG at `path`, decoded by the `image` crate, as RGBA. +fn png(path: &Path) -> image::RgbaImage { + let bytes = std::fs::read(path).unwrap(); + assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG signature"); + image::load_from_memory_with_format(&bytes, image::ImageFormat::Png).unwrap().to_rgba8() +} + +#[test] +fn image_capture_whole_artwork_including_pasteboard() { + let base = folder("whole"); + let (mut s, dir) = capture_doc(&base); + // A third rectangle off the artboard, left of it: the art spans x -90 to 150 and y 20 to 150. + let c = rect(&mut s, -90.0, 30.0, 20.0, 20.0); + paint(&mut s, &[c], "#0000ff"); + // The capture's own 150 ppi applies, not the document's raster effects resolution. + s.execute("document.rasterEffectsSettings", &json!({"resolution": 300})).unwrap(); + let undo = undo_steps(&s); + let out = script( + &mut s, + &base, + &format!("var r = app.activeDocument.imageCapture(new File({})); vc.log(r === undefined);", quoted(&dir.join("all.png"))), + ); + assert_eq!(out, [json!(true)]); + let img = png(&dir.join("all.png")); + assert_eq!((img.width(), img.height()), (500, 271), "240 × 130 pt at 150 ppi"); + assert_eq!(img.get_pixel(5, 30).0, [0, 0, 255, 255], "the art off the artboard is there"); + assert_eq!(img.get_pixel(499, 0).0, [255, 255, 255, 255], "white where there is no art"); + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_capture_exact_clip_bounds_and_matte() { + let base = folder("clip"); + let (mut s, dir) = capture_doc(&base); + // x 0 to 50 and y 300 to 250 (Y up): the top-left corner of the artboard, with `a` in it. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.matte = true; o.matteColor = {{red: 0, green: 128, blue: 0}}; d.imageCapture(new File({}), [0, 300, 50, 250], o);\ + o.transparency = true; d.imageCapture(new File({}), [0, 300, 50, 250], o);", + f("white.png"), + f("matte.png"), + f("clear.png") + ); + script(&mut s, &base, &source); + for (name, blank) in [("white.png", [255, 255, 255, 255]), ("matte.png", [0, 128, 0, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.get_pixel(2, 2).0, blank, "{name}: the area without art"); + assert_eq!(img.get_pixel(20, 30).0, [255, 0, 0, 255], "{name}: the art"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_64mp_and_side_limit_before_render() { + let base = folder("huge"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("huge.png"); + // 4000 × 4000 pt at 2400 ppi is far past 64 megapixels; 40,000 × 1 pt at 72 ppi is past 32,768 a side. + let cases = [ + format!( + "var o = new ImageCaptureOptions(); o.resolution = 2400; app.activeDocument.imageCapture(new File({}), [0, 4000, 4000, 0], o);", + quoted(&target) + ), + format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 1, 40000, 0], o);", + quoted(&target) + ), + ]; + for case in &cases { + let e = file_failure(&mut s, &base, case); + assert!(e.contains("64 megapixels"), "{case}: {e}"); + } + assert!(!target.exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_rejects_bad_options_and_names() { + let base = folder("bad"); + let (mut s, dir) = capture_doc(&base); + let png = quoted(&dir.join("x.png")); + let cases = [ + ( + format!("var o = new ImageCaptureOptions(); o.resolution = 50; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "from 72 to 2400", + ), + ( + format!("var o = new ImageCaptureOptions(); o.resolution = Infinity; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "finite number", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: NaN, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "finite number", + ), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 300, Infinity, 250]);"), "finite number"), + ( + format!("var o = new ImageCaptureOptions(); o.matte = 'yes'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "true or false", + ), + ( + format!( + "var o = new ImageCaptureOptions(); o.matteColor = {{red: 300, green: 0, blue: 0}}; app.activeDocument.imageCapture(new File({png}), undefined, o);" + ), + "from 0 to 255", + ), + ( + format!("var o = new ImageCaptureOptions(); o.matteColor = 'red'; app.activeDocument.imageCapture(new File({png}), undefined, o);"), + "RGBColor", + ), + (format!("app.activeDocument.imageCapture(new File({png}), undefined, new RasterizeOptions());"), "ImageCaptureOptions object"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("x.tif"))), "ends with .png"), + (format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join(".png"))), "ends with .png"), + ("app.activeDocument.imageCapture('x.png');".to_string(), "needs a File"), + (format!("app.activeDocument.imageCapture(new File({png}), [0, 0, 0, 0]);"), "right edge right of its left edge"), + (format!("app.activeDocument.windowCapture(new File({}), [100, 100]);", quoted(&dir.join("w.tif"))), "not available yet"), + ]; + for (case, message) in &cases { + let e = file_failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(message), "{case}: {e}"); + } + assert_eq!(std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some())).count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_denied_or_source_path_writes_nothing() { + let base = folder("denied"); + let (mut s, dir) = capture_doc(&base); + let outside = base.join("outside/x.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&outside))); + assert!(e.contains(DENIED), "{e}"); + assert!(!outside.exists()); + // An open document whose file is named .png in the folder the script may write: its source. + let source = dir.join("source.png"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&source))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + // An image linked by a path relative to the document's folder, not to the working directory. + let linked = dir.join("linked.png"); + std::fs::write(&linked, b"kept").unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "linked.png".into(), relative: Some("linked.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&linked))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&linked).unwrap(), b"kept"); + // An image linked only from a symbol's art, outside the layers. + let in_symbol = dir.join("in-symbol.png"); + std::fs::write(&in_symbol, b"kept").unwrap(); + s.edit("Symbol", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: in_symbol.to_string_lossy().into_owned(), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "symbol-pic".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + let art = vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))); + d.symbols.push(vectorcraft_doc::Symbol { name: "Mark".into(), art: std::sync::Arc::new(art), dynamic: false }); + Ok(()) + }) + .unwrap(); + let e = file_failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&in_symbol)), + ); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&in_symbol).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn capture_written_before_a_failure_is_reported() { + let base = folder("report"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("kept.png"); + let r = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({})); throw new Error('later');", quoted(&target))); + let e = r.unwrap_err().to_string(); + assert!(e.contains("later") && e.contains("kept.png"), "the failure names the file it wrote: {e}"); + assert!(target.is_file()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a0794be35c..b95a1076e5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -145,6 +145,14 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + ("", "AntiAliasingMethod ImageCaptureOptions RasterizationColorModel RasterizeOptions"), + ("Document.prototype.", "rasterize windowCapture windowCapture="), + ("ImageCaptureOptions.", "prototype"), + ("ImageCaptureOptions.prototype.", "constructor"), + ("RasterizeOptions.", "prototype"), + ("RasterizeOptions.prototype.", "constructor"), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types diff --git a/docs/mcp.md b/docs/mcp.md index b379fb7973..24cda05fea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2729,6 +2729,34 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. +- `Document.rasterize(sourceArt, clipBounds?, options?)` runs `object.rasterize` with the source art's `ids` and gives + the new `RasterItem`; the source art is replaced in one undo step and its objects throw `Stale page item` after. + `Document.imageCapture(imageFile, clipBounds?, options?)` runs `document.export` of a PNG of the art inside + `clipBounds`, or of all the visible art when it is left out, and gives `undefined` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `new RasterizeOptions()` starts with + `antiAliasingMethod` `ARTOPTIMIZED`, `backgroundBlack`, `clippingMask`, `convertSpotColors`, + `convertTextToOutlines`, `includeLayers` and `transparency` false, `colorModel` `DEFAULTCOLORMODEL`, `padding` 0 + and `resolution` 300 (https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/); `new + ImageCaptureOptions()` starts with `antiAliasing`, `matte` and `transparency` false, `matteColor` white and + `resolution` 150 (https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/). Both resolutions take 72 to + 2400 pixels per inch. Every option goes to the command at that value when the script leaves it out, so the + document's raster effects settings do not change the result. The enumerations `AntiAliasingMethod` and + `RasterizationColorModel` (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/) hold strings such + as `"AntiAliasingMethod.TYPEOPTIMIZED"`. + VectorCraft's own rules: `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as + `geometricBounds` gives them, and bounds whose right edge is not right of the left one, or whose bottom edge is not + below the top one, throw an error. `rasterize` takes one page item or a list of at most 10,000; an object of another + document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in + a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With + `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and + `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says + they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With + `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white + without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` + opened for writing is checked, and a path that is an open document's file or a file one of them links throws an + error. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or + written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it + is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -9707,6 +9735,12 @@ without it, and their results carry the `warning` that Flatten Transparency give of threaded text that it rasterizes out of its thread with the text it shows, as `type.createOutlines` does (see Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. +With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, +without the objects it replaced. An id listed twice, an object inside another listed one, a layer, a path of a +compound path or a part of another object that is not a group, and an object that is locked or in a locked layer or +group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's +`imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. ```json {"name":"run_command","arguments":{"command":"document.rasterEffectsSettings","params":{"resolution":"high","background":"white","addAround":36}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..0d3e80376b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,6 +1027,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 41c375fa579de106534d35fa764dd386442c3bb5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:30:55 -0800 Subject: [PATCH 018/533] Scripts: imageCapture refuses a missing linked file's path Document.imageCapture compared only paths that exist, so a capture to the path of a linked image whose file is missing created the file the document then loads from that link. Each path is now compared as its folder's real path and its name, so a missing file counts too. A name that differs only in letter case is the same file in a folder whose names ignore case: the folder's own entries are looked up with their ASCII letter case swapped, and on macOS the nearest folder above on the same volume. When neither tells, the capture is refused. --- .../engine/src/script/dom/raster_capture.rs | 104 ++++++++++++++++-- .../engine/src/tests/script_raster_capture.rs | 67 +++++++++++ docs/mcp.md | 11 +- 3 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index a75f1a1c4a..811d0c48c4 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -269,10 +269,10 @@ fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f6 /// The files a capture must not write over: the open documents' files and the files their linked /// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns -/// and brushes included), with a DCS image's plate files, by their real paths. A link's stored path -/// and its relative path are each taken from its document's folder, as opening the document reads -/// them. -fn sources_on_disk(h: &Host) -> Vec { +/// and brushes included), with a DCS image's plate files, also when a file is missing, in the form +/// [`placed`] gives. A link's stored path and its relative path are each taken from its +/// document's folder, as opening the document reads them. +fn sources_on_disk(h: &Host) -> Vec { let s = h.session.borrow(); let mut paths: Vec = Vec::new(); for st in s.documents() { @@ -287,7 +287,97 @@ fn sources_on_disk(h: &Host) -> Vec { } } } - paths.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect() + paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() +} + +/// A file as its folder's real path and its name. +type Placed = (std::path::PathBuf, std::ffi::OsString); + +/// `p` as its folder's real path and its file name: from its real path with links followed, or, +/// for a file that is not there, from its folder's real path. `None` when neither the file nor its +/// folder is there. +fn placed(p: &std::path::Path) -> Option { + let real = std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?)))?; + Some((real.parent()?.to_path_buf(), real.file_name()?.to_os_string())) +} + +/// Whether two [`placed`] files are one file: the same folder, and the same name, or names that +/// differ only in letter case in a folder whose volume ignores case. +fn same_file(a: &Placed, b: &Placed) -> bool { + same_folder(&a.0, &b.0) && (a.1 == b.1 || (a.1.to_string_lossy().to_lowercase() == b.1.to_string_lossy().to_lowercase() && ignores_case(&a.0))) +} + +/// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and +/// file number, so a path spelled in another letter case on a volume that ignores case still +/// matches. On Windows a real path carries the letter case stored on disk. +fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { + if a == b { + return true; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { + return x.dev() == y.dev() && x.ino() == y.ino(); + } + } + false +} + +/// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a +/// symbolic link or another file. +fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { + if !std::fs::symlink_metadata(other).is_ok_and(|m| !m.file_type().is_symlink()) { + return false; + } + match (std::fs::canonicalize(entry), std::fs::canonicalize(other)) { + (Ok(a), Ok(b)) => same_folder(&a, &b), + _ => false, + } +} + +/// `name` with the letter case of every ASCII letter swapped, and other characters as they are. +fn swapped_case(name: &str) -> String { + name.chars().map(|c| if c.is_ascii_lowercase() { c.to_ascii_uppercase() } else { c.to_ascii_lowercase() }).collect() +} + +/// Whether file names in the real folder `folder` ignore letter case. Names keep case when two of +/// the folder's first 256 entries differ only in the case of ASCII letters. Otherwise the first of +/// them whose name has an ASCII letter and that is not a symbolic link is looked up with the case +/// of those letters swapped: names ignore case when that finds the same entry. With no such entry +/// on macOS, where a whole volume either ignores or keeps case, the nearest folder at or above +/// `folder` whose name has an ASCII letter, with its parent on the same volume, is looked up the +/// same way in its parent. When neither tells, names are taken to ignore case. +fn ignores_case(folder: &std::path::Path) -> bool { + let entries: Vec = std::fs::read_dir(folder).into_iter().flatten().flatten().take(256).collect(); + let mut folded = std::collections::HashSet::new(); + let names: std::collections::HashSet = entries.iter().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + if !names.iter().all(|n| folded.insert(n.to_ascii_lowercase())) { + return false; + } + for entry in &entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let swapped = swapped_case(&name); + if swapped != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(swapped)); + } + } + #[cfg(target_os = "macos")] + for dir in folder.ancestors() { + use std::os::unix::fs::MetadataExt; + let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else { break }; + let device = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.dev()).ok(); + let here = device(folder); + if here.is_none() || device(dir) != here || device(parent) != here { + break; + } + let name = name.to_string_lossy(); + let swapped = swapped_case(&name); + if swapped != name { + return finds_same(dir, &parent.join(swapped)); + } + } + true } /// `document.imageCapture(imageFile, clipBounds?, options?)`: `document.export` of a PNG of the @@ -308,8 +398,8 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { }; check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; - let canonical = std::fs::canonicalize(&real).ok(); - if canonical.is_some_and(|c| sources_on_disk(h).contains(&c)) { + let target = placed(&real); + if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s))) { return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); } let p = json!({ diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 3385c4dd5c..e48c7a2d46 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -524,6 +524,73 @@ fn capture_denied_or_source_path_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn capture_to_a_missing_links_path_writes_nothing() { + let base = folder("missing-link"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // An image linked by a path next to the document whose file is not there. + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "gone.png".into(), relative: Some("gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let gone = dir.join("gone.png"); + assert!(!gone.exists()); + let e = + file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&gone))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!gone.exists(), "nothing written"); + // The same name in other letter case is the linked file only where the volume ignores case. + std::fs::write(dir.join("probe.txt"), b"x").unwrap(); + let volume_ignores_case = dir.join("PROBE.TXT").exists(); + let upper = dir.join("GONE.png"); + let text = format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&upper)); + if volume_ignores_case { + assert!(file_failure(&mut s, &base, &text).contains("cannot write over an open document")); + assert!(!gone.exists(), "nothing written"); + } else { + script(&mut s, &base, &text); + assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); + // Two names for one file that differ only in case show that the folder keeps case. + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("probe.txt"), b"x").unwrap(); + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); + let im = vectorcraft_doc::ImageObject { + key: "sub-gone".into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); + let sub_upper = sub.join("GONE.png"); + script(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&sub_upper))); + assert!(sub_upper.exists() && !sub.join("gone.png").exists()); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_written_before_a_failure_is_reported() { let base = folder("report"); diff --git a/docs/mcp.md b/docs/mcp.md index 24cda05fea..b58ff4129b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,14 +2749,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and - `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says - they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With + `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an + error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or - written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it - is not available yet. + error, also when that file is missing. A name that differs from it only in letter case throws the same error in a + folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or + 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to + make it fit. `Document.windowCapture` throws an error that says it is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global From 022d0ce7e886bc698e43b2a5389e6277f48b8cd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:14:32 -0800 Subject: [PATCH 019/533] Scripts: PlacedItem.trace and RasterItem.trace make an Image Trace object with its tracing options `PlacedItem.trace()` and `RasterItem.trace()` run `imageTrace.make` with the Default preset and return the Image Trace object as a `PluginItem`. Its `tracing` is a `TracingObject` with the source image, the path, anchor and color counts, the image's resolution, `expandTracing()`, `releaseTracing()` and a `TracingOptions` object. Assigning an option or loading a preset traces the image again, keeping its source image and view; a value the tracing already has runs no command. Option values are checked for type and range before any trace, and nothing changes when one is refused. Options with no VectorCraft setting and `expandTracing(true)` throw. `storeToPreset` returns `false` for a built-in preset name or `Custom` and throws for any other name. A tracing that was expanded, released, deleted or traced again by a command is stale. The source image is reached through `sourceArt` and is not listed in `pageItems`, `placedItems` or `rasterItems`, and the name of a tracing cannot be changed from a script. With a script running, `imageTrace.make` stops at the run's stop request. Setting `File.hidden` stores the new path with `set_path`, since the path is held in the object's class on this branch. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 24 +- crates/engine/src/script/dom.rs | 33 +- crates/engine/src/script/dom/images.rs | 4 +- crates/engine/src/script/dom/tracing.rs | 741 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 4 +- crates/engine/src/tests/script_dom_tracing.rs | 541 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 33 +- crates/js/src/file_classes.rs | 2 +- docs/mcp.md | 33 +- docs/target-app-parity.md | 3 +- 13 files changed, 1404 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/script/dom/tracing.rs create mode 100644 crates/engine/src/tests/script_dom_tracing.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..170c0b4b2b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -921,6 +921,10 @@ pub use buildcmds::{TraceRun, Traced, image_trace_target}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; +/// Whether an object is an Image Trace object, the source image of one, or the seam fills group in +/// one. +pub(crate) use buildcmds::{is_seam_fills, is_trace_group, is_trace_source}; + /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 692545d828..4ad46157aa 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -41,10 +41,10 @@ pub use live_paint::live_paint_gaps; pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_copy_region, sb_merge, sb_regions}; -pub(crate) use trace::TracePresetChanges; pub use trace::{ TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target, }; +pub(crate) use trace::{TracePresetChanges, is_seam_fills, is_trace_group, is_trace_source}; use trace::{ trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, }; diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index c3e7a84296..14a6ac10e2 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -17,12 +17,17 @@ thread_local! { // ---------- Image Trace ---------- -fn is_trace_group(n: &Node) -> bool { +pub(crate) fn is_trace_group(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some(TRACE_NAME) && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } +/// Whether object `id` of `d` is the source image an Image Trace object keeps as its first child. +pub(crate) fn is_trace_source(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|g| d.node(g)).is_some_and(|g| is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) +} + /// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; @@ -32,7 +37,7 @@ const SEAM_FILLS_NAME: &str = "Seam Fills"; /// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made /// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one /// of stroked paths without fills. (Auto Grouping groups hold filled paths.) -fn is_seam_fills(n: &Node) -> bool { +pub(crate) fn is_seam_fills(n: &Node) -> bool { let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; @@ -774,8 +779,12 @@ pub fn image_trace_target(s: &Session, p: &Value) -> Result { fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { let roots = root_ids(s, p)?; let d = &s.doc()?.doc; + // The source image an Image Trace object keeps is traced through that object, so it is never + // the object traced, and naming only such images is an error. + let source = |r: &NodeId| is_trace_source(d, *r); roots .iter() + .filter(|r| !source(r)) .find_map(|r| { let n = d.node(*r)?; match &n.kind { @@ -787,7 +796,10 @@ fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box None, } }) - .ok_or_else(|| bad(c, "select an image (or an Image Trace group)")) + .ok_or_else(|| match roots.iter().find(|r| source(r)) { + Some(r) => bad(c, format!("object {} is the source image of an Image Trace object: trace that object", r.0)), + None => bad(c, "select an image (or an Image Trace group)"), + }) } /// What command `c` with params `p` traces, and how, from the session: everything but the trace. @@ -1076,10 +1088,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result traced, - _ => trace_now(&inputs, &trace, &|_, _| true)?, + _ => trace_now(&inputs, &trace, &|_, _| stop.as_ref().is_none_or(|i| !i.is_set()))?, }; let TraceInputs { target, image: img, .. } = inputs; let mut warnings = keep_warnings(&trace, &res); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 18a394c125..87f348a24c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -40,11 +40,14 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod images; mod save_open; +mod tracing; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a new name given to a `PluginItem`. +const TRACING_NAME: &str = "The name of a tracing cannot be changed"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -74,6 +77,7 @@ const ITEM_CLASSES: &[&str] = &[ "RepeatItem", "PlacedDocumentItem", "IntertwineItem", + "PluginItem", ]; /// `app.coordinateSystem`. @@ -100,6 +104,8 @@ pub(super) struct State { presets: RefCell>>, /// What the placed and raster items keep ([`images::State`]). images: images::State, + /// What the tracings keep ([`tracing::State`]). + tracing: tracing::State, } impl State { @@ -303,6 +309,7 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result { }; let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id }; let s = h.session.borrow(); let st = &s.documents()[doc.index]; if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { @@ -316,6 +323,7 @@ fn typename(n: &crate::doc::Node) -> Option<&'static str> { Some(match &n.kind { NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } if crate::cmd::is_trace_group(n) => "PluginItem", NodeKind::Group { .. } => "GroupItem", NodeKind::Path { .. } => "PathItem", NodeKind::Compound { .. } => "CompoundPathItem", @@ -361,7 +369,10 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { NodeKind::RulerGuide { .. } => {} NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { out.push(n.id); - walk(children, out); + // The source image an Image Trace object keeps hidden as its first child is + // reached through that object's `tracing`. + let source = usize::from(crate::cmd::is_trace_group(n)); + walk(children.get(source..).unwrap_or_default(), out); } _ => out.push(n.id), } @@ -391,9 +402,11 @@ fn top_items(d: &Document) -> Vec { out } -/// Whether `n` and every object inside it are shown and unlocked. +/// Whether `n` and every object inside it are shown and unlocked. The source image an Image Trace +/// object keeps hidden as its first child is part of that object and is not counted. fn all_editable(n: &crate::doc::Node) -> bool { - n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) + let source = usize::from(crate::cmd::is_trace_group(n)); + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().skip(source).all(|c| all_editable(c))) } /// Whether the object and every layer and group it is in are shown and unlocked. @@ -1336,6 +1349,13 @@ fn item_set_name(h: &Host, a: &[Data]) -> Answer { if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } + // An Image Trace object is known by its name, so renaming one would end the tracing. + let item = this_item(h, a)?; + let tracing = + with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| crate::cmd::is_trace_group(n) && n.name.as_deref() != Some(&**name))); + if tracing { + return Err(HostError::Error(TRACING_NAME.into())); + } set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) } @@ -1818,7 +1838,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1945,8 +1965,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().filter(|c| !images::CLASSES.contains(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); + let own = |c: &&&str| images::CLASSES.contains(c) || tracing::CLASSES.contains(c); + classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| class(c, Some("PageItem"), Vec::new(), None))); classes.extend(images::classes(l)); + tracing::add_trace(&mut classes, l); + classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index dc5417c318..00303f2975 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -649,7 +649,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("matrix", property(l, placed_matrix, placed_set_matrix)), ("boundingBox", get(l, placed_box)), ]); - placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + placed.push(later(l, "PlacedItem", "contentVariable")); let mut raster = named(vec![ ("bitsPerChannel", get(l, raster_bits)), ("channels", get(l, raster_channels)), @@ -662,7 +662,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("transparent", get(l, raster_transparent)), ("boundingBox", get(l, raster_box)), ]); - raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + raster.extend(["colorants", "colorize", "contentVariable", "overprint"].into_iter().map(|m| later(l, "RasterItem", m))); vec![ class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs new file mode 100644 index 0000000000..f8642f3b7d --- /dev/null +++ b/crates/engine/src/script/dom/tracing.rs @@ -0,0 +1,741 @@ +//! Tracing in the script object model: `PlacedItem.trace()` and `RasterItem.trace()`, the +//! `PluginItem` an Image Trace object is, its `TracingObject` and its `TracingOptions`, as the help +//! pages , +//! and +//! describe them. +//! +//! An Image Trace object is a group that holds its source image, hidden, as its first object. +//! Tracing runs `imageTrace.make`, expanding `imageTrace.expand`, releasing `imageTrace.release` +//! and a change of view `imageTrace.setView`, so each joins the run's transaction and its work +//! counts against the run's limits. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `trace()` returns once the trace is made, so the counts can be read at once. It traces with +//! the Default preset. +//! - The traced image stays the same object: `sourceArt` gives it, and `releaseTracing()` gives it +//! back. `trace()` on an image that is the source of a tracing throws [`ALREADY_TRACED`], and on +//! a linked image whose file is missing throws `Linked image is missing`. +//! - `pathCount` counts the traced paths, without the seam fills an Abutting trace adds, +//! `anchorCount` their anchor points and `usedColorCount` the different paints they are filled +//! and stroked with, as the tracing is when they are read. `areaCount` throws. `imageResolution` +//! is the source image's pixels per inch as it is placed; an image placed at a different +//! resolution across and down has none. +//! - Assigning an option, or `loadFromPreset(name)`, traces again unless the options are already +//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its +//! `TracingOptions` follow it. A tracing that another command traced again, expanded or +//! released, or whose source image was deleted, is stale. +//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or +//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not +//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft +//! setting throw [`not_implemented`]. +//! - `viewRaster` and `viewVector` take only the pairs of the Image Trace views +//! ([`VIEWS`]); the Split view has neither. +//! - `storeToPreset(name)` gives `false` for a built-in preset and `Custom`; a script cannot change +//! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`] +//! bytes and none of `/`, `\`, `:` or control characters. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{ + Answer, Host, Item, Link, STALE_ITEM, arg, boolean, class, command, command_value, edit_item, find_doc, float, get, id_of, item_of, item_ref, + method, named, num, number, on_doc, property, text, typename_of, whole, with_doc, +}; +use crate::doc::{Node, TraceView}; +use crate::{NodeId, NodeKind}; + +/// The error of `trace()` on an image that is the source of a tracing. +pub const ALREADY_TRACED: &str = "The image is the source art of a tracing"; +/// The error of options that trace with neither fills nor strokes. +pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes"; +/// The error of `expandTracing(true)`. +pub const VIEWED_EXPAND: &str = "TracingObject.expandTracing(true) is not implemented"; +/// The longest preset name `loadFromPreset` and `storeToPreset` take, in bytes. +pub const MAX_PRESET_NAME: usize = 256; +/// The most times one run traces a tracing again through its options. +pub const MAX_RETRACES: usize = 10_000; +/// The largest `minArea`: the most pixels the tracer traces ([`vectorcraft_trace::MAX_PIXELS`]). +pub const MAX_MIN_AREA: u64 = vectorcraft_trace::MAX_PIXELS; + +/// The enumerations the members here give values of, as the help page +/// lists them. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("TracingModeType", &["TRACINGMODEBLACKANDWHITE", "TRACINGMODECOLOR", "TRACINGMODEGRAY"]), + ( + "ViewRasterType", + &["TRACINGVIEWRASTERADJUSTEDIMAGE", "TRACINGVIEWRASTERNOIMAGE", "TRACINGVIEWRASTERORIGINALIMAGE", "TRACINGVIEWRASTERTRANSPARENTIMAGE"], + ), + ( + "ViewVectorType", + &["TRACINGVIEWVECTORNOTRACINGRESULT", "TRACINGVIEWVECTOROUTLINES", "TRACINGVIEWVECTOROUTLINESWITHTRACING", "TRACINGVIEWVECTORTRACINGRESULT"], + ), +]; + +/// The classes this module defines. +pub(super) const CLASSES: &[&str] = &["PluginItem"]; + +/// Each Image Trace view with the `viewRaster` and `viewVector` that give it. +const VIEWS: &[(TraceView, &str, &str)] = &[ + (TraceView::Result, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"), + (TraceView::ResultWithOutlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINESWITHTRACING"), + (TraceView::Outlines, "ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::OutlinesWithSource, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"), + (TraceView::Source, "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTORNOTRACINGRESULT"), +]; + +/// Each `tracingMode` with its Image Trace mode. +const MODES: &[(&str, &str)] = &[ + ("TracingModeType.TRACINGMODEBLACKANDWHITE", "blackAndWhite"), + ("TracingModeType.TRACINGMODEGRAY", "grayscale"), + ("TracingModeType.TRACINGMODECOLOR", "color"), +]; + +/// Each `palette` name with its Image Trace palette. +const PALETTES: &[(&str, &str)] = &[("", "automatic"), ("Limited", "limited"), ("Full Tone", "fullTone"), ("Document Library", "documentLibrary")]; + +/// The options with no VectorCraft setting. +const NOT_IMPLEMENTED: &[&str] = &[ + "cornerAngle", + "livePaintOutput", + "maxStrokeWeight", + "minStrokeLength", + "outputToSwatches", + "pathFitting", + "preprocessBlur", + "resample", + "resampleResolution", +]; + +/// What a run keeps for tracings: for each document uid and Image Trace object a script traced +/// again through its options, the id of the object that replaced it. +#[derive(Default)] +pub(super) struct State { + next: RefCell>, +} + +/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put +/// it back put back the same object), else the Image Trace object that replaced it when this run +/// traced it again, else `id`. +pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { + let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some()); + if held { + return id; + } + h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n)) +} + +/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to +/// `new` now. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + let mut next = h.dom.tracing.next.borrow_mut(); + for ((u, _), to) in next.iter_mut() { + if *u == uid && *to == old.0 { + *to = new.0; + } + } + next.insert((uid, old.0), new.0); +} + +/// The error of a member with no VectorCraft setting. +pub fn not_implemented(class: &str, name: &str) -> String { + format!("{class}.{name} is not implemented") +} + +fn out_of_range(name: &str, range: &str) -> HostError { + HostError::Range(format!("TracingOptions.{name} is out of range: {range}")) +} + +fn invalid(name: &str) -> HostError { + HostError::Error(format!("TracingOptions.{name} has an invalid value")) +} + +fn stale() -> HostError { + HostError::Error(STALE_ITEM.into()) +} + +fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> { + match d { + Data::Object(o) => o.iter().find(|(n, _)| n == k).map(|(_, v)| v), + _ => None, + } +} + +/// The first id of a command's result `key`: a number or a list of them, read exactly. +fn result_id(v: &Value, key: &str) -> Option { + match &v[key] { + Value::Array(a) => a.first().and_then(Value::as_u64).map(NodeId), + n => n.as_u64().map(NodeId), + } +} + +/// The Image Trace object, its document and the id its handle holds, of the `cls` (`TracingObject` +/// or `TracingOptions`) `d` names. It must still be an Image Trace object of its document. +fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 4]), HostError> { + let Some((c, handle)) = host_ref_parts(d).filter(|(c, _)| *c == cls) else { + return Err(HostError::Type(format!("this is not a {cls}"))); + }; + let &[run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) }; + let doc = find_doc(h, run, uid).ok_or_else(stale)?; + let id = follow(h, doc.uid, id_of(high, low).ok_or_else(stale)?); + let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group)); + if !live { + return Err(stale()); + } + Ok((Item { doc, id }, [run, uid, high, low])) +} + +/// The `PluginItem` `this` names, with the handle numbers its `tracing` keeps. +fn plugin_of(h: &Host, a: &[Data]) -> Result<(Item, [f64; 4]), HostError> { + match host_ref_parts(arg(a, 0)) { + Some(("PluginItem", handle)) => { + let item = item_of(h, arg(a, 0))?; + match handle.as_slice() { + &[run, uid, high, low] => Ok((item, [run, uid, high, low])), + _ => Err(HostError::Type("this is not a PluginItem".into())), + } + } + _ => Err(HostError::Type("this is not a PluginItem".into())), + } +} + +/// Reads the Image Trace object of `item` with `f`. +fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -> Result) -> Result { + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(stale()), + }) +} + +/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`. +/// The selection stays as it was, with that object in place of `item`. +fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result { + let before = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); + on_doc(h, item.doc.uid, false, |h| { + let (_, r) = command_value(h, id, params)?; + let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; + let (want, now) = { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + let mut want: Vec = Vec::new(); + for i in before.iter().map(|i| if *i == item.id { new } else { *i }) { + if st.doc.node(i).is_some() && !want.contains(&i) { + want.push(i); + } + } + (want, st.selection.objects.clone()) + }; + if now != want { + if want.is_empty() { + command(h, "select.none", &json!({}))?; + } else { + command(h, "select.set", &json!({"ids": want.iter().map(|i| i.0).collect::>()}))?; + } + } + Ok(new) + }) +} + +/// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its +/// script objects follow the new one. +fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { + if h.dom.tracing.next.borrow().len() >= MAX_RETRACES { + return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); + } + params.insert("id".into(), json!(item.id.0)); + let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?; + replaced(h, item.doc.uid, item.id, new); + Ok(()) +} + +// ---- PlacedItem and RasterItem ---- + +/// `trace()`: `imageTrace.make` of the image with the Default preset → its `PluginItem`. +fn image_trace(h: &Host, a: &[Data], cls: &str) -> Answer { + let item = match host_ref_parts(arg(a, 0)) { + Some((c, _)) if c == cls => item_of(h, arg(a, 0))?, + _ => return Err(HostError::Type(format!("this is not a {cls}"))), + }; + let (source, linked) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let source = crate::cmd::is_trace_source(d, item.id); + let linked = matches!(d.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some()); + (source, linked) + }); + if source { + return Err(HostError::Error(ALREADY_TRACED.into())); + } + if linked { + let info = on_doc(h, item.doc.uid, false, |h| command(h, "links.info", &json!({"id": item.id.0})))?; + if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") { + return Err(HostError::Error(super::images::MISSING_LINK.into())); + } + } + let id = replace(h, item, "imageTrace.make", &json!({"id": item.id.0}), "id")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +fn placed_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "PlacedItem") +} + +fn raster_trace(h: &Host, a: &[Data]) -> Answer { + image_trace(h, a, "RasterItem") +} + +// ---- PluginItem ---- + +fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer { + plugin_of(h, a)?; + Ok(Data::Bool(true)) +} + +fn plugin_tracing(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = plugin_of(h, a)?; + Ok(host_ref("TracingObject", &handle)) +} + +// ---- TracingObject ---- + +/// What a tracing's counts are made of. +#[derive(Default)] +struct Counts { + paths: u64, + anchors: u64, + colors: u64, + /// The objects looked at. + visited: u64, +} + +fn anchors_of(n: &Node) -> u64 { + match &n.kind { + NodeKind::Path { path, .. } => path.anchor_count() as u64, + _ => n.children().map_or(0, |c| c.iter().map(|m| anchors_of(m)).sum()), + } +} + +/// The traced paths of the Image Trace object `g`, their anchor points and paints: every path +/// and compound path in it but its source image, the seam fills and clipping paths. +fn counts(g: &Node) -> Counts { + let mut c = Counts::default(); + let mut paints = HashSet::new(); + let mut todo: Vec<&Arc> = g.children().map(|ch| ch.iter().skip(1).collect()).unwrap_or_default(); + while let Some(n) = todo.pop() { + c.visited += 1; + if crate::cmd::is_seam_fills(n) { + continue; + } + match &n.kind { + NodeKind::Path { clipping: true, .. } => {} + NodeKind::Path { .. } | NodeKind::Compound { .. } => { + c.paths += 1; + c.anchors += anchors_of(n); + for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { + if paint != vectorcraft_color::Paint::None + && let Ok(key) = serde_json::to_string(&paint) + { + paints.insert(key); + } + } + } + _ => todo.extend(n.children().into_iter().flatten()), + } + } + c.colors = paints.len() as u64; + c +} + +/// Reads the counts of the tracing `this` names with `f`. +fn count(h: &Host, a: &[Data], f: fn(&Counts) -> u64) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let c = read_group(h, item, |_, g| Ok(counts(g)))?; + h.charge_call(c.visited)?; + Ok(num(float(f(&c)))) +} + +fn tracing_paths(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.paths) +} + +fn tracing_anchors(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.anchors) +} + +fn tracing_colors(h: &Host, a: &[Data]) -> Answer { + count(h, a, |c| c.colors) +} + +fn tracing_areas(h: &Host, a: &[Data]) -> Answer { + tracing_of(h, arg(a, 0), "TracingObject")?; + Err(HostError::Error(not_implemented("TracingObject", "areaCount"))) +} + +/// `imageResolution`: the source image's pixels per inch, 72 over the size of a pixel in points. +fn tracing_resolution(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |_, g| { + let source = g.children().and_then(|c| c.first()).ok_or_else(stale)?; + let NodeKind::Image(im) = &source.kind else { return Err(stale()) }; + let none = || HostError::Error("the source image has no single resolution".into()); + if source.is_distorted_image() { + return Err(none()); + } + let [xa, xb, ya, yb, ..] = im.xf.as_coeffs(); + let (across, down) = (xa.hypot(xb), ya.hypot(yb)); + if across <= 1e-12 || down <= 1e-12 || (across - down).abs() > 1e-9 * across.max(down) { + return Err(none()); + } + Ok(num(72.0 / across)) + }) +} + +fn tracing_parent(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))) +} + +fn tracing_source(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + read_group(h, item, |st, g| g.children().and_then(|c| c.first()).map(|s| item_ref(h, st, s.id)).ok_or_else(stale)) +} + +fn tracing_options(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("TracingOptions", &handle)) +} + +/// `expandTracing(viewed?)`: `imageTrace.expand` → the `GroupItem` that takes the tracing's place. +fn tracing_expand(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::Undefined | Data::Bool(false) => {} + Data::Bool(true) => { + tracing_of(h, arg(a, 0), "TracingObject")?; + return Err(HostError::Error(VIEWED_EXPAND.into())); + } + _ => return Err(HostError::Type("viewed must be true or false".into())), + } + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let id = replace(h, item, "imageTrace.expand", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. +fn tracing_release(h: &Host, a: &[Data]) -> Answer { + let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?; + Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) +} + +// ---- TracingOptions ---- + +/// The tracing `this` names, the settings it was traced with, its view and its preset's name. +fn options_of(h: &Host, a: &[Data]) -> Result<(Item, Map, TraceView, String), HostError> { + let (item, _) = tracing_of(h, arg(a, 0), "TracingOptions")?; + read_group(h, item, |_, g| { + let trace = g.extras().trace.as_deref(); + let params = trace.and_then(|t| t.get("params")).and_then(Value::as_object).cloned(); + let params = params.ok_or_else(|| HostError::Error("the tracing has no recorded options".into()))?; + let preset = trace.and_then(|t| t.get("preset")).and_then(Value::as_str).unwrap_or_default().to_string(); + Ok((item, params, g.trace_view(), preset)) + }) +} + +/// Reads the setting `key` of the tracing `this` names with `f`. +fn read_option(h: &Host, a: &[Data], key: &str, f: impl FnOnce(&Value) -> Answer) -> Answer { + let (_, params, ..) = options_of(h, a)?; + f(params.get(key).unwrap_or(&Value::Null)) +} + +/// Traces again with the setting `key` at `value`, unless it is at that value already. +fn write_option(h: &Host, a: &[Data], key: &str, value: Value) -> Answer { + let (item, mut params, ..) = options_of(h, a)?; + if params.get(key) == Some(&value) { + return Ok(Data::Undefined); + } + params.insert(key.into(), value); + let on = |k: &str| params.get(k).and_then(Value::as_bool) == Some(true); + if !on("fills") && !on("strokes") { + return Err(HostError::Error(NEEDS_FILLS_OR_STROKES.into())); + } + let mut p = Map::new(); + p.insert("params".into(), Value::Object(params)); + retrace(h, item, p)?; + Ok(Data::Undefined) +} + +/// A whole number from `lo` to `hi` for the option `name`. +fn whole_in(d: &Data, name: &str, lo: u64, hi: u64) -> Result { + let n = number(d, &format!("TracingOptions.{name}"))?; + if n.fract() != 0.0 || n < float(lo) || n > float(hi) { + return Err(out_of_range(name, &format!("a whole number from {lo} to {hi}"))); + } + whole(n).ok_or_else(|| out_of_range(name, &format!("a whole number from {lo} to {hi}"))) +} + +fn as_number(v: &Value) -> Answer { + v.as_f64().map(num).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn as_bool(v: &Value) -> Answer { + v.as_bool().map(Data::Bool).ok_or_else(|| HostError::Error("the tracing's options are damaged".into())) +} + +fn options_mode(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "mode", |v| { + let mode = v.as_str().unwrap_or_default(); + match MODES.iter().find(|(_, m)| *m == mode) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("TracingOptions.tracingMode has no value for this tracing's mode".into())), + } + }) +} + +fn options_set_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => MODES.iter().find(|(n, _)| n == s).map(|(_, m)| *m), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("TracingOptions.tracingMode must be a TracingModeType value".into()))?; + write_option(h, a, "mode", json!(mode)) +} + +fn options_threshold(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "threshold", as_number) +} + +fn options_set_threshold(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "threshold", 0, 255)?; + write_option(h, a, "threshold", json!(v)) +} + +fn options_max_colors(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "colors", as_number) +} + +fn options_set_max_colors(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "maxColors", 2, 256)?; + write_option(h, a, "colors", json!(v)) +} + +fn options_min_area(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "noise", as_number) +} + +fn options_set_min_area(h: &Host, a: &[Data]) -> Answer { + let v = whole_in(arg(a, 1), "minArea", 0, MAX_MIN_AREA)?; + write_option(h, a, "noise", json!(v)) +} + +fn options_fills(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "fills", as_bool) +} + +fn options_set_fills(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.fills")?; + write_option(h, a, "fills", json!(v)) +} + +fn options_strokes(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "strokes", as_bool) +} + +fn options_set_strokes(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.strokes")?; + write_option(h, a, "strokes", json!(v)) +} + +fn options_ignore_white(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "ignoreWhite", as_bool) +} + +fn options_set_ignore_white(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "TracingOptions.ignoreWhite")?; + write_option(h, a, "ignoreWhite", json!(v)) +} + +fn options_palette(h: &Host, a: &[Data]) -> Answer { + read_option(h, a, "palette", |v| { + let palette = v.as_str().unwrap_or_default(); + match PALETTES.iter().find(|(_, p)| *p == palette) { + Some((name, _)) => Ok(text(*name)), + None => Err(HostError::Error("the tracing's options are damaged".into())), + } + }) +} + +fn options_set_palette(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("TracingOptions.palette must be a string".into())) }; + let palette = PALETTES.iter().find(|(n, _)| n == name).map(|(_, p)| *p).ok_or_else(|| invalid("palette"))?; + write_option(h, a, "palette", json!(palette)) +} + +/// The view's `viewRaster` (`raster`) or `viewVector`. +fn view_part(view: TraceView, raster: bool) -> Answer { + let name = if raster { "viewRaster" } else { "viewVector" }; + VIEWS + .iter() + .find(|(v, ..)| *v == view) + .map(|(_, r, v)| text(if raster { *r } else { *v })) + .ok_or_else(|| HostError::Error(format!("TracingOptions.{name} has no value for the Split view"))) +} + +fn options_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (_, _, view, _) = options_of(h, a)?; + view_part(view, raster) +} + +/// Shows the view `viewRaster` (`raster`) or `viewVector` makes with the other one as it is. +fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer { + let (name, kind) = if raster { ("viewRaster", "ViewRasterType") } else { ("viewVector", "ViewVectorType") }; + let given = match arg(a, 1) { + Data::String(s) if ENUMS.iter().any(|(e, members)| *e == kind && members.iter().any(|m| *s == format!("{kind}.{m}"))) => s.clone(), + _ => return Err(HostError::Type(format!("TracingOptions.{name} must be a {kind} value"))), + }; + let (item, _, view, _) = options_of(h, a)?; + let Data::String(other) = view_part(view, !raster)? else { return Err(invalid(name)) }; + let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v }; + let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?; + if *to != view { + edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?; + } + Ok(Data::Undefined) +} + +fn options_view_raster(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, true) +} + +fn options_set_view_raster(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, true) +} + +fn options_view_vector(h: &Host, a: &[Data]) -> Answer { + options_view(h, a, false) +} + +fn options_set_view_vector(h: &Host, a: &[Data]) -> Answer { + options_set_view(h, a, false) +} + +fn options_preset(h: &Host, a: &[Data]) -> Answer { + let (_, _, _, preset) = options_of(h, a)?; + Ok(text(preset)) +} + +fn options_parent(h: &Host, a: &[Data]) -> Answer { + let (_, handle) = tracing_of(h, arg(a, 0), "TracingOptions")?; + Ok(host_ref("TracingObject", &handle)) +} + +/// A preset name given to `method`: a string of at most [`MAX_PRESET_NAME`] bytes without `/`, +/// `\`, `:` or control characters, trimmed. +fn preset_name<'a>(d: &'a Data, method: &str) -> Result<&'a str, HostError> { + let Data::String(name) = d else { return Err(HostError::Type(format!("TracingOptions.{method} needs a preset name, as a string"))) }; + if name.len() > MAX_PRESET_NAME { + return Err(HostError::Range(format!("TracingOptions.{method}: a preset name has at most {MAX_PRESET_NAME} bytes"))); + } + if name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) { + return Err(HostError::Error(format!("TracingOptions.{method}: a preset name cannot hold / \\ : or control characters"))); + } + let name = name.trim(); + if name.is_empty() { + return Err(HostError::Error(format!("TracingOptions.{method}: the preset name is empty"))); + } + Ok(name) +} + +/// `loadFromPreset(name)`: traces again with the built-in or saved preset `name` → `true`. +fn options_load(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "loadFromPreset")?; + let (item, params, _, preset) = options_of(h, a)?; + let wanted = vectorcraft_trace::preset(name).or_else(|| h.session.borrow().trace_preset(name).map(|q| q.params.clone())); + let wanted = wanted.ok_or_else(|| HostError::Error("TracingOptions.loadFromPreset: no built-in or saved preset has that name".into()))?; + let same = serde_json::to_value(&wanted).ok().as_ref().and_then(Value::as_object) == Some(¶ms); + if !(same && preset.eq_ignore_ascii_case(name)) { + let mut p = Map::new(); + p.insert("preset".into(), json!(name)); + retrace(h, item, p)?; + } + Ok(Data::Bool(true)) +} + +/// `storeToPreset(name)`: `false` for a built-in preset or `Custom`; any other name runs +/// `imageTrace.presets.save`, which a script cannot run. +fn options_store(h: &Host, a: &[Data]) -> Answer { + let name = preset_name(arg(a, 1), "storeToPreset")?; + let (_, params, ..) = options_of(h, a)?; + if vectorcraft_trace::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Ok(Data::Bool(false)); + } + command(h, "imageTrace.presets.save", &json!({"name": name, "params": params}))?; + Ok(Data::Bool(true)) +} + +/// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, +/// after the check that the tracing `this` names is still there. +fn missing(link: &Link, name: &'static str) -> (String, HostMember) { + let message = not_implemented("TracingOptions", name); + let l = link.clone(); + let f: vectorcraft_js::HostFunction = std::rc::Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16)?; + tracing_of(&h, arg(&a, 0), "TracingOptions")?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +/// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. +pub(super) fn add_trace(classes: &mut [HostClass], l: &Link) { + for c in classes.iter_mut() { + match c.name.as_str() { + "PlacedItem" => c.members.push(("trace".into(), method(l, placed_trace))), + "RasterItem" => c.members.push(("trace".into(), method(l, raster_trace))), + _ => {} + } + } +} + +/// `PluginItem`, after `PageItem`, `TracingObject` and `TracingOptions`. +pub(super) fn classes(l: &Link) -> Vec { + let plugin = named(vec![("isTracing", get(l, plugin_is_tracing)), ("tracing", get(l, plugin_tracing))]); + let tracing = named(vec![ + ("typename", typename_of("TracingObject")), + ("anchorCount", get(l, tracing_anchors)), + ("areaCount", get(l, tracing_areas)), + ("imageResolution", get(l, tracing_resolution)), + ("parent", get(l, tracing_parent)), + ("pathCount", get(l, tracing_paths)), + ("sourceArt", get(l, tracing_source)), + ("tracingOptions", get(l, tracing_options)), + ("usedColorCount", get(l, tracing_colors)), + ("expandTracing", method(l, tracing_expand)), + ("releaseTracing", method(l, tracing_release)), + ]); + let mut options = named(vec![ + ("typename", typename_of("TracingOptions")), + ("parent", get(l, options_parent)), + ("preset", get(l, options_preset)), + ("tracingMode", property(l, options_mode, options_set_mode)), + ("threshold", property(l, options_threshold, options_set_threshold)), + ("fills", property(l, options_fills, options_set_fills)), + ("strokes", property(l, options_strokes, options_set_strokes)), + ("maxColors", property(l, options_max_colors, options_set_max_colors)), + ("palette", property(l, options_palette, options_set_palette)), + ("ignoreWhite", property(l, options_ignore_white, options_set_ignore_white)), + ("minArea", property(l, options_min_area, options_set_min_area)), + ("viewRaster", property(l, options_view_raster, options_set_view_raster)), + ("viewVector", property(l, options_view_vector, options_set_view_vector)), + ("loadFromPreset", method(l, options_load)), + ("storeToPreset", method(l, options_store)), + ]); + options.extend(NOT_IMPLEMENTED.iter().map(|m| missing(l, m))); + vec![ + class("PluginItem", Some("PageItem"), plugin, None), + class("TracingObject", None, tracing, None), + class("TracingOptions", None, options, None), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1db3ccda6..0f140243ee 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -174,6 +174,7 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_images; +mod script_dom_tracing; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 1c1a78d864..87a775dbe4 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -457,8 +457,8 @@ fn members_not_available_yet_check_the_image_first() { &mut s, &base, "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ - try { n.trace; } catch (e) { m.push(e.message); }\ - p.embed(); try { p.trace; } catch (e) { m.push(e.message); }\ + try { n.contentVariable; } catch (e) { m.push(e.message); }\ + p.embed(); try { p.contentVariable; } catch (e) { m.push(e.message); }\ var r = d.rasterItems[0]; try { r.colorize; } catch (e) { m.push(e.message); }\ r.remove(); try { r.overprint; } catch (e) { m.push(e.message); }\ vc.log(m);", diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs new file mode 100644 index 0000000000..9479139027 --- /dev/null +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -0,0 +1,541 @@ +//! Tracing in the script object model: `trace()` on placed and raster items, the `PluginItem`, its +//! `TracingObject` and its `TracingOptions`, and the checks on what a script gives them. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-dom-tracing-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A 60 × 60 PNG of a black disc on white. +fn disc_png() -> Vec { + vectorcraft_trace::Raster::from_fn(60, 60, |x, y| { + let (dx, dy) = (f64::from(x) + 0.5 - 30.0, f64::from(y) + 0.5 - 30.0); + if dx * dx + dy * dy <= 400.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] } + }) + .encode_png() +} + +/// A session with one 400 × 300 pt document holding the disc image, linked (`link`) or embedded. +fn session(base: &Path, link: bool) -> (Session, NodeId) { + let png = base.join("main/disc.png"); + std::fs::write(&png, disc_png()).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": link})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + (s, id) +} + +/// Runs `text` as `main/main.jsx` in `base`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn log(s: &mut Session, base: &Path, text: &str) -> Vec { + let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The Image Trace objects of the active document. +fn traces(s: &Session) -> Vec { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if crate::cmd::is_trace_group(n) { + out.push(n.id); + } + }); + out +} + +/// The `trace` settings of the Image Trace object `id`. +fn trace_of(s: &Session, id: NodeId) -> Value { + s.active().unwrap().doc.node(id).and_then(|n| n.extras().trace.as_deref().cloned()).unwrap_or(Value::Null) +} + +/// Every top-level object of the active document's first layer. +fn top(s: &Session) -> Vec { + let d = &s.active().unwrap().doc; + d.children(Some(d.layers[0].id)).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default() +} + +/// Traces with the Default preset as a script does, which the script's counts should match: its +/// `paths` and `anchors`, and the different paints of the result. +fn command_counts(base: &Path, link: bool) -> (u64, u64, u64) { + let (mut s, id) = session(base, link); + let r = s.execute("imageTrace.make", &json!({"id": id.0})).unwrap(); + (r["paths"].as_u64().unwrap(), r["anchors"].as_u64().unwrap(), r["colors"].as_u64().unwrap()) +} + +#[test] +fn raster_trace_returns_plugin_with_counts() { + let base = folder("raster"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].clone(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, r = d.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing;\ + vc.log(p.typename); vc.log(p.isTracing); vc.log(t.typename); vc.log(t.sourceArt.name); vc.log(r.typename);\ + vc.log(t.pathCount); vc.log(t.anchorCount); vc.log(t.usedColorCount); vc.log(t.imageResolution);\ + vc.log(p.tracing.pathCount === t.pathCount); vc.log(t.parent.isTracing); vc.log(t.tracingOptions.typename);\ + vc.log(t.tracingOptions.parent.typename); vc.log(d.pageItems[0].typename); vc.log(t.tracingOptions.preset);", + ); + assert_eq!(out[..5], [json!("PluginItem"), json!(true), json!("TracingObject"), json!("src"), json!("RasterItem")]); + let (paths, anchors, colors) = command_counts(&base, false); + assert!(paths > 0 && anchors > 0, "{paths} {anchors}"); + assert_eq!(out[5], json!(paths)); + assert_eq!(out[6], json!(anchors)); + let used = out[7].as_u64().unwrap(); + assert!(used >= 1 && used <= colors, "{used} of {colors}"); + assert_eq!(out[8].as_f64(), ppi.as_f64()); + assert_eq!(out[9..], [json!(true), json!(true), json!("TracingOptions"), json!("TracingObject"), json!("PluginItem"), json!("Default")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(top(&s), groups); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_image_resolution_is_one_number_or_none() { + let base = folder("resolution"); + let (mut s, image) = session(&base, false); + let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].as_f64().unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.width = r.width * 2; r.height = r.height * 2;\ + var t = r.trace().tracing; vc.log(t.imageResolution); t.releaseTracing(); r.width = r.width * 2;\ + var m = ''; try { r.trace().tracing.imageResolution; } catch (e) { m = e.message; } vc.log(m);", + ); + assert!((out[0].as_f64().unwrap() - ppi / 2.0).abs() < 1e-9, "{out:?}"); + assert_eq!(out[1], json!("the source image has no single resolution")); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn placed_trace_returns_plugin_with_source_art() { + let base = folder("placed"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, pl = d.placedItems[0]; pl.name = 'src'; var p = pl.trace();\ + vc.log(p.typename); vc.log(p.tracing.sourceArt.name); vc.log(pl.typename); vc.log(pl.file.name);\ + var m = ''; try { pl.trace(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("PluginItem"), json!("src"), json!("PlacedItem"), json!("disc.png"), json!("The image is the source art of a tracing")]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(image), Some(groups[0]), "the image is the tracing's source"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_checks_the_image_first() { + let base = folder("unbound"); + let (mut s, image) = session(&base, true); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\ + try { n.trace(); } catch (e) { m.push(e.message); } p.embed(); try { p.trace(); } catch (e) { m.push(e.message); }\ + try { PlacedItem.prototype.trace.call(d.rasterItems[0]); } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(["PlacedItem.file is required", "Stale page item", "this is not a PlacedItem"])]); + assert!(traces(&s).is_empty()); + assert!(s.active().unwrap().doc.node(image).is_some()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_missing_link_refuses_preview() { + let base = folder("missing"); + let (mut s, image) = session(&base, true); + std::fs::remove_file(base.join("main/disc.png")).unwrap(); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.placedItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + assert_eq!(out, [json!("Linked image is missing")]); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_release_restores_source_kind() { + let base = folder("release"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src';\ + var p = r.trace(), t = p.tracing, o = t.tracingOptions, back = t.releaseTracing();\ + vc.log(back.name); vc.log(back.typename); vc.log(r.hidden);\ + var m = []; try { p.name; } catch (e) { m.push(e.message); } try { t.pathCount; } catch (e) { m.push(e.message); }\ + try { o.threshold; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out[..3], [json!("src"), json!("RasterItem"), json!(false)]); + assert_eq!(out[3], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_expand_returns_group_and_stales_plugin() { + let base = folder("expand"); + let (mut s, image) = session(&base, false); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0], p = r.trace(), t = p.tracing, m = [];\ + try { t.expandTracing(true); } catch (e) { m.push(e.message); }\ + try { t.expandTracing('yes'); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(p.isTracing);\ + var g = t.expandTracing(); vc.log(g.typename); vc.log(p === g); m = [];\ + try { p.isTracing; } catch (e) { m.push(e.message); } try { t.anchorCount; } catch (e) { m.push(e.message); }\ + try { r.name; } catch (e) { m.push(e.message); } vc.log(m); vc.log(app.activeDocument.pageItems[0] === g);", + ); + assert_eq!(out[0], json!(["TracingObject.expandTracing(true) is not implemented", "TypeError"])); + assert_eq!(out[1..4], [json!(true), json!("GroupItem"), json!(false)], "the group is a new object"); + assert_eq!(out[4], json!(["Stale page item", "Stale page item", "Stale page item"])); + assert_eq!(out[5], json!(true), "the group read again is the object expandTracing gave"); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + assert!(d.node(image).is_none(), "the expanded group keeps no source image"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_options_retrace_preserves_source_and_view() { + let base = folder("options"); + let (mut s, image) = session(&base, false); + let defaults = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap(); + let out = log( + &mut s, + &base, + "var r = app.activeDocument.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing, o = t.tracingOptions;\ + vc.log([o.tracingMode, o.threshold, o.fills, o.strokes, o.maxColors, o.palette, o.ignoreWhite, o.minArea]);\ + vc.log([o.viewRaster, o.viewVector]);\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE;\ + o.threshold = 200; o.minArea = 4;\ + vc.log([o.threshold, o.minArea, o.preset, o.viewRaster, o.viewVector]);\ + vc.log(t.sourceArt.name); vc.log(r.name); vc.log(p.isTracing); vc.log(p.tracing.tracingOptions.threshold); vc.log(t.pathCount > 0);", + ); + let mode = |m: &str| json!(format!("TracingModeType.TRACINGMODE{m}")); + let expected_mode = match defaults["mode"].as_str() { + Some("blackAndWhite") => mode("BLACKANDWHITE"), + Some("grayscale") => mode("GRAY"), + _ => mode("COLOR"), + }; + assert_eq!( + out[0], + json!([ + expected_mode, + defaults["threshold"], + defaults["fills"], + defaults["strokes"], + defaults["colors"], + "Limited", + defaults["ignoreWhite"], + defaults["noise"] + ]) + ); + assert_eq!(out[1], json!(["ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"])); + assert_eq!(out[2], json!([200, 4, "Custom", "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"])); + assert_eq!(out[3..], [json!("src"), json!("src"), json!(true), json!(200), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let t = trace_of(&s, groups[0]); + assert_eq!( + (t["params"]["threshold"].clone(), t["params"]["noise"].clone(), t["view"].clone()), + (json!(200), json!(4), json!("outlinesWithSourceImage")) + ); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + + // Assigning the values the options have already changes nothing. + let before = (undo_steps(&s), traces(&s)); + let out = log( + &mut s, + &base, + "var o = app.activeDocument.pageItems[0].tracing.tracingOptions; o.threshold = 200; o.minArea = 4; o.fills = true;\ + o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; vc.log(o.threshold);", + ); + assert_eq!(out, [json!(200)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_invalid_option_is_atomic() { + let base = folder("invalid"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();"); + let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + let cases = [ + ("o.threshold = 'x'", "TypeError"), + ("o.threshold = 256", "TracingOptions.threshold is out of range"), + ("o.threshold = -1", "TracingOptions.threshold is out of range"), + ("o.threshold = 1.5", "TracingOptions.threshold is out of range"), + ("o.threshold = NaN", "TypeError"), + ("o.maxColors = 1", "TracingOptions.maxColors is out of range"), + ("o.maxColors = 257", "TracingOptions.maxColors is out of range"), + ("o.minArea = 1e12", "TracingOptions.minArea is out of range"), + ("o.fills = 1", "TypeError"), + ("o.fills = false", "TracingOptions requires fills or strokes"), + ("o.tracingMode = 'color'", "TypeError"), + ("o.palette = 'Spectrum'", "TracingOptions.palette has an invalid value"), + ("o.palette = 3", "TypeError"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERADJUSTEDIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "TracingOptions.viewRaster has an invalid value"), + ("o.viewVector = 'outlines'", "TypeError"), + ("o.pathFitting = 3", "TracingOptions.pathFitting is not implemented"), + ("o.cornerAngle", "TracingOptions.cornerAngle is not implemented"), + ("o.resampleResolution = 72", "TracingOptions.resampleResolution is not implemented"), + ("t.areaCount", "TracingObject.areaCount is not implemented"), + ("o.loadFromPreset('No Such Preset')", "no built-in or saved preset has that name"), + ("o.loadFromPreset('../Default')", "cannot hold"), + ("o.loadFromPreset('C:\\\\x')", "cannot hold"), + ("o.loadFromPreset('a\\u0000b')", "cannot hold"), + ("o.loadFromPreset(new Array(300).join('x'))", "at most 256 bytes"), + ("o.loadFromPreset(' ')", "the preset name is empty"), + ("o.loadFromPreset(5)", "TypeError"), + ("o.storeToPreset('Mine')", "a script cannot run `imageTrace.presets.save`"), + ("o.storeToPreset('../Mine')", "cannot hold"), + ]; + let mut wrong = vec![]; + for (code, message) in cases { + let out = log( + &mut s, + &base, + &format!( + "var t = app.activeDocument.pageItems[0].tracing, o = t.tracingOptions, m = 'none';\ + try {{ {code}; }} catch (e) {{ m = e.name + ': ' + e.message; }} vc.log(m); vc.log(o.threshold);" + ), + ); + let m = out[0].as_str().unwrap_or_default().to_string(); + let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0])); + if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before { + wrong.push(format!("{code}: {m}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + assert!(s.prefs.trace_presets.is_empty(), "no preset was saved"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_presets_load_and_locked_store() { + let base = folder("presets"); + let (mut s, _) = session(&base, false); + let silhouettes = serde_json::to_value(vectorcraft_trace::preset("Silhouettes").unwrap()).unwrap(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + vc.log(o.loadFromPreset('Silhouettes')); vc.log(o.preset); vc.log(o.threshold);\ + vc.log(o.storeToPreset('Default')); vc.log(o.storeToPreset('custom')); vc.log(o.storeToPreset('Silhouettes'));", + ); + assert_eq!(out, [json!(true), json!("Silhouettes"), silhouettes["threshold"].clone(), json!(false), json!(false), json!(false)]); + let t = trace_of(&s, traces(&s)[0]); + assert_eq!(t["params"], silhouettes); + + // Loading the preset the tracing has already traces nothing again. + let before = (undo_steps(&s), traces(&s)); + let out = log(&mut s, &base, "vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('silhouettes'));"); + assert_eq!(out, [json!(true)]); + assert_eq!((undo_steps(&s), traces(&s)), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_external_retrace_undo_and_source_delete() { + let base = folder("stale"); + let (mut s, image) = session(&base, false); + let threshold = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap()["threshold"].clone(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = [];\ + var p = d.rasterItems[0].trace(), t = p.tracing; d.selection = p; vc.run('imageTrace.make', {{}});\ + try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\ + var q = d.pageItems[0], u = q.tracing, o = u.tracingOptions; o.threshold = 90; vc.log(o.threshold); vc.log(q.isTracing);\ + vc.run('edit.undo'); vc.log(q.isTracing); vc.log(o.threshold); vc.log(u.pathCount > 0);\ + var r = ''; try {{ u.sourceArt.remove(); }} catch (e) {{ r = e.message; }} vc.log(r); vc.log(u.pathCount > 0);\ + vc.run('edit.clear', {{ids: [{}]}});\ + try {{ u.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ q.isTracing; }} catch (e) {{ m.push(e.message); }}\ + vc.log(d.pageItems[0].typename); vc.log(m);", + image.0 + ), + ); + assert_eq!(out[..5], [json!(90), json!(true), json!(true), threshold, json!(true)], "the undo puts the first tracing back"); + assert!(out[5].as_str().is_some_and(|m| m.starts_with("cannot delete hidden or locked objects")), "{:?}", out[5]); + assert_eq!(out[6], json!(true), "the refused remove leaves the tracing"); + assert_eq!(out[7], json!("GroupItem"), "a group without its source image is no longer a tracing"); + assert_eq!(out[8], json!(vec!["Stale page item"; 4])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_deleted_plugin_is_stale() { + let base = folder("deleted"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = []; p.remove();\ + try { p.name; } catch (e) { m.push(e.message); } try { t.sourceArt; } catch (e) { m.push(e.message); }\ + try { o.threshold = 10; } catch (e) { m.push(e.message); } try { t.releaseTracing(); } catch (e) { m.push(e.message); }\ + try { o.pathFitting; } catch (e) { m.push(e.message); } try { o.cornerAngle = 1; } catch (e) { m.push(e.message); } vc.log(m);", + ); + assert_eq!(out, [json!(vec!["Stale page item"; 6])]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's trace of an image past the tracer's source limit (`vectorcraft_trace::MAX_SOURCE_PIXELS`, +/// 192 megapixels) is refused from the image's header before its pixels are decoded, and the run +/// leaves the document as it was. +#[test] +fn trace_large_image_is_bounded() { + let base = folder("large"); + let png = base.join("main/wall.png"); + std::fs::write(&png, super::linkspanel::png_header(30_000, 30_000)).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = NodeId(r["ids"][0].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.rasterItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);"); + let m = out[0].as_str().unwrap_or_default(); + assert!(m.contains("30000 × 30000 pixels") && m.contains("(192 megapixels)"), "{m}"); + assert!(traces(&s).is_empty()); + assert_eq!(top(&s), [image]); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_remove_all_takes_the_tracing() { + let base = folder("remove-all"); + let (mut s, _) = session(&base, false); + let out = log(&mut s, &base, "var d = app.activeDocument; d.rasterItems[0].trace(); d.pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, [json!(0)]); + assert!(traces(&s).is_empty()); + assert!(top(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_stop_rolls_back_long_work() { + let base = folder("stop"); + let (mut s, image) = session(&base, false); + let before = top(&s); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = s.execute("imageTrace.make", &json!({"id": image.0})); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(top(&s), before); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn image_trace_refuses_the_source_image_of_a_trace() { + let base = folder("source"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let e = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap_err().to_string(); + assert!(e.contains("source image of an Image Trace object"), "{e}"); + assert_eq!(traces(&s), [group]); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(group)); + + // With another image named after the source image, that other image is traced. + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let r = s.execute("imageTrace.make", &json!({"ids": [image.0, other.0]})).unwrap(); + let second = NodeId(r["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(other), Some(second)); + assert_eq!(d.parent_of(image), Some(group)); + assert_eq!(traces(&s).len(), 2); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_of_another_image_inside_a_tracing() { + let base = folder("inside"); + let (mut s, image) = session(&base, false); + let png = base.join("main/disc.png"); + let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let other = NodeId(other["ids"][0].as_u64().unwrap()); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\ + var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!("PluginItem"), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 2); + let d = &s.active().unwrap().doc; + let (a, b) = (d.parent_of(image).unwrap(), d.parent_of(other).unwrap()); + assert!(groups.contains(&a) && groups.contains(&b) && a != b, "each image is the source of its own tracing"); + assert!(d.parent_of(a) == Some(b) || d.parent_of(b) == Some(a), "one tracing is inside the other"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_source_art_is_not_listed_with_the_images() { + let base = folder("lists"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.rasterItems[0].trace(); var n = d.rasterItems.length, k = 0;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename === 'RasterItem') k++; }\ + d.rasterItems.removeAll(); vc.log(n); vc.log(k); vc.log(d.rasterItems.length); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, [json!(1), json!(1), json!(0), json!("PluginItem")]); + assert_eq!(traces(&s).len(), 1, "removing the raster items leaves the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_plugin_keeps_its_name() { + let base = folder("renamed"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, m = '', n = p.name; p.name = n;\ + try { p.name = 'logo'; } catch (e) { m = e.message; } vc.log(m); vc.log(p.name === n); vc.log(p.typename); vc.log(t.pathCount > 0);", + ); + assert_eq!(out, [json!("The name of a tracing cannot be changed"), json!(true), json!("PluginItem"), json!(true)]); + assert_eq!(traces(&s).len(), 1); + assert_eq!(undo_steps(&s), 2, "the place and the run"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 931023a427..8593d593aa 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -78,7 +78,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems PlacedItem PlacedItems RasterItem RasterItems RulerUnits ZOrderMethod", + PageItems PlacedItem PlacedItems PluginItem RasterItem RasterItems RulerUnits TracingObject TracingOptions ZOrderMethod", ), ("Application.", "prototype"), ( @@ -121,7 +121,9 @@ const INSIDE: &[(&str, &str)] = &[ ("PlacedItems.", "prototype"), ("PlacedItems.prototype.", "add constructor getByName index length parent removeAll typename"), ("PlacedItem.", "prototype"), - ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace trace="), + ("PlacedItem.prototype.", "boundingBox constructor contentVariable contentVariable= embed file file= matrix matrix= relink trace"), + ("PluginItem.", "prototype"), + ("PluginItem.prototype.", "constructor isTracing tracing"), ("RasterItems.", "prototype"), ("RasterItems.prototype.", "constructor getByName index length parent removeAll typename"), ("RasterItem.", "prototype"), @@ -129,7 +131,23 @@ const INSIDE: &[(&str, &str)] = &[ "RasterItem.prototype.", "bitsPerChannel boundingBox channels colorants colorants= colorize colorize= colorizedGrayscale constructor \ contentVariable contentVariable= embedded embedded= file imageColorSpace matrix matrix= overprint overprint= status \ - trace trace= transparent", + trace transparent", + ), + ("TracingObject.", "prototype"), + ( + "TracingObject.prototype.", + "anchorCount areaCount constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ + tracingOptions typename usedColorCount", + ), + ("TracingOptions.", "prototype"), + ( + "TracingOptions.prototype.", + "constructor cornerAngle cornerAngle= fills fills= ignoreWhite ignoreWhite= livePaintOutput livePaintOutput= \ + loadFromPreset maxColors maxColors= maxStrokeWeight maxStrokeWeight= minArea minArea= minStrokeLength \ + minStrokeLength= outputToSwatches outputToSwatches= palette palette= parent pathFitting pathFitting= \ + preprocessBlur preprocessBlur= preset resample resample= resampleResolution resampleResolution= storeToPreset \ + strokes strokes= threshold threshold= tracingMode tracingMode= typename viewRaster viewRaster= viewVector \ + viewVector=", ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), @@ -163,6 +181,15 @@ const INSIDE: &[(&str, &str)] = &[ ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), ("RasterLinkState.", "DATAFROMFILE DATAMODIFIED NODATA"), + // The enumerations of tracings. + ("", "TracingModeType ViewRasterType ViewVectorType"), + ("TracingModeType.", "TRACINGMODEBLACKANDWHITE TRACINGMODECOLOR TRACINGMODEGRAY"), + ("ViewRasterType.", "TRACINGVIEWRASTERADJUSTEDIMAGE TRACINGVIEWRASTERNOIMAGE TRACINGVIEWRASTERORIGINALIMAGE TRACINGVIEWRASTERTRANSPARENTIMAGE"), + ( + "ViewVectorType.", + "TRACINGVIEWVECTORNOTRACINGRESULT TRACINGVIEWVECTOROUTLINES TRACINGVIEWVECTOROUTLINESWITHTRACING \ + TRACINGVIEWVECTORTRACINGRESULT", + ), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 7cb632376d..b6bf5a3388 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -518,7 +518,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< if outcome(i, o, &r)? { let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; if matches!(fs, Value::String(_)) { - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; } } Ok(Value::Undefined) diff --git a/docs/mcp.md b/docs/mcp.md index bd8fa335c6..2fc817b9ad 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,7 +2756,38 @@ app through the global object `vc`, and writes to the Script Console and runs ot `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the - end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet. + end of the run. `contentVariable`, `colorants`, `colorize` and `overprint` are not available yet. +- `PlacedItem.trace()` and `RasterItem.trace()` trace the image with `imageTrace.make` and the Default preset and + return the Image Trace object as a `PluginItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/), whose + `isTracing` is `true` and whose `tracing` is its `TracingObject` + (https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/). A `TracingObject` has `sourceArt` (the traced image), + `pathCount`, `anchorCount`, `usedColorCount`, `imageResolution`, `tracingOptions`, `parent`, `expandTracing()` + (`imageTrace.expand`, which returns the expanded group) and `releaseTracing()` (`imageTrace.release`, which returns + the image). `TracingOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/) has `tracingMode`, + `threshold`, `maxColors`, `palette`, `fills`, `strokes`, `ignoreWhite`, `minArea`, `viewRaster`, `viewVector`, + `preset`, `parent`, `loadFromPreset(name)` and `storeToPreset(name)`, and the enumerations `TracingModeType`, + `ViewRasterType` and `ViewVectorType` hold strings such as `"TracingModeType.TRACINGMODECOLOR"`. VectorCraft's own + rules: `trace()` returns once the trace is made. It throws `The image is the source art of a tracing` on an image an + Image Trace object holds, and `Linked image is missing` on a linked image whose file is missing. `pathCount` does not + count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and + `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions + across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the + source image and the view, and a value the tracing already has runs no command. The `PluginItem`, `TracingObject` + and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole + number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest + image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, + `"Full Tone"` or `"Document Library"`; `viewRaster` and `viewVector` take only the pairs that match an Image Trace + view. A value of the wrong type throws a `TypeError`, a number out of range a `RangeError`, and nothing changes. + `expandTracing(true)` throws `TracingObject.expandTracing(true) is not implemented` with nothing changed. A preset + name is a string of at most 256 bytes without `/`, `\`, `:` or control characters. `storeToPreset` returns `false` + for a built-in preset name and `Custom`, and throws for any other name, since a script cannot run + `imageTrace.presets.save`. A tracing that was expanded, released, deleted, traced again by a command, or whose + source image was deleted throws `Stale page item`. A script gets the source image from `sourceArt`, and `pageItems`, + `placedItems` and `rasterItems` do not list it. Assigning a different `name` to a `PluginItem` throws + `The name of a tracing cannot be changed`. `areaCount`, `cornerAngle`, `livePaintOutput`, + `maxStrokeWeight`, `minStrokeLength`, `outputToSwatches`, `pathFitting`, `preprocessBlur`, `resample` and + `resampleResolution` throw an error that says they are not implemented. With a script running, `imageTrace.make` + stops at the run's stop request and changes nothing. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5073c9574c..5388cacfb9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,7 +1029,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Tracing, rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6a19ae164b18368ff74f751ad80325af21e4a1ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:34:45 -0800 Subject: [PATCH 020/533] Scripts: script.check counts imageCapture as a file write The checker lists Document.imageCapture with saveAs and exportFile as a document method that writes the file it is given, and the host name check gives it an OUTSIDE row. RasterizeOptions and ImageCaptureOptions move to the bare classes, as the save and export option classes did. A capture whose clipBounds miss all the art writes a blank image of that area, and a new test covers it; docs/mcp.md says so beside the rasterize rule, which throws an error for such bounds. --- .../engine/src/tests/script_raster_capture.rs | 25 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 ++++----- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 15 +++++++++++ docs/mcp.md | 3 ++- 5 files changed, 48 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index e48c7a2d46..762ef76bef 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -382,6 +382,31 @@ fn image_capture_exact_clip_bounds_and_matte() { let _ = std::fs::remove_dir_all(base); } +/// Bounds that miss every object still give an image of that area, blank or transparent. +#[test] +fn image_capture_of_bounds_without_art_is_blank() { + let base = folder("empty"); + let (mut s, dir) = capture_doc(&base); + // x 300 to 350 and y 100 to 50 (Y up): below and right of both rectangles. + let f = |n: &str| quoted(&dir.join(n)); + let source = format!( + "var d = app.activeDocument, o = new ImageCaptureOptions(); o.resolution = 72;\ + d.imageCapture(new File({}), [300, 100, 350, 50], o);\ + o.transparency = true; d.imageCapture(new File({}), [300, 100, 350, 50], o);", + f("blank.png"), + f("clear.png") + ); + let undo = undo_steps(&s); + script(&mut s, &base, &source); + for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { + let img = png(&dir.join(name)); + assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); + } + assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_rejects_64mp_and_side_limit_before_render() { let base = folder("huge"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b95a1076e5..52721f7c33 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -145,21 +146,18 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), - ("", "AntiAliasingMethod ImageCaptureOptions RasterizationColorModel RasterizeOptions"), + // The enumerations of rasterizing and the document's rasterize and window capture methods. + ("", "AntiAliasingMethod RasterizationColorModel"), ("Document.prototype.", "rasterize windowCapture windowCapture="), - ("ImageCaptureOptions.", "prototype"), - ("ImageCaptureOptions.prototype.", "constructor"), - ("RasterizeOptions.", "prototype"), - ("RasterizeOptions.prototype.", "constructor"), ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), ("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// and the save and export option classes. +/// and the save, export, rasterize and image capture option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions ImageCaptureOptions RasterizeOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index a73dd557d6..c87e1347d6 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -75,7 +75,7 @@ pub(crate) const REFLECT: &str = "reflect"; pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "imageCapture", "saveAs"]; // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e985fa3d0f..0f7fa38c7e 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `imageCapture` writes the file it is given, with or without bounds and options, and +/// called by its name in brackets; `rasterize` stays inside the document. +#[test] +fn image_capture_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument.imageCapture(f);\n", + "var d = app.activeDocument; d.imageCapture(f, [0, 0, 10, 10], new ImageCaptureOptions());\n", + "d['imageCapture'](f);\n", + "d.rasterize(d.pageItems[0]);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 4][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4904f683f1..4510330cba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,7 +2749,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot as `"AntiAliasingMethod.TYPEOPTIMIZED"`. VectorCraft's own rules: `clipBounds` is `[left, top, right, bottom]` in the run's script coordinates, as `geometricBounds` gives them, and bounds whose right edge is not right of the left one, or whose bottom edge is not - below the top one, throw an error. `rasterize` takes one page item or a list of at most 10,000; an object of another + below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` + writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and From cb6b9e3577318971ef681ad1dd4dac3f97628a21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:33:44 -0800 Subject: [PATCH 021/533] Rasterize: ids leave out an object inside another listed one object.rasterize with ids now does what the same objects selected do: an object listed with a group or layer that holds it is left out and the group is rasterized, as edit::roots_of leaves it out of a selection. Document.rasterize still throws an error for such a list before it runs the command. --- crates/engine/src/cmd/menucmds.rs | 16 +++++++++------- crates/engine/src/script/dom/raster_capture.rs | 13 ++++++++++++- docs/mcp.md | 6 +++--- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index f339f7b96f..c5bc2be07f 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, none inside another, each unlocked in unlocked layers and groups; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -949,8 +949,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } /// The objects `ids` names for Rasterize, in paint order: each an object of the active document, -/// listed once, none inside another listed one, and neither it nor a layer or group it is in -/// locked. +/// listed once, and neither it nor a layer or group it is in locked. An object inside another +/// listed one is left out, as `edit::roots_of` leaves it out of a selection. fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = super::checked_ids_param(s, p, "ids", cmd)?; let d = &s.doc()?.doc; @@ -960,24 +960,26 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { return Err(bad(cmd, format!("id {} is listed twice", id.0))); } } + let mut roots = Vec::with_capacity(ids.len()); for id in &ids { // The layers and groups from the top down to the object itself. let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; if d.node(*id).is_some_and(|n| n.is_layer()) { return Err(bad(cmd, format!("id {} is a layer, not an object", id.0))); } + if up.iter().any(|a| a != id && listed.contains(a)) { + continue; + } let parent = up.len().checked_sub(2).and_then(|i| d.node(up[i])); if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); } - if let Some(outer) = up.iter().find(|a| *a != id && listed.contains(*a)) { - return Err(bad(cmd, format!("id {} is inside id {}, which is listed too", id.0, outer.0))); - } if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } + roots.push(*id); } - Ok(vectorcraft_doc::Selection { objects: ids, ..Default::default() }.in_paint_order(d)) + Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) } /// The id of the image in `node`, the node Rasterize makes: the image itself, or the image in its diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 811d0c48c4..1ad9fcb395 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -176,7 +176,8 @@ fn rasterize_params(items: Option<&[(String, Data)]>) -> std::result::Result std::result::Result, HostError> { let list: Vec<&Data> = match d { Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("rasterize takes at most {MAX_LISTED} objects"))), @@ -196,6 +197,16 @@ fn sources(h: &Host, doc: Doc, d: &Data) -> std::result::Result, HostEr } ids.push(item.id.0); } + let listed: std::collections::HashSet = ids.iter().copied().collect(); + let inside = with_doc(h, doc, |_, st| { + ids.iter().find_map(|id| { + let up = st.doc.ancestry(crate::NodeId(*id))?; + up.iter().any(|a| a.0 != *id && listed.contains(&a.0)).then_some(()) + }) + }); + if inside.is_some() { + return Err(HostError::Error("a source page item is inside another one, which is listed too".into())); + } Ok(ids) } diff --git a/docs/mcp.md b/docs/mcp.md index 4510330cba..3ab6ead40d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9754,9 +9754,9 @@ of threaded text that it rasterizes out of its thread with the text it shows, as Threading text from the in and out ports), and the other frames keep the text they hold. `object.rasterize` refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, -without the objects it replaced. An id listed twice, an object inside another listed one, a layer, a path of a -compound path or a part of another object that is not a group, and an object that is locked or in a locked layer or -group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id +listed twice, a layer, a path of a compound path or a part of another object that is not a group, and an object that +is locked or in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. From fde921a7445f10bb9b18fb255209484123b8ed66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:44:39 -0800 Subject: [PATCH 022/533] Scripts: review fixes for tracing, placed items, saves and the New Document layout - The Image Trace panel's lookup test skips an Image Trace object's source image, as imageTrace.make does since trace() came in. - A save of several files refuses a path the file access in force refuses before any file is written, whatever writer the caller gives. - move and duplicate look a page item up through its class, so a PlacedItem that was embedded is stale as the relative object. - PLACEATEND into an Image Trace object puts the object directly above the source image, which stays the first child. - controlBounds takes in the anchors and Bezier handles of the item's paths. - The file of a PlacedItems.add() result is stale once its document closes. - Assigning PlacedItem.file reads the placed image's id from the command's own result, so an id above 2^53 binds and clears exactly. - The enumerations the save and export option defaults name are registered, with the members the scripting constants page lists. - A tracing replaced twice and then undone is followed to the one the document holds. - Choosing the artboard layout in force again keeps a preset's rows. - docs/mcp.md and docs/gaps.md describe controlBounds, a null preset for addDocument, the view options and scripted tracing. --- crates/engine/src/cmd/fileio/save.rs | 8 +- crates/engine/src/cmd/fileio/tests.rs | 25 ++++++ crates/engine/src/script/dom.rs | 82 +++++++++++++------ crates/engine/src/script/dom/images.rs | 28 +++---- crates/engine/src/script/dom/save_open.rs | 71 ++++++++++++++++ crates/engine/src/script/dom/tracing.rs | 39 +++++---- crates/engine/src/tests/script_dom.rs | 28 ++++++- crates/engine/src/tests/script_dom_images.rs | 61 ++++++++++++++ crates/engine/src/tests/script_dom_tracing.rs | 46 +++++++++++ crates/engine/src/tests/script_save_open.rs | 30 +++++++ .../tests/it/script_host_vs_scriptcheck.rs | 38 +++++++++ crates/ui-egui/src/dialogs/new_document.rs | 11 ++- .../ui-egui/src/panels/image_trace/tests.rs | 21 +++-- docs/gaps.md | 4 +- docs/mcp.md | 15 ++-- 15 files changed, 430 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 94187808c6..ba7e6682af 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,13 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is refused here, so none of the files is written, also through + // a `write` that does not check the file access itself. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 56e2a12f30..36ace77603 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -1038,6 +1038,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() { let _ = std::fs::remove_dir_all(&d); } +/// A save that writes several files, through a writer that does not check the file access in +/// force, writes none of them when that access refuses one: the save refuses it itself. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() { + let d = tmp_dir("refused-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let mut written = vec![]; + let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + job.write(|p, b| { + std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?; + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}"); + assert!(written.is_empty(), "{written:?}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87f348a24c..20d6668374 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1171,20 +1171,23 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result a.iter().collect(), d => vec![d], }; - let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; - let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); - if !ok { - let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); - return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + // The locked artboards are worked out once for the whole list. + with_doc(h, doc, |_, st| { + let locked = st.doc.locked_artboards(); + let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen = std::collections::HashSet::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locked, item.id) { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } } - if !ids.contains(&item.id) { - ids.push(item.id); - } - } - Ok(ids) + Ok(ids) + }) } fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { @@ -1453,6 +1456,28 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); + Ok(f.bounds(h.dom.coords.get(), handles.map_or(r, |b| r.union(b)))) +} + +/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown +/// paths in a group or compound path (a clip group's from its clipping path). `None` for other +/// objects. +fn handle_bounds(n: &crate::doc::Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), + NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b)) + } + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1623,19 +1648,25 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); - let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); - let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { - if handle_of(target, "Document").is_some() { - return Err(HostError::Error("a document as the relative object is not available yet".into())); - } - return Err(HostError::Type("the relative object must be a page item or a layer".into())); + // A page item is looked up as its class names it (a wrapper whose object changed class is + // stale), a layer by its handle. + let (doc, target) = if handle_of(target, "PageItem").is_some() { + let t = item_of(h, target)?; + (t.doc, t.id) + } else { + let handle = handle_of(target, "Layer"); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + (doc, id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -1672,7 +1703,10 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let d = &st.doc; let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); - let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // A clip group's first child is its clipping path, and an Image Trace object's its source + // image: both stay first (the source image itself may go to the end of its own tracing). + let source = crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent); + let clips = d.node(to.parent).is_some_and(|n| n.clips() || (crate::cmd::is_trace_group(n) && !source)) && count > 0; let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -1932,7 +1966,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index b1a3665190..10291e2ef1 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -40,9 +40,9 @@ use vectorcraft_geom::{Affine, Point}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, - editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, - with_doc, + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, doc_of, + doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -127,14 +127,6 @@ fn pending_handle(d: &Data) -> Option<[f64; 3]> { } } -/// The page item handle (run, uid and the two halves of the id) of the image a -/// `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result. -pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, HostError> { - let Some([run, uid, slot]) = pending_handle(d) else { return Ok(None) }; - let [high, low] = super::id_parts(pending_id(h, run, uid, slot)?); - Ok(Some([run, uid, high, low])) -} - /// The ids of a document's linked (`placed`) or embedded images in paint order. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; @@ -360,6 +352,8 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer { if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { let k = slot_of(h, run, uid, slot)?; if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + // Null while its document is open; stale once that document is closed. + find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; return Ok(Data::Null); } } @@ -387,12 +381,12 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { } let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let path = image_path(h, arg(a, 1), "PlacedItem.file")?; - let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?; - let ids: Vec = match field(&placed, "ids") { - Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(), - _ => Vec::new(), - }; - let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids"))); + // The ids are read from the command's own result, where every id is exact (a script number + // holds integers exactly only up to 2^53). + let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let ids: Vec = placed["ids"].as_array().map(|ids| ids.iter().filter_map(serde_json::Value::as_u64).collect()).unwrap_or_default(); + let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); + let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); match id.filter(|id| linked(*id)) { Some(id) => { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..04a06629d0 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -84,6 +84,77 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + // The enumerations of the option defaults ([`Default::Member`]), with the members + // https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "ZIP4BIT", + "ZIP8BIT", + "None", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "STYLEATTRIBUTES", "PRESENTATIONATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF8", "UTF16"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "GLYPHSUSEDPLUSENGLISH", "COMMONENGLISH", "GLYPHSUSEDPLUSROMAN", "COMMONROMAN", "GLYPHSUSED", "None"]), + ("SVGFontType", &["CEFFONT", "SVGFONT", "OUTLINEFONT"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index f8642f3b7d..4e37fb9f31 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -118,26 +118,31 @@ pub(super) struct State { } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put -/// it back put back the same object), else the Image Trace object that replaced it when this run -/// traced it again, else `id`. +/// it back put back the same object), else the first object the document holds among those that +/// replaced it, one after the other, when this run traced it again (an Undo can put back one of +/// them), else the last of them, else `id`. pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { - let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some()); - if held { - return id; - } - h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n)) -} - -/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to -/// `new` now. -fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { - let mut next = h.dom.tracing.next.borrow_mut(); - for ((u, _), to) in next.iter_mut() { - if *u == uid && *to == old.0 { - *to = new.0; + let s = h.session.borrow(); + let doc = s.documents().iter().find(|d| d.uid == uid); + let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some()); + let next = h.dom.tracing.next.borrow(); + let mut id = id; + // Each object is replaced by one made later, so the steps end; the bound holds them anyway. + for _ in 0..=next.len() { + if held(id) { + return id; + } + match next.get(&(uid, id.0)) { + Some(n) => id = NodeId(*n), + None => return id, } } - next.insert((uid, old.0), new.0); + id +} + +/// Records that `new` replaced `old` in the document `uid`. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); } /// The error of a member with no VectorCraft setting. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5bf276e3b9..18fdf0b133 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,20 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. +#[test] +fn page_item_control_bounds_take_in_the_handles() { + let (mut s, _, _) = doc(); + let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, i = p[p.length - 1]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; + let (visible, control) = (b(&out[0]), b(&out[1])); + assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); + assert!((control[1] - 300.0).abs() < 1e-9, "the handles reach the top of the page: {control:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -451,6 +465,14 @@ fn a_grid_by_column_takes_the_number_of_rows() { 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}"); + if layout.ends_with("GridByCol") { + // A column fills from the top before the next one starts, to the right of it (to the + // left from right to left). + let (first, second, next) = (boards[0].rect, boards[1].rect, boards[rows].rect); + assert!((second.x0 - first.x0).abs() < 1e-9 && second.y0 > first.y0, "{layout} {count}: {first:?} {second:?}"); + let rightward = next.x0 > first.x0; + assert_eq!(rightward, layout == "GridByCol", "{layout} {count}: {first:?} {next:?}"); + } } } @@ -1003,8 +1025,10 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + // String literals of the script, whatever characters the temporary folder's path holds. + let literal = |p: String| serde_json::to_string(&p).unwrap(); + let (p, other) = (literal(path.to_string_lossy().into_owned()), literal(format!("{}.other", path.to_string_lossy()))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 7a3b764276..8101e17ab0 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -522,3 +522,64 @@ fn members_not_available_yet_check_the_image_first() { assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); let _ = std::fs::remove_dir_all(base); } + +/// The `file` of a `PlacedItems.add()` result with no file is null while its document is open, and +/// the item is stale once that document is closed. +#[test] +fn a_pending_placed_items_file_is_stale_once_its_document_closes() { + let base = folder("pending-closed"); + let mut s = session(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems.add(); vc.log(p.file); vc.run('file.close', {});\ + var m = ''; try { vc.log(p.file); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(null), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + +/// Assigning `file` binds the placed item to the image `file.place` made, by its exact id, also +/// for an id above 2^53, which a script number does not hold exactly. +#[test] +fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { + let base = folder("big-id"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.placedItems.add(); p.file = new File('{}'); vc.log(p.file.name); vc.log(p.width);", js_path(&png)), + ); + assert_eq!(out, vec![json!("a.png"), json!(4)]); + let imgs = images(&s); + assert_eq!(imgs.len(), 1, "{imgs:?}"); + assert_eq!(imgs[0].0, NodeId(big)); + let _ = std::fs::remove_dir_all(base); +} + +/// A `PlacedItem` that was embedded is stale as the relative object of `move`: the raster item +/// it became is named by a fresh wrapper. +#[test] +fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ + p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, vec![json!("Stale page item"), json!("PathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 9479139027..dd48079cef 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -393,6 +393,26 @@ fn trace_external_retrace_undo_and_source_delete() { let _ = std::fs::remove_dir_all(base); } +/// After two option changes, an Undo puts back the tracing the first change made, and the objects +/// of the first tracing follow it there. +#[test] +fn trace_undo_of_the_second_retrace_reaches_the_first() { + let base = folder("chain"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\ + o.threshold = 90; o.threshold = 60; vc.log(o.threshold); vc.run('edit.undo');\ + vc.log(o.threshold); vc.log(p.isTracing); vc.log(p.tracing.pathCount > 0);", + ); + assert_eq!(out, [json!(60), json!(90), json!(true), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_deleted_plugin_is_stale() { let base = folder("deleted"); @@ -506,6 +526,32 @@ fn trace_of_another_image_inside_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// An object moved or duplicated to the end of a tracing goes directly above its source image, +/// which stays the tracing's first child. +#[test] +fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() { + let base = folder("at-end"); + let (mut s, _) = session(&base, false); + let png = base.join("main/disc.png"); + s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\ + r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATEND);\ + var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATEND);\ + vc.log(p.tracing.sourceArt.name); vc.log(d.rasterItems.length); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("src"), json!(2), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + let d = &s.active().unwrap().doc; + let names: Vec> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect(); + let name = |n: &str| Some(n.to_string()); + assert_eq!(names[..3], [name("src"), name("moved"), name("moved")], "the source stays first: {names:?}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..3812314b26 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -178,6 +178,36 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() { let _ = std::fs::remove_dir_all(base); } +/// The defaults of the options a save or export does not map are named through their +/// enumerations, and an options object given them saves as one left as it was. +#[test] +fn option_defaults_are_named_through_their_enumerations() { + let base = folder("enum-defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.colorDownsamplingMethod = DownsampleMethod.NODOWNSAMPLE;\n\ + o.colorCompression = CompressionQuality.None; o.monochromeCompression = MonochromeCompression.None;\n\ + o.flattenOutput = OutputFlattening.PRESERVEAPPEARANCE; o.pDFXStandard = PDFXStandard.PDFXNONE;\n\ + d.saveAs(new File(dir + '/a.pdf'), o);\n\ + var v = new ExportOptionsSVG(); v.cssProperties = SVGCSSPropertyLocation.STYLEATTRIBUTES;\n\ + v.documentEncoding = SVGDocumentEncoding.ASCII; v.DTD = SVGDTDVersion.SVG1_1; v.fontType = SVGFontType.CEFFONT;\n\ + v.fontSubsetting = SVGFontSubsetting.ALLGLYPHS; d.exportFile(new File(dir + '/s'), ExportType.SVG, v);\n\ + vc.log([DownsampleMethod.BICUBICDOWNSAMPLE, CompressionQuality.ZIP8BIT, SVGCSSPropertyLocation.ENTITIES]);" + ), + ); + assert_eq!(out, json!([["DownsampleMethod.BICUBICDOWNSAMPLE", "CompressionQuality.ZIP8BIT", "SVGCSSPropertyLocation.ENTITIES"]])); + assert!(std::fs::read(dir.join("a.pdf")).unwrap().starts_with(b"%PDF-")); + assert!(dir.join("s.svg").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// A save that writes several files, such as an EPS with a file per artboard, writes none of them /// when one may not be written. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 8593d593aa..3beea4cfed 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,6 +177,44 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of the save and export options' defaults. + ( + "", + "ColorConversion ColorDestination ColorProfile CompressionQuality DownsampleMethod MonochromeCompression \ + OutputFlattening PDFChangesAllowedEnum PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes \ + SVGCSSPropertyLocation SVGDTDVersion SVGDocumentEncoding SVGFontSubsetting SVGFontType", + ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM \ + AUTOMATICJPEG2000MEDIUM AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM \ + AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM \ + JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE \ + CHANGE40ANYCHANGES CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), // The enumerations of placed and raster items. ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..48f32b93d8 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,9 +253,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. The +/// layout in force chosen again changes nothing. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let (lay, shown, ..) = layout(d); + if key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay) { + return; + } let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) @@ -935,7 +939,10 @@ mod tests { set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + // The layout in force chosen again keeps the rows, and the columns follow them. + let kept = if to == "gridByColumn" { json!({"layout": to, "columns": 2, "rows": rows}) } else { json!({"layout": to, "columns": 3}) }; + assert_eq!(field(&app, "artboardLayout"), kept, "{to}, rows {rows}"); + assert_eq!(columns(&app), 3, "{to}, rows {rows}"); } } set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index c35a961aa3..ca44c496ac 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1674,16 +1674,24 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { } /// The object Trace acts on as the panel found it before [`find_target`]: every selected object put -/// in paint order, the first image or Image Trace object among them taken, else the first selected -/// object. +/// in paint order, the first image or Image Trace object among them taken (an Image Trace object's +/// source image is traced through that object, so it is skipped), else the first selected object +/// when it is neither. fn target_node_sorting_everything(app: &VectorcraftApp) -> Option { let st = app.session.active()?; - let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let traceable = |n: &Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let source = |id: NodeId| { + st.doc + .parent_of(id) + .and_then(|g| st.doc.node(g)) + .is_some_and(|g| is_trace(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) + }; st.selection .in_paint_order(&st.doc) .into_iter() - .find_map(|id| st.doc.node(id).filter(traceable).cloned()) - .or_else(|| first_selected(app).map(|n| (*n).clone())) + .filter(|id| !source(*id)) + .find_map(|id| st.doc.node(id).filter(|n| traceable(n)).cloned()) + .or_else(|| first_selected(app).filter(|n| !traceable(n)).map(|n| (*n).clone())) } /// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image @@ -1779,6 +1787,9 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace", "trace image"], &["trace image", "trace"], &["rect", "trace image"], + &["trace image"], + &["trace image", "rect"], + &["trace image", "front"], &["clip"], &["rect", "clipped"], &["outer"], diff --git a/docs/gaps.md b/docs/gaps.md index fc32f5b719..602b94f48a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and - `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + `rasterItems`, with `PlacedItem` and `RasterItem`), and trace them with `trace()`, which gives the Image Trace + object as a `PluginItem` with its `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no + setting for, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 00ad4fe8af..6730483bc9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2642,8 +2642,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A - `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a - `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + `presetSettings` of `null` or `undefined` counts as omitted. Any other `presetSettings` that is not a + `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, @@ -2656,7 +2656,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and + compound paths; a clip group's come from its clipping path), `editable`, `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 @@ -2717,7 +2718,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, - `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`, as + do the enumerations of the other options' defaults (`CompressionQuality`, `DownsampleMethod`, + `SVGCSSPropertyLocation` and the like), with the members + https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is @@ -2777,7 +2781,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the - source image and the view, and a value the tracing already has runs no command. The `PluginItem`, `TracingObject` + source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or + `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`, From 9b2bfcd50f933fbf8a3dd7cea2aab3afa4b35175 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:04:21 -0800 Subject: [PATCH 023/533] Scripts: a Copy or Cut the run puts back is not reported, and matrices keep finite values - A command whose result cannot reach the script is put back, and the run counts its Copy or Cut only when the clipboard keeps it. Before, a put-back command.batch left its copy on the clipboard, and a put-back Cut after an earlier copy still gave the report copied: true. command.batch now has the clipboard saved before it, as edit.cut and action.batch do. - concatenateMatrix and the other concatenate functions sum each value past the range of a number when a product overflows or falls below the normal range next to another product, so [2^600, 2^600, 0, 1] then [2^600, 0, -2^600, 1] gives [0, 2^600, -2^600, 1] instead of a RangeError, and two products of 2^-1075 sum to 2^-1074. - getRotationMatrix and concatenateRotationMatrix reduce the angle with a remainder that keeps its sign, so -89.99999999999999 is not rounded to the quarter turn 270; -90, -180 and -270 stay exact. - docs/mcp.md says isEqualMatrix and isSingularMatrix give true or false, not a new record. --- crates/engine/src/script/dom/matrix.rs | 54 ++++++++++++++++---- crates/engine/src/script/mod.rs | 25 +++++----- crates/engine/src/tests/script_dom_prefs.rs | 55 +++++++++++++++++++++ docs/mcp.md | 3 +- 4 files changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 71065256fb..9ee2fda4e6 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -2,8 +2,8 @@ //! and //! describe them. A matrix is a plain //! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function gives a new record and leaves the records passed to it as -//! they were. +//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a +//! new record, those two give a boolean, and none changes the records passed to it. //! //! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix //! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. @@ -81,11 +81,33 @@ fn number(d: &Data, what: &str, default: f64) -> std::result::Result Matrix { let [a, b, c, d, e, f] = m; let [a2, b2, c2, d2, e2, f2] = n; - [a * a2 + b * c2, a * b2 + b * d2, c * a2 + d * c2, c * b2 + d * d2, e * a2 + f * c2 + e2, e * b2 + f * d2 + f2] + [ + products_sum(a, a2, b, c2, 0.0) + 0.0, + products_sum(a, b2, b, d2, 0.0) + 0.0, + products_sum(c, a2, d, c2, 0.0) + 0.0, + products_sum(c, b2, d, d2, 0.0) + 0.0, + products_sum(e, a2, f, c2, e2) + 0.0, + products_sum(e, b2, f, d2, f2) + 0.0, + ] +} + +/// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of +/// normal numbers is the only one that is not 0, the sum is taken as numbers are. Otherwise the +/// products are summed past the range of a number and rounded at the end, so a finite value is not +/// lost to a product too large or too small for a number. +fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { + let (p, q) = (x * y, z * w); + let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; + let alone = |a: f64, b: f64| a == 0.0 || b == 0.0; + let plain = p + q; + if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + return plain + t; + } + products_difference(x, y, 0.0 - z, w).add(Wide::of(t)).value() } fn translate(dx: f64, dy: f64) -> Matrix { @@ -97,14 +119,15 @@ fn scaled(sx: f64, sy: f64) -> Matrix { [sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0] } -/// A turn of `degrees` counterclockwise, exact at quarter turns. +/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of +/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it. fn rotate(degrees: f64) -> Matrix { - let turn = degrees.rem_euclid(360.0); + let turn = degrees % 360.0; let (sin, cos) = match turn { 0.0 => (0.0, 1.0), - 90.0 => (1.0, 0.0), - 180.0 => (0.0, -1.0), - 270.0 => (-1.0, 0.0), + 90.0 | -270.0 => (1.0, 0.0), + 180.0 | -180.0 => (0.0, -1.0), + 270.0 | -90.0 => (-1.0, 0.0), _ => turn.to_radians().sin_cos(), }; // `0.0 - sin` rather than `-sin`, so a turn of 0 gives 0 and not -0. @@ -194,6 +217,19 @@ impl Wide { Self::new(self.m / o.m, self.e.saturating_sub(o.e)) } + /// The sum. A number more than 2^60 times smaller than the other is past its precision. + fn add(self, o: Self) -> Self { + let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) }; + if small.m == 0.0 { + return big; + } + let gap = small.e.saturating_sub(big.e); + if gap < -60 { + return big; + } + Self::new(big.m + small.m * pow2(gap), big.e) + } + /// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it. fn value(self) -> f64 { let (mut m, mut e) = (self.m, self.e); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index b914d3d57f..61f4f9d2ba 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -627,9 +627,10 @@ impl World { } } -/// The commands that can change the clipboard and still fail, and that do not put it back -/// themselves. The clipboard can hold a great deal, so a savepoint copies it only for these. -const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "edit.cut"]; +/// The commands that can change the clipboard and still fail, or still be put back because their +/// result cannot reach the script, and that do not put it back themselves. The clipboard can hold +/// a great deal, so a savepoint copies it only for these. +const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "command.batch", "edit.cut"]; /// The commands that remove a document's undo history, or the document: a savepoint keeps a whole /// copy of the histories for these. Any other command that removes or changes a step under the @@ -777,7 +778,8 @@ struct Host { log: RefCell>, log_bytes: Cell, written: RefCell, - /// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action. + /// A command ran a Copy or Cut ([`Session::copies`]), also inside a batch or an action, and + /// the run kept it. copied: Cell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, @@ -1265,7 +1267,6 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; - let copies = s.copies; crate::file_access::start_recording_writes(); // The command reads and writes only where the script's own files may, and the open documents' files. let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); @@ -1279,9 +1280,6 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value match r { Ok(v) => { note_ids(s); - if s.copies != copies { - host.copied.set(true); - } let (mut objects, mut bytes) = (0, 0); for st in &s.docs { match before.iter().find(|(uid, ..)| *uid == st.uid) { @@ -1341,9 +1339,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); - let r = { + let (copies, r) = { let mut s = session.borrow_mut(); - step(&mut s, host, &id, ¶ms) + (s.copies, step(&mut s, host, &id, ¶ms)) }; // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { @@ -1366,14 +1364,19 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Ok(data) }); // A command whose result does not reach the script is put back, like one that failed. + let mut s = session.borrow_mut(); if let Some(save) = save { - let mut s = session.borrow_mut(); if crossed.is_ok() { save.keep(&mut s); } else if !save.restore(&mut s) { return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // A Copy or Cut counts for the run only once what it put on the clipboard is kept. + if s.copies != copies { + host.copied.set(true); + } + drop(s); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index d8bb4dd77d..bac0981ccc 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -371,6 +371,36 @@ fn concatenation_applies_the_first_matrix_first() { ); } +#[test] +fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD, m.mValueTX, m.mValueTY]; }\ + function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var x = Math.pow(2, 600), y = Math.pow(2, -500), z = Math.pow(2, -575);\ + var c = app.concatenateMatrix(mat([x, x, 0, 1, x, x]), mat([x, 0, -x, 1, 0, 0]));\ + vc.log([c.mValueA, c.mValueB === x, c.mValueC === -x, c.mValueD, c.mValueTX, c.mValueTY === x]);\ + vc.log(app.concatenateMatrix(mat([y, y, 0, 1, 0, 0]), mat([z, 0, z, 1, 0, 0])).mValueA === Number.MIN_VALUE);\ + var p = 2.0543170765449965e-57, q = 6.201533916984909e-252;\ + vc.log(app.concatenateMatrix(mat([p, 0, 0, 1, 0, 0]), mat([q, 0, 0, 1, 0, 0])).mValueA === p * q);\ + vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));", + ); + assert_eq!(out, vec![json!([0, true, true, 1, 0, true]), json!(true), json!(true), json!([0, -2, 3, 0, 0, 0])]); +} + +#[test] +fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { + let mut s = Session::new(); + let out = log( + &mut s, + "function v(m) { return [m.mValueA, m.mValueB, m.mValueC, m.mValueD]; }\ + var m = app.getRotationMatrix(-89.99999999999999); vc.log(m.mValueA > 0); vc.log(m.mValueB);\ + vc.log(v(app.getRotationMatrix(-90))); vc.log(v(app.getRotationMatrix(-180))); vc.log(v(app.getRotationMatrix(-450)));", + ); + assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); @@ -476,3 +506,28 @@ fn only_copies_that_fill_the_clipboard_and_are_kept_are_counted() { assert_eq!(s.copies, 1); assert!(!s.clipboard_copied); } + +#[test] +fn a_copy_or_cut_the_run_puts_back_is_not_reported() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + // The clipboard holds a copy from before the run. + s.execute("edit.copy", &json!({})).unwrap(); + let copies = s.copies; + // No command result reaches the script, so each command below is put back. + crate::script::TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + "try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }", + ); + crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError"]), "{r}"); + assert_eq!(r.get("copied"), None, "{r}"); + assert_eq!(s.copies, copies); + assert!(s.clipboard_copied); + assert!(s.active().unwrap().doc.node(NodeId(a)).is_some()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 602e8187ab..aa65793760 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2715,7 +2715,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each - function gives a new record and leaves the ones passed to it unchanged. A record maps `(x, y)` to + function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. + No function changes the records passed to it. A record maps `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own rules: `concatenateMatrix(m, n)` applies `m` and then `n`, and the other `concatenate…` functions apply the record and then the transformation they make; a left-out move or angle is 0, a left-out `scaleX` is 100 and a left-out From ab12c44ebd68a318df3962d4e88896d62c9fff94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:59:26 -0800 Subject: [PATCH 024/533] JavaScript: .js scripts run async functions and await A .js script now reads async function declarations and expressions, async arrow functions and async methods in object literals, as ECMA-262 2017 section 25.5 defines them. A call returns a Promise that the function's return resolves and an uncaught exception rejects. await suspends the function's frame until its operand settles; a promise job resumes it with the value, or throws the rejection at the await, so try, catch and finally work around it. - Options::es2017 turns the syntax on and implies Options::es2015; script.run sets it for .js files. .jsx scripts and source strings keep async and await as plain names. - A suspended frame is a heap object the collector traces, reached only from its promise reactions, so a function waiting on a promise that nothing can settle is freed. Each resume is a job and takes fuel. - AsyncFunction and its prototype exist without a global binding; async functions are not constructors and have no prototype property. - The test262 runner reads the async-function, await and async-arrow folders and counts runs with and without the option; an async test with a runtime negative now has to throw. --- crates/engine/src/script/include.rs | 5 +- crates/engine/src/script/mod.rs | 4 +- crates/engine/src/tests/script_run.rs | 23 +++ crates/js/src/ast.rs | 4 + crates/js/src/async_tests.rs | 159 +++++++++++++++ crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/async_function.rs | 41 ++++ crates/js/src/builtins/promise.rs | 145 +++++++++++++- crates/js/src/bytecode.rs | 7 +- crates/js/src/compiler.rs | 14 +- crates/js/src/heap.rs | 14 +- crates/js/src/interp.rs | 109 ++++++++++- crates/js/src/interp/async_function.rs | 153 +++++++++++++++ crates/js/src/interp_tests.rs | 1 + crates/js/src/lib.rs | 26 ++- crates/js/src/parser.rs | 234 ++++++++++++++++++++--- crates/js/src/realm.rs | 8 + crates/js/tests/test262.rs | 134 ++++++++++++- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 20 files changed, 1047 insertions(+), 66 deletions(-) create mode 100644 crates/js/src/async_tests.rs create mode 100644 crates/js/src/builtins/async_function.rs create mode 100644 crates/js/src/interp/async_function.rs diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index a024949a35..f380c6cbd7 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -221,7 +221,8 @@ pub(crate) struct Files { es2015: bool, } -/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] and +/// [`vectorcraft_js::Options::es2017`] when its file name ends in /// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as /// ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { @@ -326,7 +327,7 @@ impl Files { /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { - Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, es2017: self.es2015, ..Options::default() } } /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a9c828532e..af62a9c5e6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1979,13 +1979,15 @@ impl Session { // A `.js` script's realm has the later editions' built-ins (`Promise`). A kept realm gets // them at the first `.js` run that names it, and keeps them as it keeps its globals. let es2015 = include::es2015_script(request.file.as_deref()); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; + // It also reads async functions and `await` (ECMAScript 2017). + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, es2017: es2015, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + realm.set_es2017(es2015); if es2015 { realm.add_es2015(); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 7b0e4bc2f8..3d08a4f64d 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -331,6 +331,29 @@ fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("es2017"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let src = "async function twice(p) { return 2 * await p; }\nvar half = async x => x / 2;\n\ + twice(Promise.resolve(3)).then(function (v) { vc.log(v); });\n\ + (async function () { try { await Promise.reject(new Error('no')); } catch (e) { vc.log(await half(8) + e.message); } })();\n\ + vc.log('sync');\n"; + let r = s.execute("script.run", &path(&write("async.js", src))).unwrap(); + assert_eq!(r["log"], json!(["sync", 6, "4no"]), "{r}"); + for (name, text) in [("async.jsx", "async function f() {}"), ("arrow.jsx", "var f = async x => x;")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + 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())); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..6fa32e6253 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -218,6 +218,8 @@ pub enum Expr { /// `...expression` in an array literal or an argument list, and as the last of an arrow /// function's parenthesized parameters while they are read. Spread(ExprId), + /// `await operand`, in an async function's body. + Await(ExprId), } /// A piece of a template literal's text between its substitutions. @@ -393,6 +395,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// An async function (ECMAScript 2017): a call returns a promise, and its body may `await`. + pub is_async: bool, pub span: Span, } diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs new file mode 100644 index 0000000000..46656f1205 --- /dev/null +++ b/crates/js/src/async_tests.rs @@ -0,0 +1,159 @@ +//! Async functions and `await` in realms with [`Options::es2017`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2017: true, ..Options::default() }, Limits::default()) +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +fn syntax_error(r: &mut Realm, src: &str) { + match r.run(src) { + Err(e) if e.kind == RunErrorKind::Syntax => {} + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn awaits_resume_in_the_job_order_promise_reactions_have() { + let src = "async function f() { log.push('f1'); await null; log.push('f2'); await null; log.push('f3'); }\n\ + f();\n\ + Promise.resolve().then(function () { log.push('t1'); }).then(function () { log.push('t2'); });\n\ + log.push('sync');"; + assert_eq!(log(src), "f1 sync f2 t1 f3 t2"); +} + +#[test] +fn the_function_returns_a_promise_its_return_resolves_and_its_throw_rejects() { + let src = "async function ok(x) { return x + 1; }\n\ + async function bad() { throw new TypeError('no'); }\n\ + var p = ok(1); log.push(p instanceof Promise);\n\ + p.then(function (v) { log.push('ok ' + v); });\n\ + bad().then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true ok 2 true"); +} + +#[test] +fn a_rejected_await_throws_where_it_stands_and_finally_runs_after_an_await() { + let src = "async function f() {\n\ + try { await Promise.reject('r'); log.push('not here'); }\n\ + catch (e) { log.push('caught ' + e); }\n\ + finally { await 1; log.push('finally'); }\n\ + return 'end';\n\ + }\n\ + f().then(function (v) { log.push(v); });"; + assert_eq!(log(src), "caught r finally end"); + let rethrow = "async function g() { try { await Promise.reject(new Error('x')); } finally { log.push('cleanup'); } }\n\ + g().catch(function (e) { log.push('rejected ' + e.message); });"; + assert_eq!(log(rethrow), "cleanup rejected x"); +} + +#[test] +fn arrows_expressions_and_methods_can_be_async() { + let src = "var a = async x => (await x) * 2;\n\ + var b = async (x, y) => { return await x + y; };\n\ + var c = async function named() { return typeof named; };\n\ + var o = { async m(v) { return this.k + await v; }, k: 'k' };\n\ + Promise.all([a(2), b(Promise.resolve(1), 2), c(), o.m('v')]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "4,3,function,kv"); +} + +#[test] +fn async_functions_are_not_constructors_and_have_no_prototype() { + let src = "async function f() {}\n\ + log.push(f.hasOwnProperty('prototype'));\n\ + try { new f(); } catch (e) { log.push(e instanceof TypeError); }\n\ + var AF = Object.getPrototypeOf(f).constructor;\n\ + log.push(AF !== Function, typeof AF, Object.getPrototypeOf(AF) === Function);\n\ + log.push(typeof this.AsyncFunction);\n\ + var g = AF('a', 'return await a;');\n\ + log.push(Object.getPrototypeOf(g) === Object.getPrototypeOf(f));\n\ + g(5).then(function (v) { log.push(v); });\n\ + log.push(String(async function h() { await 0; }));"; + assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); +} + +#[test] +fn await_is_an_identifier_outside_async_functions() { + let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ + var async = function (x) { return x; }; log.push(async(1));\n\ + async\nfunction g() {}\n\ + log.push(typeof g);"; + assert_eq!(log(src), "3 1 function"); + // A function in an async arrow function's parameters reads `await` as its own body does, + // and an async function declared in a script may be named `await`. + let nested = "var g = async (x = function () { return await; }) => x;\n\ + var h = async (x = async function () { await 0; }) => x;\n\ + async function await() { return 1; }\n\ + log.push(typeof g, typeof h, typeof await);"; + assert_eq!(log(nested), "function function function"); + let mut r = realm(); + syntax_error(&mut r, "async function f() { var await; }"); + syntax_error(&mut r, "async function f(await) {}"); + syntax_error(&mut r, "async function f(x = await 1) {}"); + syntax_error(&mut r, "function f() { await 1; }"); + syntax_error(&mut r, "if (1) async function f() {}"); + syntax_error(&mut r, "async (x = await 1) => x"); + syntax_error(&mut r, "async\n(x) => x"); + syntax_error(&mut r, "async (a = (...await) => {}) => {}"); +} + +#[test] +fn a_suspended_function_survives_a_collection_and_an_unreachable_one_is_freed() { + let mut r = realm(); + r.run( + "var resume; var gate = new Promise(function (res) { resume = res; });\n\ + var out = [];\n\ + async function f() { var local = { n: 41 }; var v = await gate; out.push(local.n + v); }\n\ + f();", + ) + .unwrap(); + r.interp().collect_garbage(); + r.run("resume(1);").unwrap(); + assert_eq!(r.run("out.join()").unwrap(), JsValue::String("42".into())); + // A function waiting on a promise nothing can settle is collected with it. + r.interp().collect_garbage(); + let before = r.interp().heap.live_cells(); + r.run("(function () { async function w() { var big = []; for (var i = 0; i < 200; i++) big.push({ i: i }); await new Promise(function () {}); } w(); })();") + .unwrap(); + r.interp().collect_garbage(); + let after = r.interp().heap.live_cells(); + assert!(after < before + 50, "{before} {after}"); +} + +#[test] +fn a_run_that_ends_with_awaits_pending_ends_cleanly() { + let mut r = realm(); + let v = r.run("async function f() { await new Promise(function () {}); return 1; } f(); 'done'").unwrap(); + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); + assert_eq!(r.run("1 + 1").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn each_resume_takes_fuel() { + let mut r = realm(); + r.set_limits(Limits { fuel: 20_000, ..Limits::default() }); + let e = r.run("async function f() { for (;;) await 0; } f();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); +} + +#[test] +fn es5_and_extendscript_realms_do_not_read_async_functions() { + let mut es2015 = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + syntax_error(&mut es2015, "async function f() {}"); + assert_eq!(es2015.run("var async = 1, await = 2; async + await").unwrap(), JsValue::Number(3.0)); + syntax_error(&mut Realm::with_options(Options::default(), Limits::default()), "async function f() {}"); + syntax_error(&mut Realm::new(), "var f = async () => 1;"); +} diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 26b351e14a..09cb089e5b 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -10,6 +10,7 @@ //! run past [`crate::Limits`]. mod array; +mod async_function; pub(crate) mod extensions; mod global; mod json; @@ -464,7 +465,16 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + dynamic_function(interp, args, false) +} + +/// The function `Function(p1, …, body)` makes, or with `is_async` the async function that +/// `AsyncFunction(p1, …, body)` makes from `(async function anonymous(p1,…\n) {\nbody\n})` +/// (ECMA-262 2017 section 25.5.1.1). An async function's source is read with +/// [`crate::Options::es2017`] whatever the realm reads scripts with, since only an async function +/// leads a script to `AsyncFunction`. +pub(crate) fn dynamic_function(interp: &mut Interp, args: &[Value], is_async: bool) -> JsResult { + let head: &str = if is_async { "(async function anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -476,12 +486,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -494,7 +504,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); - let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; + let es2017 = interp.options.es2017 || is_async; + let options = crate::Options { strict: false, max_source_units: remaining, es2017, ..interp.options.clone() }; let program = match crate::parse_utf16(&units, &options) { Ok(p) => p, Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)), diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs new file mode 100644 index 0000000000..43eea77b2a --- /dev/null +++ b/crates/js/src/builtins/async_function.rs @@ -0,0 +1,41 @@ +//! `AsyncFunction` and its prototype (ECMA-262 2017 section 25.5, +//! ), in realms with +//! [`crate::Options::es2015`]: the prototype of every async function, and the constructor a script +//! reaches through it. `AsyncFunction` is not a global. + +use super::{data, dynamic_function, native}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +/// Creates `AsyncFunction` and `AsyncFunction.prototype`, keeping the prototype for the async +/// functions the realm makes. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let function_proto = interp.intrinsics.function_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + interp.promises.async_function_proto = Some(proto); + let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; + interp.promises.async_function_ctor = Some(ctor); + // `Function` is the constructor's prototype (section 25.5.2). + let function_ctor = constructor_of(interp, function_proto); + if let Some(o) = interp.heap.object_mut(ctor) { + o.proto = function_ctor.or(o.proto); + } + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary + // built-in prototypes. + data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) +} + +/// The `constructor` property `proto` has from the built-ins, when it is an object. +fn constructor_of(interp: &Interp, proto: ObjId) -> Option { + match interp.get_own_property(proto, &crate::heap::key("constructor")) { + Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), + _ => None, + } +} + +/// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). +fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index d960fac60b..53d08f6f06 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -142,6 +142,8 @@ enum Then { Settle(ObjId), /// An exception rejects through this resolving record. Reject(ObjId), + /// An async function goes on after `await`; its own promise takes its result. + Resume, } /// The built-in functions a promise operation's functions call, with their record. @@ -156,9 +158,11 @@ enum Kind { CatchFinally, ValueThunk, Thrower, + AwaitFulfilled, + AwaitRejected, } -const KINDS: [(Kind, NativeFn); 9] = [ +const KINDS: [(Kind, NativeFn); 11] = [ (Kind::Resolve, resolve_function), (Kind::Reject, reject_function), (Kind::AllElement, all_element), @@ -168,6 +172,8 @@ const KINDS: [(Kind, NativeFn); 9] = [ (Kind::CatchFinally, catch_finally), (Kind::ValueThunk, value_thunk), (Kind::Thrower, thrower), + (Kind::AwaitFulfilled, await_continuation), + (Kind::AwaitRejected, await_continuation), ]; /// `Promise`'s objects and the run's job queue. @@ -186,11 +192,17 @@ pub(crate) struct Promises { rejected: Vec, /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). pub(crate) max_jobs: usize, + /// `AsyncFunction.prototype` (ECMA-262 2017 section 25.5.3), the prototype of async functions. + pub(crate) async_function_proto: Option, + /// `AsyncFunction` (section 25.5.1), which is not a global. + pub(crate) async_function_ctor: Option, } impl Default for Promises { fn default() -> Self { Self { + async_function_proto: None, + async_function_ctor: None, proto: None, ctor: None, natives: Vec::new(), @@ -208,10 +220,11 @@ impl Promises { /// Adds what the queue and the promise objects hold to the collector's roots. pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.objects.extend(self.async_function_proto.iter().chain(&self.async_function_ctor)); roots.values.extend(self.completion.iter()); match &self.running { Some(Then::Settle(o) | Then::Reject(o)) => roots.objects.push(*o), - None => {} + Some(Then::Resume) | None => {} } for job in &self.queue { match job { @@ -259,7 +272,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { let n = native(interp, "", f, 1, NativeKind::Plain, false)?; interp.promises.natives.push(n); } - Ok(()) + super::async_function::install(interp) } /// Turns on [`crate::Options::es2015`] in a realm made without it and creates `Promise` there, @@ -552,6 +565,120 @@ fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult }) } +// ---- async functions ---- + +/// The built-in a suspended async function's reactions are bound to. The job queue resumes the +/// function instead of calling it, and scripts cannot reach it. +fn await_continuation(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(Abrupt::Internal("an await continuation was called".into())) +} + +impl Interp { + /// Settles the promise of an async function whose frame ends: its return value resolves it, + /// and the exception that leaves it rejects it. + pub(crate) fn settle_async(&mut self, p: ObjId, r: Result) -> JsResult<()> { + match r { + Ok(v) => resolve_promise(self, p, v), + Err(e) => { + let site = caught(self); + reject_promise(self, p, e, site) + } + } + } + + /// A new pending promise for the async function call whose frame is on top. + pub(crate) fn new_async_promise(&mut self) -> JsResult { + new_promise(self) + } + + /// `await v` in the async function the top frame runs (Await, ECMA-262 2017 section 6.2.3.1, + /// with PromiseResolve as later editions have it): `v` becomes a built-in promise, the frame + /// is suspended until it settles, and the function's call gives its promise, `Some` when the + /// frame was the boundary frame. Throws at the `await` when reading `v`'s `constructor` throws. + pub(crate) fn await_value(&mut self, v: Value) -> JsResult> { + if self.async_promise().is_none() { + return Err(Abrupt::Internal("await outside an async function".into())); + } + let ctor = self.promises.ctor.map_or(Value::Undefined, Value::Object); + scoped(self, |interp| { + let p = promise_resolve(interp, &ctor, v)?; + root(interp, &p); + let Value::Object(p) = p else { return Err(Abrupt::Internal("PromiseResolve gave a value that is not a promise".into())) }; + let bytes = interp.suspend_bytes(); + interp.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let act = interp.heap.alloc_object(Object::new(Class::Activation(None), None)); + root(interp, &Value::Object(act)); + let on_fulfilled = record_function(interp, Kind::AwaitFulfilled, act, 1)?; + root(interp, &on_fulfilled); + let on_rejected = record_function(interp, Kind::AwaitRejected, act, 1)?; + root(interp, &on_rejected); + // The reactions settle no promise of their own; this one stays pending and unseen. + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + promise_data(interp, derived)?.handled = true; + perform_then(interp, p, on_fulfilled, on_rejected, derived)?; + let (a, boundary) = interp.suspend_frame()?; + let promise = a.promise; + let held = a.bytes(); + if let Some(o) = interp.heap.object_mut(act) { + o.class = Class::Activation(Some(Box::new(a))); + } + interp.heap.bytes = interp.heap.bytes.saturating_add(held); + if boundary { + return Ok(Some(Value::Object(promise))); + } + interp.push(Value::Object(promise))?; + Ok(None) + }) + } + + /// The activation `handler` resumes when it is a suspended async function's reaction, and + /// whether it is the rejection's. + fn await_activation(&self, handler: &Value) -> Option<(ObjId, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| self.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let reject = if self.promises.natives.get(Kind::AwaitFulfilled as usize) == Some(target) { + false + } else if self.promises.natives.get(Kind::AwaitRejected as usize) == Some(target) { + true + } else { + return None; + }; + match args.first() { + Some(Value::Object(act)) => Some((*act, reject)), + _ => None, + } + } + + /// Resumes the async function `handler` belongs to with the settled value: its frame goes back + /// on top as a boundary frame the caller runs, and a rejection is thrown at its `await`. A job + /// that finds the frame already resumed does nothing. + fn resume_async(&mut self, handler: &Value, argument: Value, reject: bool, site: Option) -> JsResult<()> { + let Some((act, _)) = self.await_activation(handler) else { return Err(Abrupt::Internal("not an await reaction".into())) }; + let taken = match self.heap.object_mut(act).map(|o| &mut o.class) { + Some(Class::Activation(slot)) => slot.take(), + _ => return Err(Abrupt::Internal("an await reaction lost its activation".into())), + }; + let Some(a) = taken else { return Ok(()) }; + self.heap.bytes = self.heap.bytes.saturating_sub(a.bytes()); + self.restore_frame(*a)?; + self.promises.running = Some(Then::Resume); + if !reject { + return self.push(argument); + } + if site.is_some() { + self.throw_site = site; + } + match self.unwind_or_abort(argument) { + Ok(Some(v)) => self.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => self.finish_job(Err(e)), + Err(e) => Err(e), + } + } +} + // ---- the job queue ---- impl Interp { @@ -627,6 +754,10 @@ impl Interp { self.use_fuel()?; scoped(self, |interp| { let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, site, .. } if interp.await_activation(&handler).is_some() => { + root(interp, &argument); + return interp.resume_async(&handler, argument, reject, site); + } Job::Reaction { handler, argument, reject, derived, site } => { if !interp.is_callable(&handler) { return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; @@ -660,7 +791,7 @@ impl Interp { match (then, r) { (Then::Settle(d), Ok(v)) => resolve_promise(self, d, v), (Then::Settle(d), Err(e)) => reject_promise(self, d, e, site), - (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(_), Ok(_)) | (Then::Resume, _) => Ok(()), (Then::Reject(rec), Err(e)) => scoped(self, |interp| { root(interp, &Value::Object(rec)); reject_through(interp, rec, e, site) @@ -835,8 +966,8 @@ fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult { let mut v = v.clone(); loop { @@ -845,7 +976,7 @@ fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { _ => return Ok(false), }; match func { - Func::Closure { .. } => return Ok(true), + Func::Closure { code, .. } => return Ok(!code.arrow && !code.is_async), Func::Native { constructor, .. } => return Ok(constructor), Func::Bound { target, .. } => { interp.use_fuel()?; diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 28db7edf3d..723ad84b40 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -205,6 +205,9 @@ pub(crate) enum Op { ToStr, /// Pushes the template object of `templates[i]`, the same object for each evaluation. TemplateObject(u32), + /// `value` → its awaited value: suspends the running async function until the value settles, + /// and goes on with its fulfillment value or throws its rejection reason here. + Await, } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -299,6 +302,8 @@ pub(crate) struct Code { /// The function has default or rest parameters: its parameters start uninitialized, its /// code initializes them and then enters its body with [`Op::BodyEnv`]. pub(crate) param_init: bool, + /// The code is an async function's: a call returns a promise, and it may run [`Op::Await`]. + pub(crate) is_async: bool, } impl Code { @@ -380,7 +385,7 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1), Op::ArraySpread | Op::NewSpread => e(2, 1), Op::CallSpread(_) => e(3, 1), - Op::ToStr => e(1, 1), + Op::ToStr | Op::Await => e(1, 1), }) } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index b5bdd16958..dac56b9359 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -268,12 +268,14 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some(f) = self.ast.function(*fid) else { return internal("function out of range") }; + let Some(name) = f.name.as_ref() else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations a variable, not async ones. + if !self.strict && !f.is_async { annex.push((k, scope, id)); } } else { @@ -1158,6 +1160,11 @@ impl<'a> FnCompiler<'a> { Expr::Template { quasis, exprs } => self.template(quasis, exprs)?, Expr::TaggedTemplate { .. } => self.chain(id)?, Expr::Spread(_) => return internal("spread outside an array literal or argument list"), + Expr::Await(arg) => { + self.expr(*arg)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::Await); + } Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?, Expr::Unary { .. } => self.unary(id)?, Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?, @@ -1762,6 +1769,7 @@ impl<'a> FnCompiler<'a> { arrow: meta.arrow, uses_this: self.uses_this, param_init: meta.param_init, + is_async: meta.is_async, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -1780,6 +1788,7 @@ struct Meta { length: u32, arrow: bool, param_init: bool, + is_async: bool, } fn len_u32(n: usize) -> u32 { @@ -1844,6 +1853,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, length: len_u32(length), arrow: f.kind == FunctionKind::Arrow, param_init, + is_async: f.is_async, }; c.finish(hoisted, meta) } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index a1af2cd0bd..e25bac7323 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -250,6 +250,8 @@ pub(crate) enum Class { Promise(Box), /// The state that the functions a promise operation makes share; scripts never see it. PromiseRecord(Box), + /// An async function's frame waiting at `await`, until it is resumed; scripts never see it. + Activation(Option>), } /// What an XML value is. @@ -313,7 +315,7 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) | Class::Activation(_) => "Object", Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", @@ -728,6 +730,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } extra = crate::builtins::promise::RECORD_BYTES; } + Class::Activation(Some(a)) => { + for v in a.values() { + mark_value(v, work, strings); + } + work.extend(a.ids()); + for code in a.codes() { + mark_code(code, strings); + } + extra = a.bytes(); + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 8c77936da5..783fd80f95 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -184,11 +184,16 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// The promise of the async function the frame runs: a return resolves it, an exception + /// that leaves the frame rejects it, and the call's value is the promise. + async_promise: Option, } /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +pub(crate) mod async_function; + /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -502,7 +507,8 @@ fn is(k: &[u16], s: &str) -> bool { } impl Interp { - pub(crate) fn new(options: Options, limits: Limits) -> Self { + pub(crate) fn new(mut options: Options, limits: Limits) -> Self { + options.es2015 = options.modern(); let mut heap = Heap::default(); let global = heap.alloc_object(Object::new(Class::Ordinary, None)); let global_env = heap.alloc_env(Env::Obj { object: global, with_this: false, outer: None }); @@ -787,7 +793,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.async_promise.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -816,7 +822,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(v), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(v); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -835,7 +845,11 @@ impl Interp { match self.step() { Ok(Some(v)) => return Ok(Some(v)), Ok(None) => {} - Err(Abrupt::Throw(v)) => self.unwind(v)?, + Err(Abrupt::Throw(v)) => { + if let Some(v) = self.unwind_or_abort(v)? { + return Ok(Some(v)); + } + } Err(other) => { self.note_site(); self.abort_to_boundary(); @@ -870,10 +884,26 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::Await => { + let v = self.pop()?; + self.await_value(v) + } _ => self.exec(op).map(|()| None), } } + /// [`Self::unwind`], ending the frames down to the boundary frame when it fails with a limit + /// or an internal error, which leaves the frame it was in on top. + pub(crate) fn unwind_or_abort(&mut self, v: Value) -> JsResult> { + match self.unwind(v) { + Err(e @ (Abrupt::Limit(_) | Abrupt::Internal(_))) => { + self.abort_to_boundary(); + Err(e) + } + r => r, + } + } + fn note_site(&mut self) { if self.throw_site.is_none() && let Some(f) = self.frames.last() @@ -884,7 +914,10 @@ impl Interp { /// Finds the handler for an exception: in the top frame, or in the frames below it up to the /// boundary frame. Returns the exception when no handler takes it before the boundary frame. - fn unwind(&mut self, v: Value) -> JsResult<()> { + /// An async function's frame without a handler rejects its promise with the exception and + /// returns the promise as a `return` would: `Some` with it when that frame was the boundary + /// frame. + fn unwind(&mut self, v: Value) -> JsResult> { self.note_site(); let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed @@ -920,10 +953,25 @@ impl Interp { if let (false, Some(site)) = (caught, site) { self.finally_sites.push((site, target_len)); } - return Ok(()); + return Ok(None); + } + // The promise is settled while the frame is still on top, so a limit reached doing it + // ends the frames the way any other limit does. + let promise = frame.async_promise; + if let Some(p) = promise { + self.settle_async(p, Err(v.clone()))?; } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + if let Some(p) = promise { + self.drop_left_finally_marks(); + self.drop_left_finally_sites(frame.base); + if frame.boundary { + return Ok(Some(Value::Object(p))); + } + self.push(Value::Object(p))?; + return Ok(None); + } if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -947,6 +995,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // An async function's return resolves its promise, while the frame is still on top, and + // the call gives the promise. + let v = match self.async_promise() { + Some(p) => { + self.settle_async(p, Ok(v))?; + Value::Object(p) + } + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); // A `return` in a finally block leaves the block, and the value takes its exception's slot. @@ -1100,7 +1157,7 @@ impl Interp { self.replace(1, Value::String(s)) } Op::TemplateObject(i) => self.op_template_object(i), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Return | Op::ReturnCompletion | Op::Await => internal("return reached the dispatcher"), } } @@ -2095,17 +2152,30 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let is_async = code.is_async; + let proto = match self.promises.async_function_proto { + Some(p) if is_async => p, + _ => self.intrinsics.function_proto, + }; let length = code.length; let strict = code.strict; let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; - // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). + // An arrow function has no `prototype` and cannot be constructed (section 14.2.16), and + // neither has nor can an async function (ECMA-262 2017 section 25.5.4). An async function + // must not have own `caller` or `arguments` properties, restricted or not, in sloppy code + // too (section 16.2). if arrow { return Ok(f); } + if is_async { + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } let p = self.new_object(); self.define(p, key("constructor"), Prop::Data { value: Value::Object(f), flags: HIDDEN })?; self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; @@ -2701,6 +2771,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.is_async => Err(self.type_error("an async function is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; let proto = match self.get_from(callee, &key("prototype"), &f)? { @@ -2764,6 +2835,7 @@ impl Interp { } }; let (fenv, var_env) = self.instantiate_function(&code, env, &args, callee)?; + let code_is_async = code.is_async; let base = self.stack.len(); self.frames.push(Frame { code, @@ -2777,7 +2849,16 @@ impl Interp { construct, completion: Value::Undefined, boundary, + async_promise: None, }); + // An async function's call makes its promise first thing (section 25.5.5.2); the frame + // keeps what the function holds reachable while it is made. + if code_is_async && let Err(e) = self.start_async_call() { + if let Some(frame) = self.frames.pop() { + self.stack.truncate(frame.base); + } + return Err(e); + } Ok(()) } @@ -3135,9 +3216,16 @@ impl Interp { self.global_lex } - /// Sets [`Options::es2015`] for the next runs. + /// Sets [`Options::es2015`] for the next runs; turning it off turns [`Options::es2017`] off too. pub(crate) fn set_es2015(&mut self, es2015: bool) { self.options.es2015 = es2015; + self.options.es2017 &= es2015; + } + + /// Sets [`Options::es2017`] for the next runs; turning it on turns [`Options::es2015`] on too. + pub(crate) fn set_es2017(&mut self, es2017: bool) { + self.options.es2017 = es2017; + self.options.es2015 |= es2017; } /// Declares a script's top-level `let` and `const` names in the global scope, uninitialized @@ -3213,6 +3301,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + async_promise: None, }); Ok(()) } diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs new file mode 100644 index 0000000000..7121215b9d --- /dev/null +++ b/crates/js/src/interp/async_function.rs @@ -0,0 +1,153 @@ +//! An async function's frame while it waits at `await` (ECMA-262 2017 sections 25.5 and 6.2.3.1, +//! ): [`Interp::suspend_frame`] moves the running +//! frame, its operands and its pending `finally` state into an [`Activation`], which lives on the +//! heap inside the functions that resume it, and [`Interp::restore_frame`] puts it back on top of +//! the frames to go on. An activation that nothing can resume any more is collected like any +//! other object. + +use std::rc::Rc; + +use super::{Frame, Interp, JsResult, ThrowSite, internal}; +use crate::bytecode::Code; +use crate::heap::{EnvId, ObjId}; +use crate::value::Value; + +/// The estimated bytes of an activation, beyond the object and its operands. +pub(crate) const ACTIVATION_BYTES: usize = 128; +/// The estimated bytes of each operand, `finally` mark or `finally` site an activation keeps. +pub(crate) const SLOT_BYTES: usize = 16; + +/// A suspended frame. Stack slots in `marks` and `sites` count from the frame's first operand. +#[derive(Clone)] +pub(crate) struct Activation { + code: Rc, + pc: usize, + env: EnvId, + var_env: EnvId, + env_depth: u32, + this: Value, + callee: Option, + completion: Value, + /// The promise the async function's call returned. + pub(crate) promise: ObjId, + stack: Vec, + marks: Vec<(ObjId, u32, usize)>, + sites: Vec<(ThrowSite, usize)>, +} + +impl Activation { + /// The values the activation holds, for the collector. + pub(crate) fn values(&self) -> impl Iterator { + self.stack.iter().chain([&self.this, &self.completion]) + } + + /// The objects and environments the activation holds, for the collector. + pub(crate) fn ids(&self) -> impl Iterator { + self.callee.iter().chain([&self.promise]).chain(self.marks.iter().map(|(o, _, _)| o)).map(|o| o.0).chain([self.env.0, self.var_env.0]) + } + + /// The code the activation runs and the code of its `finally` sites, for the collector. + pub(crate) fn codes(&self) -> impl Iterator { + std::iter::once(&*self.code).chain(self.sites.iter().map(|((code, _), _)| &**code)) + } + + /// The estimated bytes of the activation, beyond the object. + pub(crate) fn bytes(&self) -> usize { + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(self.stack.len() + self.marks.len() + self.sites.len())) + } +} + +impl Interp { + /// The promise of the async function the top frame runs, when it runs one. + pub(crate) fn async_promise(&self) -> Option { + self.frames.last().and_then(|f| f.async_promise) + } + + /// Makes the promise of the async function call whose frame was just pushed. + pub(crate) fn start_async_call(&mut self) -> JsResult<()> { + let p = self.new_async_promise()?; + match self.frames.last_mut() { + Some(f) => { + f.async_promise = Some(p); + Ok(()) + } + None => internal("an async call without a frame"), + } + } + + /// The bytes [`Self::suspend_frame`] will move off the operand stack, for the heap check made + /// before it. + pub(crate) fn suspend_bytes(&self) -> usize { + let Some(f) = self.frames.last() else { return ACTIVATION_BYTES }; + let n = self.stack.len().saturating_sub(f.base) + + self.finally_marks.iter().filter(|&&(_, _, s)| s >= f.base).count() + + self.finally_sites.iter().filter(|&&(_, s)| s >= f.base).count(); + ACTIVATION_BYTES.saturating_add(SLOT_BYTES.saturating_mul(n)) + } + + /// Takes the top frame, which runs an async function, off the frames with its operands and + /// its `finally` state. Gives the activation and whether the frame was a boundary frame. + pub(crate) fn suspend_frame(&mut self) -> JsResult<(Activation, bool)> { + let Some(frame) = self.frames.pop() else { return internal("await without a frame") }; + let Some(promise) = frame.async_promise else { return internal("await outside an async function") }; + let base = frame.base; + if self.stack.len() < base { + return internal("frame operands below the stack"); + } + let stack = self.stack.split_off(base); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(o, mark, slot)| { + if slot < base { + return true; + } + marks.push((o, mark, slot - base)); + false + }); + let at = self.finally_sites.iter().position(|&(_, slot)| slot >= base).unwrap_or(self.finally_sites.len()); + let sites = self.finally_sites.split_off(at).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let activation = Activation { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + promise, + stack, + marks, + sites, + }; + Ok((activation, frame.boundary)) + } + + /// Puts a suspended frame back on top of the frames as a boundary frame, with its operands at + /// the top of the operand stack. + pub(crate) fn restore_frame(&mut self, a: Activation) -> JsResult<()> { + if self.frames.len() >= self.limits.frames { + return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Frames)); + } + let base = self.stack.len(); + for v in a.stack { + self.push(v)?; + } + self.finally_marks.extend(a.marks.into_iter().map(|(o, mark, slot)| (o, mark, slot + base))); + self.finally_sites.extend(a.sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.frames.push(Frame { + code: a.code, + pc: a.pc, + base, + env: a.env, + var_env: a.var_env, + env_depth: a.env_depth, + this: a.this, + callee: a.callee, + construct: None, + completion: a.completion, + boundary: true, + async_promise: Some(a.promise), + }); + Ok(()) + } +} diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index d0bed32c1d..4a281a7b2f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -983,6 +983,7 @@ fn code(ops: Vec) -> Code { arrow: false, uses_this: false, param_init: false, + is_async: false, } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 3bc60375e9..36577c7960 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -63,6 +63,10 @@ //! jobs a script queues run in order once its code has ended, before its run ends, on the run's //! limits; a promise still rejected with no handler at the end is reported by //! [`Realm::unhandled_rejections`]. +//! +//! With [`Options::es2017`], the parser and the realm also read and run async functions and +//! `await` (ECMA-262 2017 section 25.5, ). +//! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] pub mod ast; @@ -126,11 +130,29 @@ pub struct Options { /// Give a realm the later editions' built-ins this engine has: `Promise` and its job queue. /// Off, a realm has the ES5.1 built-ins only, as ExtendScript scripts expect. pub es2015: bool, + /// Also read and run async functions and `await` (ECMAScript 2017). It turns on + /// [`Options::es2015`] too, whatever that field says. Off, `async` and `await` are identifiers. + pub es2017: bool, +} + +impl Options { + /// [`Options::es2015`], which [`Options::es2017`] turns on too. + pub(crate) fn modern(&self) -> bool { + self.es2015 || self.es2017 + } } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } + Self { + strict: false, + preprocessor_lines: false, + max_depth: DEFAULT_MAX_DEPTH, + max_source_units: 64 << 20, + e4x: false, + es2015: false, + es2017: false, + } } } @@ -226,6 +248,8 @@ impl LineTable { } } +#[cfg(test)] +mod async_tests; #[cfg(test)] mod builtins_tests; #[cfg(test)] diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index db034d1e2d..c2ce5505b3 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -36,6 +36,21 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is an async function's body: `await` is an operator, not an identifier. + in_async: bool, + /// The code is an async function's parameters: `await` is neither an operator nor an + /// identifier there (ECMA-262 2017 section 14.6.1). + async_params: bool, +} + +/// What the parser noted about a parenthesized expression or a call to `async` that may turn out +/// to be an arrow function's head. +#[derive(Clone, Copy, Debug)] +struct Head { + /// A line break comes between `async` and `(`. + line_break: bool, + /// The parentheses hold an `await` expression or the identifier `await`. + awaits: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -72,6 +87,8 @@ enum BinKind { enum Prefix { Unary(UnaryOp), Update(UpdateOp), + /// `await`, in an async function's body. + Await, } pub(crate) struct Parser<'s> { @@ -101,11 +118,20 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read async functions and `await` ([`crate::Options::es2017`]). + es2017: bool, + /// How many `await` expressions and `await` identifiers have been read. + awaits: u32, + /// The parenthesized expressions and calls to `async` read so far that may be arrow heads. + heads: HashMap, + /// The last identifier expression read from an `async` written without escapes. + async_ident: Option, } 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).with_e4x(options.e4x).with_es2015(options.es2015); + let es2015 = options.modern(); + let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(es2015); 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 { @@ -123,8 +149,12 @@ impl<'s> Parser<'s> { function_allowed: false, in_list: false, e4x: options.e4x, - es2015: options.es2015, - scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2015, + scopes: if es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + es2017: options.es2017, + awaits: 0, + heads: HashMap::new(), + async_ident: None, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -266,9 +296,23 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if name == "await" && (self.ctx.in_async || self.ctx.async_params) { + return Err(self.error_at_token(token, "'await' cannot be an identifier in an async function")); + } Ok(()) } + /// The current token is `async` written without escapes, read as the start of an async + /// function or arrow function only with [`crate::Options::es2017`]. + fn at_async(&self) -> bool { + self.es2017 && self.tok.ident() == Some("async") && !self.tok.escaped + } + + /// The current token is `async` and `function` follows it on the same line: an async function. + fn at_async_function(&self) -> bool { + self.at_async() && self.peek().is_some_and(|t| t.is_keyword(Keyword::Function) && !t.newline_before) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -280,6 +324,9 @@ impl<'s> Parser<'s> { if self.ctx.strict && is_eval_or_arguments(&name) { return Err(self.error_at_token(&self.tok, format!("'{name}' cannot be declared in strict mode"))); } + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } let token = self.bump()?; Ok(Name { name, span: token.span }) } @@ -341,7 +388,11 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some(f) = self.ast.function(id) else { return Ok(()) }; + let Some(name) = f.name.clone() else { return Ok(()) }; + // An async function in a block never repeats another name (Annex B.3.3.4 covers plain + // function declarations only). + let plain = !f.is_async; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -350,7 +401,7 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + Some(_) => self.declare_lexical(&name, plain), None => Ok(()), } } @@ -457,7 +508,7 @@ impl<'s> Parser<'s> { /// A source element: a function declaration or a statement. fn parse_statement_item(&mut self) -> Result { - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.parse_function_declaration(); self.leave(); @@ -509,6 +560,9 @@ impl<'s> Parser<'s> { } self.parse_function_declaration() } + TokenKind::Ident(_) if self.at_async_function() => { + Err(self.error_at_token(&self.tok, "an async function declaration cannot stand here; put it in a block")) + } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), _ => self.plain_statement(start), } @@ -959,9 +1013,11 @@ impl<'s> Parser<'s> { // ---- functions ---- fn parse_function_declaration(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, is_async)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -977,15 +1033,30 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `is_async`, an async function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + is_async: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with `await` as the function has it, then the code around + // them goes on as it was. + // An `await` inside the function does not count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = false; + self.ctx.async_params = is_async; + let result = self.function_rest(kind, name, start, is_async); + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, is_async: bool) -> Result { self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1025,7 +1096,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1034,13 +1105,18 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let span = self.span_from(start); + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, is_async, span }; + // An async declaration or expression takes FormalParameters as a plain function does + // (ECMA-262 2017 section 14.6): repeated simple names are an error only in strict code. + // Arrow functions and async methods reject every repeat. self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } - /// An arrow function's body and the function, from `=>`, with its parameters read. - fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result { + /// An arrow function's body and the function, from `=>`, with its parameters read; with + /// `is_async`, an async arrow function's. + fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool, is_async: bool) -> Result { if self.tok.newline_before { return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'")); } @@ -1048,7 +1124,7 @@ impl<'s> Parser<'s> { self.enter()?; let names: Vec = params.iter().chain(&rest).map(|p| p.name.clone()).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let block = self.at(Punct::LBrace); @@ -1066,7 +1142,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, is_async, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1081,6 +1158,13 @@ impl<'s> Parser<'s> { Some(Expr::Sequence(list)) => list.clone(), _ => vec![*inner], }; + self.arrow_items(items) + } + + /// The parameters the items of an arrow function's head give: names, names with `= default`, + /// and a last `...name`. + fn arrow_items(&self, items: Vec) -> Result { + let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters"); let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None); let name_of = |id: ExprId| match self.ast.expr(id) { Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }), @@ -1181,7 +1265,9 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; + // `async` followed on its line by a name starts an async arrow function. + let async_name = self.at_async() && self.peek().is_some_and(|t| matches!(t.kind, TokenKind::Ident(_)) && !t.newline_before); + let mut expr = if async_name { self.parse_async_name_arrow(no_in)? } else { self.parse_conditional(no_in)? }; if self.es2015 && self.at(Punct::Arrow) { expr = self.arrow_from(expr, no_in)?; } @@ -1203,12 +1289,39 @@ impl<'s> Parser<'s> { /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); - let params = match self.ast.expr(expr) { - Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None), - Some(Expr::Paren(_)) => self.arrow_params(expr)?, + let head = self.heads.get(&expr).copied(); + let (params, is_async) = match self.ast.expr(expr) { + Some(Expr::Ident(name)) => ((vec![Name { name: name.clone(), span: start }], vec![None], None), false), + Some(Expr::Paren(_)) => (self.arrow_params(expr)?, false), + // `async (…) =>` was read as a call to `async` (ECMA-262 2017 section 14.7). + Some(Expr::Call { args, .. }) if head.is_some() => { + if head.is_some_and(|h| h.line_break) { + return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); + } + (self.arrow_items(args.clone())?, true) + } _ => return Err(self.unexpected()), }; - self.parse_arrow(start, params, no_in) + // `await` cannot be an arrow function's parameter, or stand in one's default value, + // where it is an operator or in an async arrow function's head. + if head.is_some_and(|h| h.awaits) && (is_async || self.ctx.in_async) { + return Err(self.error_at_offset(start.start, "'await' cannot stand in an arrow function's parameters here")); + } + self.parse_arrow(start, params, no_in, is_async) + } + + /// `async name => …` from `async` (ECMA-262 2017 section 14.7): the one parameter is read as + /// an async function's is. + fn parse_async_name_arrow(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + let async_params = std::mem::replace(&mut self.ctx.async_params, true); + let param = self.binding_identifier(); + self.ctx.async_params = async_params; + let param = param?; + if !self.at(Punct::Arrow) { + return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok)))); + } + self.parse_arrow(start, (vec![param], vec![None], None), no_in, true) } /// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code @@ -1278,7 +1391,17 @@ impl<'s> Parser<'s> { /// Prefix operators, read with a loop and applied innermost first. fn parse_unary(&mut self) -> Result { let mut prefixes = Vec::new(); - while let Some(prefix) = prefix_op(&self.tok) { + loop { + // In an async function's body, `await` is a prefix operator (ECMA-262 2017 section 14.6). + let prefix = if self.ctx.in_async && self.tok.ident() == Some("await") { + if self.tok.escaped { + return Err(self.error_at_token(&self.tok, "keyword 'await' must not contain escaped characters")); + } + Prefix::Await + } else { + let Some(prefix) = prefix_op(&self.tok) else { break }; + prefix + }; prefixes.push((prefix, self.tok.span)); self.bump()?; } @@ -1296,6 +1419,10 @@ impl<'s> Parser<'s> { } self.ast.push_expr(Expr::Unary { op, arg: expr }, span) } + Prefix::Await => { + self.awaits = self.awaits.saturating_add(1); + self.ast.push_expr(Expr::Await(expr), span) + } }; } Ok(expr) @@ -1351,12 +1478,18 @@ impl<'s> Parser<'s> { expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span); } TokenKind::Punct(Punct::LParen) => { + let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); + let line_break = self.tok.newline_before; + let awaits = self.awaits; let args = self.parse_arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; + if async_head && self.at(Punct::Arrow) { + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + } } _ => break, } @@ -1409,9 +1542,19 @@ impl<'s> Parser<'s> { TokenKind::Keyword(Keyword::True) => Expr::Bool(true), TokenKind::Keyword(Keyword::False) => Expr::Bool(false), TokenKind::Keyword(Keyword::Function) => return self.parse_function_expression(), + TokenKind::Ident(_) if self.at_async_function() => return self.parse_function_expression(), TokenKind::Ident(name) => { let name = name.clone(); self.check_identifier(&self.tok, &name)?; + if name == "await" { + self.awaits = self.awaits.saturating_add(1); + } + if self.at_async() { + let token = self.bump()?; + let id = self.ast.push_expr(Expr::Ident(name), token.span); + self.async_ident = Some(id); + return Ok(id); + } Expr::Ident(name) } TokenKind::Number(n) => { @@ -1463,6 +1606,7 @@ impl<'s> Parser<'s> { /// function, which may also be `()` or end with `...name`; those two must come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; + let awaits = self.awaits; let mut items = Vec::new(); let mut head_only = self.at(Punct::RParen); while !self.at(Punct::RParen) { @@ -1493,7 +1637,11 @@ impl<'s> Parser<'s> { self.ast.push_expr(Expr::Sequence(items), span) } }; - Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start))) + let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); + if self.at(Punct::Arrow) { + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + } + Ok(paren) } /// A template literal from its first piece (the current token): its pieces and substitutions. @@ -1522,9 +1670,20 @@ impl<'s> Parser<'s> { } fn parse_function_expression(&mut self) -> Result { - let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let is_async = self.at_async(); + let start = if is_async { self.bump()?.span } else { self.tok.span }; + self.expect_keyword(Keyword::Function)?; + // A function expression's name is read as its own body reads names (ECMA-262 2017 + // section 14.6): `await` is a name for an ordinary one, and not for an async one. + // Nor does the name count for an arrow function's head around it. + let (in_async, async_params, awaits) = (self.ctx.in_async, self.ctx.async_params, self.awaits); + self.ctx.in_async = is_async; + self.ctx.async_params = false; + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.in_async = in_async; + self.ctx.async_params = async_params; + self.awaits = awaits; + let id = self.parse_function_rest(FunctionKind::Expression, name?, start, is_async)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1575,13 +1734,30 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } let key = PropertyKey::Ident(word.ident().unwrap_or_default().to_string()); return self.property_value(key, start); } + // `async name(…) {…}` (ECMA-262 2017 section 14.6): an async method, whose value is an + // async function that does not bind its own name. + if self.at_async() && self.peek().is_some_and(|t| !t.newline_before && property_key(&t).is_some()) { + self.bump()?; + let (key, _) = self.parse_property_key()?; + let function = self.parse_function_rest(FunctionKind::Expression, None, start, true)?; + // A method's parameters have distinct names (UniqueFormalParameters). + let mut seen = HashSet::new(); + for p in self.ast.function(function).into_iter().flat_map(|f| f.params.iter().chain(&f.rest)) { + if !seen.insert(p.name.as_str()) { + return Err(self.error_at_offset(p.span.start, format!("duplicate parameter name '{}'", p.name))); + } + } + let span = self.span_from(start); + let value = self.ast.push_expr(Expr::Function(function), span); + return Ok(Property { key, value: PropertyValue::Init(value), span }); + } let (key, _) = self.parse_property_key()?; self.property_value(key, start) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ce8e37df32..166b32cea0 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -240,6 +240,14 @@ impl Realm { self.interp.set_es2015(es2015); } + /// Sets [`Options::es2017`] for the next runs, and for the code they evaluate; on, it also + /// sets [`Options::es2015`]. Async functions an earlier run made keep running when it is + /// turned off. Call [`Realm::add_es2015`] too in a realm made without either option, since + /// an async function needs `Promise`. + pub fn set_es2017(&mut self, es2017: bool) { + self.interp.set_es2017(es2017); + } + /// Gives a realm made without [`Options::es2015`] the built-ins that option adds (`Promise`), /// for its next runs; a realm that has them already is left as it is. It does not take them /// away again. Call it between runs. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 62aa806316..66a5b159d7 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -863,12 +863,11 @@ fn promise_builtins_run() { handle.join().unwrap(); } -/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global -/// `print` that collects its output; an `async` test passes when it prints -/// `Test262:AsyncTestComplete`. -fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { - let options = Options { es2015: true, ..Options::default() }; - let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); +/// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` +/// that collects its output; an `async` test without a runtime negative passes when it prints +/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); let out = printed.clone(); realm.define_function("print", move |args| { @@ -882,7 +881,7 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Ok(JsValue::Undefined) }); let result = realm.run(script); - if asynchronous && result.is_ok() { + if asynchronous && negative_type.is_none() && result.is_ok() { let printed = printed.borrow(); return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { Ok(()) @@ -951,7 +950,8 @@ fn run_promise(dir: &Path) { let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; let script = if strict { format!("\"use strict\";\n{body}") } else { body }; let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); - match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + let es2015 = Options { es2015: true, ..Options::default() }; + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, &es2015)) { Ok(Ok(())) => counts.passed += 1, Ok(Err(why)) => { counts.failed += 1; @@ -988,6 +988,124 @@ fn run_promise(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The folders under `test/language/` that hold tests of async functions and `await`. +const ASYNC_FOLDERS: &[&str] = &["expressions/async-function", "statements/async-function", "expressions/await", "expressions/async-arrow-function"]; + +/// The feature tags an async-function test may carry and still run: [`ES2015_FEATURES`], +/// `async-functions` and `Promise`. +const ASYNC_FEATURES: &[&str] = &["async-functions", "Promise"]; + +#[test] +fn async_functions_run() { + let Some(dir) = suite_dir() else { + println!("test262 async functions: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_async_functions(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests in [`ASYNC_FOLDERS`] whose feature tags are all in [`ES2015_FEATURES`] or +/// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative +/// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests +/// included, skipping module tests and those that need a missing built-in. Prints the counts of +/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +fn run_async_functions(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let es2015 = Options { es2015: true, ..Options::default() }; + let es2017 = Options { es2015: true, es2017: true, ..Options::default() }; + let editions = [es2015, es2017.clone()]; + let mut counts = [Es2015Counts::default(), Es2015Counts::default()]; + let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize); + for folder in ASYNC_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !ES2015_FEATURES.contains(&f.as_str()) && !ASYNC_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("module") || meta.negative_phase.as_deref() == Some("resolution") { + skipped += 1; + continue; + } + let asynchronous = has("async"); + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &es2017) { + skipped += 1; + continue; + } + selected += 1; + for (options, counts) in editions.iter().zip(counts.iter_mut()) { + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let outcome = if expect_error { + let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; + if parse(&text, options).is_err() { + counts.parse_passed += 1; + continue; + } + counts.parse_failed += 1; + "parsed; a SyntaxError was expected".to_string() + } else { + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous, options)) { + Ok(Ok(())) => { + counts.run_passed += 1; + continue; + } + Ok(Err(why)) => { + counts.run_failed += 1; + why + } + Err(_) => { + counts.run_failed += 1; + counts.panicked += 1; + "PANIC".to_string() + } + } + }; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + assert!(selected > 0, "no async-function tests under {}", dir.display()); + let [before, after] = counts; + let report = dir.join("async-function-failures.txt"); + if let Err(e) = std::fs::write(&report, &after.failures) { + println!("could not write {}: {e}", report.display()); + } + let line = |c: &Es2015Counts| { + format!( + "negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)", + c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked + ) + }; + println!( + "test262 async functions: {selected} tests. With Options::es2015 alone: {}. With Options::es2017: {}. Skipped {skipped} module \ + or missing-built-in tests and {other_features} tests with other feature tags. Failures: {}", + line(&before), + line(&after), + report.display() + ); + assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); diff --git a/docs/mcp.md b/docs/mcp.md index a0108999dc..2c49b01d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,18 @@ own rules: all of them, and the Script Console shows an error line for each, as in `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. +A `.js` script also reads async functions and `await` as ECMA-262 2017 section 25.5 defines them +(https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, +async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function +goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` +work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is +reached through `Object.getPrototypeOf(async function () {}).constructor` and is not a global. Outside an async +function `await` is an ordinary name, and in a `.jsx` file or a `source` string `async` and `await` are ordinary +names and an async function is a syntax error. These are VectorCraft's own rules: each time a function resumes +counts as a job and takes 1 unit of fuel, and a function still waiting when no job is left stays suspended, and the +run ends. + Before any of the script runs, its preprocessor lines are read. The help page https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/ describes these lines, and https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/ describes `$.evalFile`, `$.fileName` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ea01b22966..65cabd7f70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1084,6 +1084,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. Until the language has iterators, `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 402 of 538 runs pass, where none ran before. The 136 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and a `name` on built-in functions. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. `await` is an identifier outside async functions, and `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file; `.jsx` scripts and `source` strings do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 81a2dea0a44ef212a2885a93396bb0b1fbaccce2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:27:11 -0800 Subject: [PATCH 025/533] Saves: a refused file of a save without a path is named by its file name A save of several files without a path given (separateArtboards) refuses a file outside the write root before any file is written, and the error now names that file by its file name, as the error for the document's own file does. A path the client gives stays whole in the error. --- crates/engine/src/cmd/fileio/save.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index ba7e6682af..3ae8def31b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Does a file the file access refuses before the first is written get named as + /// [`super::access::naming_in_error`] names it (a save without a path given)? + names_refused: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.names_refused = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1072,12 +1082,13 @@ impl SaveJob { } // Every path is checked against the file access in force before the first file is // written. A refused file is refused here, so none of the files is written, also through - // a `write` that does not check the file access itself. + // a `write` that does not check the file access itself. The error names the file as the + // job names refused files ([`SaveJob::naming_refused_files`]). #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some((p, refused)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) { - return Err(refused); + return Err(if self.names_refused { super::access::naming_in_error(refused, p) } else { refused }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1235,9 +1246,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refused_files() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) From 1f71bda80f66f37344ca4c5dec48e21a19e4d0cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:05:09 -0800 Subject: [PATCH 026/533] Scripts: imageCapture protects every place a link is read from - imageCapture refuses a path that any open document's link is read from: the stored path from the document's folder, the relative path from the file the document was read from (a template opened as an untitled document included), the name in those folders, and a DCS image's plate files beside each of those places. Documents the interface opened while the run was paused count too. - new IllustratorSaveOptions() starts with compatibility Compatibility.ILLUSTRATOR19. - PageItem.controlBounds throws that it is not available yet instead of giving the visible bounds. - move and duplicate with PLACEAFTER and a clipping group's clipping path as the relative object throw an error. - The settings of one run's DocumentPreset objects hold at most 4 MB together. - A run keeps the page-item lists of up to 8 documents, so reads that alternate between documents do not walk them again. --- crates/engine/src/cmd/links.rs | 46 +++++---- crates/engine/src/script/dom.rs | 54 ++++++++--- .../engine/src/script/dom/raster_capture.rs | 20 ++-- crates/engine/src/script/dom/save_open.rs | 7 +- crates/engine/src/script/mod.rs | 7 ++ crates/engine/src/tests/script_dom.rs | 61 +++++++++++- .../engine/src/tests/script_raster_capture.rs | 95 +++++++++++++++++++ crates/engine/src/tests/script_run.rs | 4 +- crates/engine/src/tests/script_save_open.rs | 4 +- docs/mcp.md | 16 ++-- 10 files changed, 258 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index febe0946de..4d6c2c8b39 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -194,16 +194,24 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { out } -/// The link of every linked image and placed document of `d`, wherever it is stored, brush art -/// included, with the plate files of an image placed from a DCS file. -pub(crate) fn linked_files_with_plates(d: &Document) -> Vec<(LinkInfo, Vec)> { - groups(d, None) - .into_iter() - .map(|g| { - let plates = g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&g.link.path, &f.name)).collect(); - (g.link, plates) - }) - .collect() +/// Every place a linked image or placed document of `d` (a document looking from `base`) is read +/// from, wherever it is stored, brush art included, whether or not a file is there: each place +/// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, +/// as its plate-change check finds them. A link's absolute stored and relative paths are listed +/// as they are too. +pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { + let mut out = vec![]; + for g in groups(d, None) { + let link = &g.link; + let mut mains: Vec = + std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).filter(|p| Path::new(p).is_absolute()).map(str::to_string).collect(); + mains.extend(places(link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } + } + out } /// The linked images and placed documents of `d` by file and content, wherever they are stored @@ -397,6 +405,17 @@ fn found_at(path: String) -> Option { /// by name in the document's folder, then in that of [`LinkBase::relative`]. Only paths /// [`fileio::document_path`] follows from the document's own file are looked at. fn locate(link: &LinkInfo, base: LinkBase) -> Option { + let mut f = places(link, base).find_map(found_at)?; + f.relative = base.relative.map(|from| { + let from = absolute_path(from); + Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) + }); + Some(f) +} + +/// The places [`locate`] looks for the file of `link` at, in its order, whether or not a file is +/// there. +fn places<'a>(link: &'a LinkInfo, base: LinkBase<'a>) -> impl Iterator + 'a { let (relative, other) = (link.relative.as_deref(), base.doc != base.relative); let stored = [ (Some(link.path.as_str()), base.doc), @@ -405,12 +424,7 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { (Some(link.name()), base.doc), (other.then_some(link.name()), base.relative), ]; - let mut f = stored.into_iter().filter_map(|(p, from)| follow_from(p?, from, base.doc, fileio::document_path)).find_map(found_at)?; - f.relative = base.relative.map(|from| { - let from = absolute_path(from); - Path::new(&from).parent().and_then(|dir| relative_path(Path::new(&f.path), dir)) - }); - Some(f) + stored.into_iter().filter_map(move |(p, from)| follow_from(p?, from, base.doc, fileio::document_path)) } /// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 478dbca2c5..d651d82867 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -87,17 +87,21 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// What the object model keeps for one run: its coordinate system, the last list of page items of +/// each of up to [`MAX_ITEM_LISTS`] documents, kept while that document is unchanged, whether a +/// call's own savepoint ([`atomically`]) is open, and the settings of each `DocumentPreset` the run +/// made. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + /// The documents' lists, the one listed most recently at the end. + items: RefCell>, saving: Cell, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, presets: RefCell>>, + /// What the settings in `presets` hold together ([`MAX_PRESET_BYTES`]). + preset_bytes: Cell, } impl State { @@ -130,6 +134,9 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// The most documents whose page-item lists a run keeps at once. +const MAX_ITEM_LISTS: usize = 8; + type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. @@ -339,10 +346,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { /// The ids of a document's page items in paint order ([`State`] keeps the last list). fn page_items(h: &Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.items.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - { + if let Some((_, _, ids)) = h.dom.items.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)) { return ids.clone(); } fn walk(nodes: &[Arc], out: &mut Vec) { @@ -361,7 +365,12 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); let ids = Rc::new(ids); - *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + let mut lists = h.dom.items.borrow_mut(); + lists.retain(|(uid, ..)| *uid != st.uid); + if lists.len() >= MAX_ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), ids.clone())); ids } @@ -950,20 +959,26 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + h.dom.preset_bytes.set(h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::())); + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; +/// The most bytes the settings of one run's `DocumentPreset` objects hold together, as +/// [`data_size`] counts them. +const MAX_PRESET_BYTES: u64 = 4 << 20; + /// The settings a `DocumentPreset` has, each a property a script reads and assigns. const PRESET_FIELDS: &[&str] = &[ "artboardLayout", @@ -1016,7 +1031,16 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; - match fields.iter_mut().find(|(k, _)| k == key) { + let slot = fields.iter_mut().find(|(k, _)| k == key); + // The settings of the run's presets hold at most MAX_PRESET_BYTES together, and the value a + // setting replaces no longer counts. + let old = slot.as_ref().map_or(0, |(_, v)| data_size(v)); + let kept = h.dom.preset_bytes.get().saturating_sub(old).saturating_add(data_size(&value)); + if kept > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("the DocumentPresets of a script can hold at most {} MB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(kept); + match slot { Some((_, v)) => *v = value, None => fields.push((key.to_string(), value)), } @@ -1628,6 +1652,10 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } Placement::Above | Placement::Below => { let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + let mask = d.node(parent).is_some_and(crate::doc::Node::clips) && d.position(target).is_some_and(|(_, i, _)| i == 0); + if how == Placement::Below && mask { + return Err(HostError::Error("an object cannot go below a clipping group's clipping path".into())); + } (parent, Some(target)) } }; @@ -1908,7 +1936,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), @@ -1920,6 +1947,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), [ "artworkKnockout", "blendingMode", + "controlBounds", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 1ad9fcb395..8883fb1714 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -281,22 +281,18 @@ fn capture_settings(items: Option<&[(String, Data)]>) -> std::result::Result<(f6 /// The files a capture must not write over: the open documents' files and the files their linked /// images and placed documents show, wherever those are stored (opacity masks, symbols, patterns /// and brushes included), with a DCS image's plate files, also when a file is missing, in the form -/// [`placed`] gives. A link's stored path and its relative path are each taken from its -/// document's folder, as opening the document reads them. +/// [`placed`] gives. A link's places are the ones opening the document looks at: its stored path +/// from the document's folder and its relative path from the folder of the file the document was +/// read from (a template opened as an untitled document has no file of its own), with a DCS +/// image's plate files beside each. The documents the interface has open while the run's slice +/// runs, such as one opened while the run was paused, count too. fn sources_on_disk(h: &Host) -> Vec { let s = h.session.borrow(); + let interface = h.interface_docs.borrow(); let mut paths: Vec = Vec::new(); - for st in s.documents() { + for st in s.documents().iter().chain(interface.iter()) { paths.extend(st.path.clone()); - let document = st.path.as_deref(); - for (link, plates) in crate::cmd::links::linked_files_with_plates(&st.doc) { - for stored in std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).chain(plates.iter().map(String::as_str)) { - if std::path::Path::new(stored).is_absolute() { - paths.push(stored.to_string()); - } - paths.extend(crate::cmd::fileio::document_path(stored, document).ok()); - } - } + paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); } paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..725330e3af 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -196,7 +196,12 @@ const AI_KEPT: &[(&str, Default)] = &[ ]; fn ai_starts() -> Vec<(&'static str, Data)> { - vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] + vec![ + ("compatibility", text("Compatibility.ILLUSTRATOR19")), + ("compressed", Data::Bool(true)), + ("pdfCompatible", Data::Bool(true)), + ("embedICCProfile", Data::Bool(false)), + ] } fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index affacab584..2225a89a3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -802,6 +802,9 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// While a slice runs: the documents the interface has open ([`World::docs`] of the run's + /// job), which a capture must not write over either. Empty between slices. + interface_docs: RefCell>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -2065,6 +2068,7 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::default(), + interface_docs: RefCell::new(Vec::new()), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2464,6 +2468,8 @@ fn failure_frame(report: &Value) -> (String, String) { fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result, String> { let depth = std::mem::replace(&mut s.depth, 0); job.world.swap(s); + // The interface's documents are the host's to read during the slice, and the job's again after. + std::mem::swap(&mut job.world.docs, &mut *job.host.interface_docs.borrow_mut()); // The run's front document draws and converts through its own profiles, and the interface's // again after the slice. s.sync_front_profiles(); @@ -2487,6 +2493,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result Vec { s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + assert_eq!(children(&s)[0], b, "the clipping path is the group's first child"); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for source in [ + "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + "var p = app.activeDocument.pageItems; p.getByName('loose').duplicate(p.getByName('mask'), ElementPlacement.PLACEAFTER);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("cannot go below a clipping group's clipping path"), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "a refused move changes nothing"); + assert_eq!(undo_steps(&s), steps); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('loose').move(p.getByName('mask'), ElementPlacement.PLACEBEFORE);"); + assert_eq!(children(&s), [b, c, a]); +} + #[test] fn a_copy_that_cannot_be_placed_is_deleted() { let mut s = Session::new(); @@ -670,9 +698,12 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].rotate(5);", + "app.activeDocument.pageItems[0].controlBounds;", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); @@ -824,6 +855,24 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); } +/// The presets of one run hold at most 4 MB of settings together; a setting that replaces another +/// gives back what the old value held. +#[test] +fn document_preset_settings_are_limited_in_bytes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var big = new Array(1572865).join('a'), p = new DocumentPreset(), q = new DocumentPreset();\ + p.title = big; p.units = big; p.title = big; q.title = 'x'; vc.log(p.title.length);\ + try { q.colorMode = big; } catch (e) { vc.log([e.name, e.message]); }\ + vc.log(q.colorMode === undefined); p.title = 'short'; q.colorMode = big; vc.log(q.colorMode.length);", + ); + assert_eq!(out[0], json!(1_572_864)); + assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); + assert_eq!(out[2], json!(true), "a refused setting is not stored"); + assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -1026,8 +1075,10 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + // Script string literals, so a quote or a backslash in the temporary folder's path stays text. + let literal = |p: String| serde_json::to_string(&p).unwrap(); + let (p, other) = (literal(path.to_string_lossy().into_owned()), literal(format!("{}.other", path.to_string_lossy()))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 762ef76bef..610882b419 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -616,6 +616,101 @@ fn capture_to_a_missing_links_path_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Places a linked image of the key `key` with `link` on the active document's default layer. +fn place_linked(s: &mut Session, key: &str, link: vectorcraft_doc::LinkInfo) { + s.edit("Place", |d, _| { + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: key.into(), + width: 1, + height: 1, + xf: vectorcraft_geom::Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + Ok(()) + }) + .unwrap(); +} + +/// An untitled document opened from a template finds a link by its relative path from the +/// template's folder, so a capture there is refused, also when the file is missing. +#[test] +fn capture_to_a_templates_relative_link_writes_nothing() { + let base = folder("template-link"); + let (mut s, dir) = capture_doc(&base); + let st = s.active_mut().unwrap(); + st.path = None; + st.links_from = Some(dir.join("t.vctemplate").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale, relative: Some("pic.png".into()), ..Default::default() }); + let target = dir.join("pic.png"); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!target.exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + +/// A DCS image whose stored path is stale reads its plate files beside the main file its relative +/// path finds, so a capture over one of those is refused. +#[test] +fn capture_over_a_plate_beside_a_found_dcs_file_writes_nothing() { + use vectorcraft_doc::separated::{InkPlate, PlateFile, Separated}; + let base = folder("dcs-plate"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + std::fs::write(dir.join("main.eps"), b"main").unwrap(); + let plate = dir.join("cyan.png"); + std::fs::write(&plate, b"kept").unwrap(); + let separated = Separated::new(1, 1, vec![InkPlate { name: "Cyan".into(), cmyk: [1.0, 0.0, 0.0, 0.0], data: vec![255] }]).unwrap(); + let files = [PlateFile { name: "cyan.png".into(), size: 4, modified: 0 }]; + let blob = vectorcraft_doc::ImageBlob::separated_tiff(&separated, None, &files).unwrap(); + s.edit("Blob", |d, _| { + d.images.insert("dcs".into(), blob); + Ok(()) + }) + .unwrap(); + let stale = base.join("outside/gone/main.eps").to_string_lossy().into_owned(); + place_linked(&mut s, "dcs", vectorcraft_doc::LinkInfo { path: stale, relative: Some("main.eps".into()), ..Default::default() }); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&plate))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&plate).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document the interface opens while the run is paused is open too: a capture over its file is +/// refused. +#[test] +fn capture_over_a_document_opened_while_paused_writes_nothing() { + let base = folder("paused-open"); + let (mut s, dir) = capture_doc(&base); + let target = dir.join("opened.png"); + let main = base.join("main/main.jsx"); + let text = format!( + "Folder.userData; for (var i = 0; i < 2000000; i++) {{}}\ + try {{ app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]); vc.log('written'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&target) + ); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + let svg = br#""#; + crate::cmd::fileio::open_bytes(&mut s, "opened.svg", svg, Some(target.to_string_lossy().into_owned())).unwrap(); + std::fs::write(&target, b"kept").unwrap(); + let r = loop { + if let Some(r) = s.script_pump() { + break r.unwrap(); + } + }; + s.script_frames = false; + let out = r["log"].as_array().cloned().unwrap_or_default(); + assert!(out.len() == 1 && out[0].as_str().is_some_and(|m| m.contains("cannot write over an open document")), "{out:?}"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_written_before_a_failure_is_reported() { let base = folder("report"); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 02176c38c9..fcd364e744 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -181,7 +181,9 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + // Names the app's own reference errors give a hint for: a script's own text keeps none. + ("throw '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"), ("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"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..d8d6a82a50 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -63,7 +63,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ d.saveAs(new File(dir + '/a.svg'));\n\ - var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ + var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability, new IllustratorSaveOptions().compatibility]);\n\ o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ o.colorCompression = 'CompressionQuality.None';\n\ d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ @@ -77,7 +77,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { var u = [app.userInteractionLevel]; app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; u.push(app.userInteractionLevel); vc.log(u);" ), ); - assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true])); + assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true, "Compatibility.ILLUSTRATOR19"])); assert_eq!(out[1], json!("b.pdf"), "saveAs gives the document the new file"); assert_eq!(out[2], json!("b.pdf"), "exportFile leaves the document's file as it is"); assert_eq!(out[3], json!(["Document", 2, true, "a.svg"])); diff --git a/docs/mcp.md b/docs/mcp.md index 3ab6ead40d..f8595cacc4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2639,7 +2639,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + starts with the defaults that page gives. The settings of the `DocumentPreset` objects one run makes hold at most + 4 MB together, and an assignment past that throws a `RangeError`. A preset's `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a @@ -2655,14 +2656,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to - 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `editable`, `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 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 + directly below it. `PLACEAFTER` with a clipping group's clipping path as the relative object throws an error and + changes nothing. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws @@ -2691,7 +2692,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. 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. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.controlBounds`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. @@ -2759,7 +2760,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error, also when that file is missing. A name that differs from it only in letter case throws the same error in a + error, also when that file is missing. The linked files are every place opening the document looks for a link's + file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS + image's plate files beside each, and the documents count whether they were open when the run started or were + opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to make it fit. `Document.windowCapture` throws an error that says it is not available yet. From 26e0cef48dad241c0e387c6dbb101c91c9a9f06c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:19:11 -0800 Subject: [PATCH 027/533] Scripts: ScriptUI palettes stay open after the run and run their handlers in line new Window("palette") in a script with a named #targetengine shows a palette that stays open beside the documents after the run ends. show() runs onShow and returns at once; hide(), show() and close() work as for a dialog, and close() and the close box run onClose. Each click, change or close on a palette runs its handler as a run of its own in the palette's engine, with its own report and undo step. While another run goes on, the event waits and runs after it, oldest first; a newer event for the same control or close replaces a waiting one. An error in a handler ends that run and leaves the palette open. A palette in a script without #targetengine, or with #targetengine main, throws an Error that asks for a #targetengine line. Palettes close when their engine is dropped or ends with an internal error, and when the session ends. A session keeps at most 16 palettes and 64 waiting events. script.palettes lists the palettes and their controls, and script.palette.event gives a palette a click, change or close. The script checker lists palettes under dialogs instead of hostOnly. --- crates/engine/src/cmd/scripts.rs | 45 +- crates/engine/src/lib.rs | 3 + crates/engine/src/script/files.rs | 10 +- crates/engine/src/script/mod.rs | 35 +- crates/engine/src/script/palettes.rs | 347 ++++++++++++++ crates/engine/src/script/scriptui.rs | 93 +++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_palettes.rs | 312 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/realm.rs | 10 + crates/js/src/scriptui.rs | 425 ++++++++++++++---- crates/js/src/scriptui_tests.rs | 126 +++++- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/lib.rs | 4 +- crates/scriptcheck/src/tests.rs | 6 + crates/ui-egui/src/app.rs | 6 + crates/ui-egui/src/dialogs/script_window.rs | 8 +- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 33 ++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/script_palettes.rs | 93 ++++ crates/ui-egui/src/script_runs.rs | 6 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_palettes.rs | 109 +++++ docs/mcp.md | 50 ++- docs/target-app-parity.md | 3 +- 51 files changed, 1649 insertions(+), 108 deletions(-) create mode 100644 crates/engine/src/script/palettes.rs create mode 100644 crates/engine/src/tests/script_palettes.rs create mode 100644 crates/ui-egui/src/script_palettes.rs create mode 100644 crates/ui-egui/src/tests/script_palettes.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index fd02b3a9a1..831b56c586 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, windows and resource strings throw that they are not available yet); new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -63,6 +63,24 @@ pub fn specs() -> Vec { always, engine_drop ), + cmd!( + query "script.palettes", + "List Script Palettes", + [], + None, + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + always, + palettes + ), + cmd!( + query "script.palette.event", + "Script Palette Event", + [], + None, + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + always, + palette_event + ), cmd!( query "script.console", "Script Console", @@ -245,6 +263,31 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result { Ok(json!({"dropped": true, "name": name})) } +fn palettes(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.script_palettes().iter().map(script::palettes::palette_json).collect(); + Ok(json!({ + "palettes": list, + "waiting": s.script_palette_events_waiting(), + "limit": script::palettes::MAX_PALETTES, + "waitingLimit": script::palettes::MAX_WAITING, + })) +} + +fn palette_event(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.palette.event"; + let Some(id) = p.get("palette").and_then(Value::as_u64) else { + return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it")); + }; + let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; + let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; + let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; + if s.script_frames { + return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); + } + s.script_palette_run_waiting() +} + fn console_lines(s: &mut Session, _: &Value) -> Result { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..5a790a06d9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -312,6 +312,9 @@ pub struct Session { pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run + /// ([`script::palettes`]). + pub(crate) script_palettes: script::palettes::Palettes, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..467e148696 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -216,6 +216,9 @@ pub(crate) struct Setup { pub script: Option, /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. pub source: String, + /// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's + /// handler, the one of the script that showed the palette. + pub own: Option, /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). pub data_dir: Option, /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source @@ -302,7 +305,7 @@ impl Disk { let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); let web = cfg!(target_arch = "wasm32"); let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); - let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes())); let script = script.map(|p| (p, own.clone())); let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); @@ -373,6 +376,11 @@ impl Disk { } } + /// The SHA-256 the run's grants are for ([`Setup::own`]). + pub(crate) fn own(&self) -> &str { + &self.own + } + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. fn saw(&mut self, hash: String) -> bool { if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index cb0398500a..de8f299cec 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -47,14 +47,20 @@ //! run. An engine keeps no document and no run: its host functions reach the run through a link //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +//! +//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and +//! whose events run as runs of their own in that engine, one at a time once no run is going. A +//! palette closes with its engine. pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod palettes; pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use palettes::{ScriptPalette, Waiting}; pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; @@ -801,6 +807,13 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The named engine the run is in; `None` for a new realm. + engine: Option, + /// The script file the run was read from; `None` for a script given as text. + file: Option, + /// For the run of a palette's handler, the palette's id and the event, until the palette takes + /// it ([`palettes`]). + palette_event: RefCell>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1686,6 +1699,7 @@ impl Session { match gone { Some(engine) => { drop(engine); + self.keep_engines_palettes(); Ok(()) } None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))), @@ -1933,6 +1947,7 @@ impl Session { lost }); drop(lost); + self.keep_engines_palettes(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1954,6 +1969,7 @@ impl Session { /// Begins a run of `request`. → the run's name. pub(crate) fn script_start(&mut self, request: Request) -> Result { + let palette_event = self.script_palettes.starting.take(); self.settle_for_script()?; // In a build where a fault ends the program, every unsaved document has a copy first. if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { @@ -2048,6 +2064,7 @@ impl Session { script: request.file.clone(), // The text with its included files, so a changed included file asks again. source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + own: palette_event.as_ref().and_then(|q| q.grants.clone()), data_dir: self.script_data_dir.clone(), engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { let m = m.borrow(); @@ -2068,6 +2085,9 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + engine: engine.clone(), + file: request.file.clone(), + palette_event: RefCell::new(palette_event), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2122,6 +2142,7 @@ impl Session { // error drops a kept one. let keep = !fresh && e.kind != RunErrorKind::Internal; self.return_engine(engine.as_deref(), &link, keep.then_some(realm)); + self.keep_engines_palettes(); let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0); close_run(self, &host, &mut report, ending(&e.kind)); let message = failure_text(&report); @@ -2212,6 +2233,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.keep_engines_palettes(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2481,6 +2503,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result realm.refresh_script_ui().map(|()| Progress::Done(v)), + // A failed run keeps its globals, so its palettes show what it left too; a refresh + // that fails as well (the fuel is spent, a stop) leaves them as they were. + Err(e) if named && e.kind != RunErrorKind::Internal => { + let _ = realm.refresh_script_ui(); + Err(e) + } + r => r, + } }) }); if let Some(started) = started { diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs new file mode 100644 index 0000000000..d6ff578f29 --- /dev/null +++ b/crates/engine/src/script/palettes.rs @@ -0,0 +1,347 @@ +//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a +//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and +//! changes while the person goes on working. +//! +//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script +//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once. +//! Each click, change or close the person gives a palette waits here, and then runs as a run of its +//! own in the palette's engine, which takes the mutation lease like any other run: one event at a +//! time, oldest first, each starting only once no run is going. While an event waits, another click +//! on the same control, another change of it or another close of the same palette takes its place +//! in line, with the newer value, instead of waiting as well. +//! +//! A palette closes when its script calls `close()` or the person closes it, unless `onClose` +//! returns `false`; when its engine is dropped or ends with an internal error; and with the session. +//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that +//! handler's run like any failed run, with its report, and leaves the palette open. +//! +//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`]. + +use std::collections::VecDeque; + +use serde_json::{Map, Value, json}; + +use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::{EngineError, Result, Session}; + +/// The most palettes a session keeps, shown or hidden. +pub const MAX_PALETTES: usize = 16; +/// The most events that wait for a run, for every palette together. +pub const MAX_WAITING: usize = 64; + +/// A palette a run showed. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptPalette { + /// Its number in the session, which no other palette of the session has had. + pub id: u64, + /// The named engine its handlers run in. + pub engine: String, + /// The script file of the run that first showed it, whose folder its handlers read in; `None` + /// for a script given as text. + pub file: Option, + /// Its controls, as the last `show()`, `add()` or handler left them. + pub dialog: ScriptUiDialog, + pub visible: bool, + /// The SHA-256 the file grants of the script that first showed it are kept for, which its + /// handlers' runs keep using. + pub(crate) grants: String, +} + +/// What became of an event given to a palette. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waiting { + /// It waits at the end of the line. + Added, + /// It took the place of a waiting event for the same control. + Merged, +} + +/// An event given to a palette, waiting for its run or handed to it. +#[derive(Clone, Debug)] +pub(crate) struct Queued { + pub(crate) palette: u64, + pub(crate) event: UiEvent, + /// For a list's change, the list's items as the palette showed them when the event was given and + /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list + /// still has. + pub(crate) list: Option<(Vec, f64)>, + /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which + /// the run takes as its own ([`super::files::Setup::own`]). + pub(crate) grants: Option, +} + +/// The palettes of a session, and the events that wait for a run. +#[derive(Debug, Default)] +pub(crate) struct Palettes { + list: Vec, + waiting: VecDeque, + last_id: u64, + /// The event the run that starts next handles ([`Session::script_palette_start`]). + pub(crate) starting: Option, +} + +/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? +fn same_place(a: &UiEvent, b: &UiEvent) -> bool { + match (a, b) { + (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, + (UiEvent::Close, UiEvent::Close) => true, + _ => false, + } +} + +impl Palettes { + fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> { + self.list.iter_mut().find(|p| p.id == id && p.engine == engine) + } + + /// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`. → its id. + pub(crate) fn show( + &mut self, + id: Option, + engine: &str, + (file, grants): (Option, String), + dialog: ScriptUiDialog, + ) -> std::result::Result { + if let Some(p) = id.and_then(|id| self.find(id, engine)) { + p.dialog = dialog; + p.visible = true; + return Ok(p.id); + } + if self.list.len() >= MAX_PALETTES { + return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first")); + } + self.last_id += 1; + self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants }); + Ok(self.last_id) + } + + /// The palette's controls as a handler or `add()` left them. → false when it is closed. + pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.dialog = dialog; + true + } + + /// `hide()`. → false when it is closed. + pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool { + let Some(p) = self.find(id, engine) else { return false }; + p.visible = false; + self.waiting.retain(|q| q.palette != id); + true + } + + /// `close()`, once `onClose` allowed it. → false when it was closed already. + pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { + let before = self.list.len(); + self.list.retain(|p| !(p.id == id && p.engine == engine)); + self.waiting.retain(|q| q.palette != id); + self.list.len() != before + } + + /// Closes the palettes of the engines `keep` does not keep, with their waiting events. + fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) { + self.list.retain(|p| keep(&p.engine)); + let open: Vec = self.list.iter().map(|p| p.id).collect(); + self.waiting.retain(|q| open.contains(&q.palette)); + } + + /// Puts `event` for the shown palette `id` in line, once it is checked against the palette. + fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result { + let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) }; + if !p.visible { + return Err(format!("the script palette {id} is hidden")); + } + let event = scriptui::check_event(&p.dialog, event)?; + let list = match &event { + UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), + _ => None, + }; + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + slot.event = event; + slot.list = list; + return Ok(Waiting::Merged); + } + if self.waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); + } + self.waiting.push_back(Queued { palette: id, event, list, grants: None }); + Ok(Waiting::Added) + } + + /// The oldest waiting event whose palette is still shown, and that palette. + fn next(&mut self) -> Option<(ScriptPalette, Queued)> { + while let Some(q) = self.waiting.pop_front() { + if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { + return Some((p.clone(), q)); + } + } + None + } +} + +/// `name` in a `#targetengine` line, quoted with a quote it does not hold. +fn engine_line(name: &str) -> String { + let quote = if name.contains('"') { '\'' } else { '"' }; + format!("#targetengine {quote}{name}{quote}") +} + +/// The source of a palette's handler run: its engine, and the call that hands the event to the +/// palette, which takes it from the run's host. +fn handler_source(engine: &str) -> String { + format!("{}\nWindow.__vcPaletteEvent();\n", engine_line(engine)) +} + +/// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s +/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's +/// number, or a list's item index or null). +pub(crate) fn parse_event( + dialog: &ScriptUiDialog, + event: &str, + control: Option<&Value>, + value: Option<&Value>, +) -> std::result::Result { + if event == "close" { + if control.is_some() || value.is_some() { + return Err("a close takes no `control` and no `value`".into()); + } + return Ok(UiEvent::Close); + } + let id = match control { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?, + _ => return Err("`control` must be a control's index, name or text".into()), + }; + let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + let event = match (event, value) { + ("click", None) => UiEvent::Click(id), + ("click", Some(_)) => return Err("a click takes no `value`".into()), + ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + ("change", Some(Value::Number(v))) if list => match v.as_u64() { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), + ("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)), + ("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()), + _ => return Err("`event` must be click, change or close".into()), + }; + scriptui::check_event(dialog, event) +} + +/// A palette as `script.palettes` lists it. +pub(crate) fn palette_json(p: &ScriptPalette) -> Value { + let controls: Vec = p + .dialog + .nodes + .iter() + .enumerate() + .skip(1) + .map(|(i, n)| { + let mut c = Map::new(); + c.insert("index".into(), json!(i)); + c.insert("kind".into(), json!(kind_id(n.kind))); + c.insert("name".into(), json!(n.name)); + c.insert("text".into(), json!(n.text)); + c.insert("enabled".into(), json!(n.enabled)); + c.insert("visible".into(), json!(n.visible)); + match n.kind { + UiKind::CheckBox | UiKind::RadioButton => { + c.insert("value".into(), json!(n.checked)); + } + UiKind::Slider | UiKind::ProgressBar => { + c.insert("value".into(), json!(n.value)); + } + UiKind::DropDownList | UiKind::ListBox => { + c.insert("items".into(), json!(n.items)); + c.insert("selection".into(), json!(n.selection)); + } + _ => {} + } + Value::Object(c) + }) + .collect(); + json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls}) +} + +fn kind_id(kind: UiKind) -> &'static str { + match kind { + UiKind::Dialog => "palette", + UiKind::Group => "group", + UiKind::Panel => "panel", + UiKind::StaticText => "statictext", + UiKind::EditText => "edittext", + UiKind::Button => "button", + UiKind::CheckBox => "checkbox", + UiKind::RadioButton => "radiobutton", + UiKind::DropDownList => "dropdownlist", + UiKind::ListBox => "listbox", + UiKind::Slider => "slider", + UiKind::ProgressBar => "progressbar", + } +} + +impl Session { + /// The palettes the named engines' runs showed and have not closed, shown or hidden, in the + /// order they were first shown. + pub fn script_palettes(&self) -> &[ScriptPalette] { + &self.script_palettes.list + } + + /// How many palette events wait for a run. + pub fn script_palette_events_waiting(&self) -> usize { + self.script_palettes.waiting.len() + } + + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going + /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it + /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. + pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result { + self.script_palettes.wait(id, event) + } + + /// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a + /// run is going or no event waits; otherwise the run's name, or the error that ended it before + /// it began. + pub fn script_palette_start(&mut self) -> Option> { + // An event waits while a drag or an undo group is open, which a run cannot start in. + if self.script_running() || self.script_palettes.waiting.is_empty() || self.settle_for_script().is_err() { + return None; + } + let (palette, mut queued) = self.script_palettes.next()?; + queued.grants = Some(palette.grants.clone()); + let title = palette.dialog.title(); + let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() }; + let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = super::Request { + name, + name_given: true, + file: palette.file.clone(), + checked_real: None, + source: handler_source(&palette.engine), + args: Map::new(), + fuel: super::DEFAULT_FUEL, + locale, + answers: Vec::new(), + }; + self.script_palettes.starting = Some(queued); + let r = self.script_start(request); + self.script_palettes.starting = None; + Some(r) + } + + /// Closes the palettes whose engine the session no longer keeps. + pub(crate) fn keep_engines_palettes(&mut self) { + let names: Vec = self.script_engines().into_iter().map(|(name, ..)| name).collect(); + self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e)); + } + + /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, + /// the one just given last. → that one's report. + pub(crate) fn script_palette_run_waiting(&mut self) -> Result { + let mut last = Err(EngineError::Other("no script palette event waits".into())); + while let Some(started) = self.script_palette_start() { + last = started.and_then(|_| self.script_run_to_end()); + } + last + } +} diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 2f77fbb5b8..8ca7154e47 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -1,6 +1,9 @@ //! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run //! gives when it shows one, checked and laid out here before the app draws it, and the events the -//! person or `script.run`'s `answers` give back. +//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described +//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions +//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here +//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other. //! //! A description lists the dialog first and each control after the container that holds it. It is //! refused with an error thrown at `show()` when a control's container comes after it or is not a @@ -136,6 +139,9 @@ pub struct UiNode { pub max: f64, pub items: Vec, pub selection: Option, + /// How many times a list's items were added or removed, which a palette's waiting change of + /// the list is checked against. + pub revision: f64, pub multiline: bool, pub readonly: bool, pub rect: UiRect, @@ -497,6 +503,7 @@ pub fn parse(d: &Data) -> Result { max, items, selection, + revision: number(field(f, "revision")).unwrap_or(0.0), multiline: flag("multiline"), readonly: flag("readonly"), rect: UiRect::default(), @@ -668,7 +675,89 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result /// Adds `Window` to the realm, for the run `link` holds. pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { - realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) + realm.define_script_ui(vec![ + ("open".into(), function(link, open)), + ("wait".into(), function(link, wait)), + ("end".into(), function(link, end)), + ("palette".into(), function(link, palette)), + ("paletteShow".into(), function(link, palette_show)), + ("paletteUpdate".into(), function(link, palette_update)), + ("paletteHide".into(), function(link, palette_hide)), + ("paletteClose".into(), function(link, palette_close)), + ("paletteEvent".into(), function(link, palette_event)), + ]) +} + +/// The error of `new Window("palette")` in a run without a named engine. +pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script"; + +/// The named engine of the run, for a palette. +fn palette_engine(host: &Host) -> Result<&str, HostError> { + host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into())) +} + +/// A palette's id as a script holds it: a whole number from 1, or none. +fn palette_id(d: Option<&Data>) -> Option { + match d { + Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64), + _ => None, + } +} + +/// `new Window("palette")`: refused in a run without a named engine. +fn palette(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Undefined) +} + +/// A palette's `show()`, with its description and its id (none the first time). → its id. +fn palette_show(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + let id = palette_id(args.get(1)); + let grants = host.disk.borrow().own().to_string(); + let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants), dialog); + shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) +} + +/// The palette `id`'s controls as a handler or `add()` left them. +fn palette_update(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let dialog = described(host, args)?; + if let Some(id) = palette_id(args.get(1)) { + host.session.borrow_mut().script_palettes.update(id, &engine, dialog); + } + Ok(Data::Undefined) +} + +fn palette_hide(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.hide(id, &engine); + } + Ok(Data::Undefined) +} + +fn palette_close(host: &Host, args: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + if let Some(id) = palette_id(args.first()) { + host.session.borrow_mut().script_palettes.close(id, &engine); + } + Ok(Data::Undefined) +} + +/// The event a palette handler's run is for, once: `{palette, event, id, value, items}`, as `show()` +/// takes a dialog's event with the palette's id added, and for a list's change the items the +/// palette showed; `null` for any other run, and after the first call. +fn palette_event(host: &Host, _: &[Data]) -> Result { + let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; + let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; + fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if let Some((items, revision)) = queued.list { + fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); + fields.push(("revision".into(), Data::Number(revision))); + } + Ok(Data::Object(fields)) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..55395c0d01 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -170,6 +170,7 @@ impl Session { script_frames: false, script_high_water: Default::default(), script_in_run: false, + script_palettes: Default::default(), script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 58addcd9fe..c655eea8b5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_palettes; mod script_run; mod script_scriptui; mod scripts; diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs new file mode 100644 index 0000000000..006f022627 --- /dev/null +++ b/crates/engine/src/tests/script_palettes.rs @@ -0,0 +1,312 @@ +//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run +//! and run one at a time after it, the events that take a waiting one's place, `close()` and the +//! close box, the engine's end, and the limits. + +use serde_json::{Value, json}; + +use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; +use crate::script::scriptui::PALETTE_NEEDS_ENGINE; +use crate::script::{DialogAnswer, UiEvent, Waiting}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "p.js"})) +} + +/// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() || s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Runs `source` in the app to its end. +fn run_in_app(s: &mut Session, source: &str) -> Value { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + pump(s).expect("the run ended").unwrap() +} + +/// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and +/// adds a rectangle, and a field (control 2). +const TOOLS: &str = "#targetengine tools\n\ + var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + var field = p.add('edittext', undefined, ''); \ + go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ + field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; + +fn only_palette(s: &Session) -> u64 { + let list = s.script_palettes(); + assert_eq!(list.len(), 1, "{list:?}"); + list[0].id +} + +#[test] +fn show_returns_at_once_and_the_palette_stays_after_the_run() { + let mut s = one_doc(); + let r = run(&mut s, TOOLS).unwrap(); + assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); + let id = only_palette(&s); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["engine"], "tools"); + assert_eq!(listed["palettes"][0]["title"], "Tools"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); + assert_eq!(changed["log"], json!(["change abc"])); +} + +#[test] +fn a_later_run_in_the_engine_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); + assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); +} + +#[test] +fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { + let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("picked")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let data = base.join("picked/data.txt"); + std::fs::write(&data, "hello").unwrap(); + let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); + let main = base.join("main/main.jsx"); + let source = format!( + "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ + var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ + b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" + ); + std::fs::write(&main, source).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + break; + } + assert!(s.script_pump().is_none(), "the run waits at its file dialog"); + } + let picked = data.to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["hello"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); +} + +#[test] +fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); + assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); +} + +#[test] +fn a_palette_click_during_another_run_runs_after_it() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); + assert!(pump(&mut s).is_none(), "the run waits at its confirm"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); + assert_eq!(s.script_palette_events_waiting(), 1); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn double_clicks_while_queued_run_once() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged)); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); + assert_eq!(s.script_palette_events_waiting(), 2); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + let mut logs = vec![]; + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); +} + +#[test] +fn a_palette_from_a_script_without_a_named_engine_is_refused() { + let mut s = one_doc(); + for source in ["", "#targetengine main\n"] { + let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); + assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); + } + assert!(s.script_palettes().is_empty()); +} + +#[test] +fn close_fires_on_close_and_frees_the_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); + let id = only_palette(&s); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert_eq!(closed["log"], json!(["closing"])); + assert!(s.script_palettes().is_empty(), "the close box freed the palette"); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); + + run(&mut s, TOOLS).unwrap(); + let r = + run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); + run(&mut s, "#targetengine tools\np.close();").unwrap(); + assert!(s.script_palettes().is_empty(), "close() freed the palette"); +} + +#[test] +fn dropping_the_engine_closes_its_palettes() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); + let id = s.script_palettes()[0].id; + s.script_palette_event(id, UiEvent::Click(1)).unwrap(); + s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); + let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); + assert_eq!(left, ["other"]); + assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); + assert!(s.script_palette_start().is_none()); +} + +#[test] +fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { + let mut s = one_doc(); + let before = s.documents()[0].history.undo.len(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("broken"), "{e}"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler's rectangle was rolled back"); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_dialog_in_a_handler_throws_in_the_app() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ + try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(only_palette(&s), id, "the palette stays open"); +} + +#[test] +fn palettes_and_waiting_events_have_limits() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", + ) + .unwrap(); + assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); + s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); + assert!(s.script_palettes().is_empty()); + + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + for c in 1..=MAX_WAITING { + assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); + } + let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); + assert!(e.contains("this one was not kept"), "{e}"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 800b0f35df..08badaae56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,7 +44,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), - ("Window.", "length prototype"), + ("Window.", "__vcPaletteEvent length prototype"), ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ad8d10acce..117ae759b6 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -502,6 +502,16 @@ impl Realm { } } + /// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as + /// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the + /// run's fuel, and what it throws ends the run. + pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { + match crate::scriptui::refresh(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index f2f8a33b2c..52f42ee49c 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2,10 +2,11 @@ //! describes it, whose //! drawing a host does ([`crate::Realm::define_script_ui`]). //! -//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A -//! window of type `palette` or `window`, and a resource specification in place of the type, throw -//! an `Error` that says they are not available yet. `add(type[, bounds, text, properties])` adds a -//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`, and +//! `new Window("palette", ...)` a palette, once the host's `palette` allows it. A window of type +//! `window`, and a resource specification in place of the type, throw an `Error` that says they are +//! not available yet. `add(type[, bounds, text, properties])` adds a +//! control to a dialog, a palette, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet. A @@ -24,6 +25,15 @@ //! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether //! it ended normally. //! +//! A palette's `show()` gives the host's `paletteShow` its description and its id (none the first +//! time), which gives back the id, then runs `onShow` and returns `undefined` without waiting. +//! `hide()` gives `paletteHide` the id, and `close()` runs `onClose`, and unless it returns `false` +//! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps +//! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the +//! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a +//! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown +//! palette does the same for that palette, so the host's list of its controls stays in step. +//! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] @@ -66,8 +76,14 @@ const CLOSING: &str = "__vcClosing"; const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const PALETTE_ID: &str = "__vcPaletteId"; +const IN_CLOSE: &str = "__vcInClose"; +/// How many times a list's items were added or removed: a palette's waiting change of the list is +/// for the items it had then. +const REVISION: &str = "__vcRevision"; -/// The objects of `Window`, kept by the realm, and the dialog that is showing. +/// The objects of `Window`, kept by the realm, the dialog that is showing, and the palettes the +/// host shows, shown or hidden. #[derive(Clone, Debug)] pub(crate) struct Classes { window_proto: ObjId, @@ -78,6 +94,7 @@ pub(crate) struct Classes { selection_get: ObjId, selection_set: ObjId, showing: Option, + palettes: Vec, } impl Classes { @@ -85,10 +102,21 @@ impl Classes { pub(crate) fn objects(&self) -> Vec { let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; all.extend(self.showing); + all.extend(self.palettes.iter().copied()); all } } +/// Is `kind` a window's: a dialog's or a palette's? +fn is_window(kind: &str) -> bool { + kind == "dialog" || kind == "palette" +} + +/// Does `kind` hold controls? +fn is_container(kind: &str) -> bool { + is_window(kind) || kind == "group" || kind == "panel" +} + /// Forgets the dialog that was showing when a run ended where it was. pub(crate) fn end_run(i: &mut Interp) { if let Some(c) = i.script_ui.as_mut() { @@ -254,7 +282,7 @@ fn new_element( set_open(i, o, "bounds", bounds.clone())?; } set_open(i, o, "layout", Value::Object(layout))?; - if matches!(kind, "dialog" | "group" | "panel") { + if is_container(kind) { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; let children = list(i, &[], true)?; @@ -274,16 +302,24 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult if ty.to_lowercase() != "item" { return Err(error(i, "add: a list holds only items")); } - return add_item(i, o, &arg(args, 1)); + let item = add_item(i, o, &arg(args, 1))?; + if let Some(win) = object_slot(i, o, WINDOW)? { + i.rooted(std::slice::from_ref(&item), |i| update_palette(i, win))?; + } + return Ok(item); } - if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + if !is_container(&kind) { return Err(error(i, &format!("add: a {kind} holds no controls"))); } if ty.contains('{') { @@ -401,6 +441,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult append(i, o, KIDS, "children", Value::Object(c))?; set_slot(i, win, COUNT, Value::Number(count + 1.0))?; set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?; + // The host's copy of a shown palette keeps each control's place in the list, which events + // name it by. + update_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -433,6 +476,7 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; append(i, o, ITEMS, "items", Value::Object(item))?; + bump_revision(i, o)?; Ok(Value::Object(item)) }) }) @@ -530,9 +574,16 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult<()> { + let r = number_slot(i, o, REVISION)?; + set_slot(i, o, REVISION, Value::Number(r + 1.0)) +} + fn kids_of(i: &Interp, o: ObjId) -> JsResult> { match object_slot(i, o, KIDS)? { Some(a) => list_values(i, a), @@ -597,29 +648,158 @@ fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { Ok(Value::Undefined) } -fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { +/// `this` as a window, and whether it is a palette. +fn window_of(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, bool)> { match kind_of(i, this)? { - Some((o, kind)) if kind == "dialog" => Ok(o), + Some((o, kind)) if is_window(&kind) => Ok((o, kind == "palette")), _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), } } -/// `close([result])`: closes the dialog that is showing once the running handler returns. +/// `close([result])`: closes the dialog that is showing once the running handler returns, or the +/// palette at once. fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let o = dialog_of(i, &this, "close")?; + let (o, palette) = window_of(i, &this, "close")?; let result = match arg(args, 0) { Value::Undefined => 0.0, v => number_arg(i, &v, "close: the result")?, }; - if classes(i)?.showing == Some(o) { + if palette { + close_palette(i, o)?; + } else if classes(i)?.showing == Some(o) { set_slot(i, o, CLOSING, Value::Number(result))?; } Ok(Value::Undefined) } -/// `hide()`: closes the dialog that is showing with the result 0. +/// `hide()`: closes the dialog that is showing with the result 0, or hides the palette, which a +/// later `show()` shows again as it was. fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - close(i, this, &[], false) + let (o, palette) = window_of(i, &this, "hide")?; + if !palette { + return close(i, this, &[], false); + } + if let Value::Number(id) = slot(i, o, PALETTE_ID)? { + let f = host_fn(i, "paletteHide")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(Value::Undefined) +} + +fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { + if let Some(c) = i.script_ui.as_mut() { + f(&mut c.palettes); + } +} + +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its +/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + if slot(i, win, IN_CLOSE)?.truthy() { + return Ok(()); + } + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let allowed = may_close(i, win); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + if !allowed? { + return Ok(()); + } + if let Value::Number(id) = slot(i, win, PALETTE_ID)? { + set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_palettes(i, |p| p.retain(|o| *o != win)); + let f = host_fn(i, "paletteClose")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(()) +} + +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. +fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + let (desc, ..) = describe(i, win)?; + let f = host_fn(i, "paletteUpdate")?; + i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; + Ok(()) +} + +/// Gives the host the controls of every palette it shows, after a handler may have changed them. +fn update_palettes(i: &mut Interp) -> JsResult<()> { + for win in classes(i)?.palettes { + update_palette(i, win)?; + } + Ok(()) +} + +/// Gives the host the controls of every palette the realm keeps, as a run left them +/// ([`crate::Realm::refresh_script_ui`]); nothing without palettes. +pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { + return Ok(()); + } + update_palettes(i) +} + +/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` +/// returns `undefined` without waiting. +fn show_palette(i: &mut Interp, win: ObjId) -> JsResult { + let (desc, ..) = describe(i, win)?; + let id = slot(i, win, PALETTE_ID)?; + let f = host_fn(i, "paletteShow")?; + Ok(Pause { host: f, args: vec![desc, id], keep: vec![Value::Object(win)], resume: palette_shown, failed: None }) +} + +fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its palette".into())) }; + let Value::Number(_) = id else { return Err(Abrupt::Internal("the host gave the palette no id".into())) }; + set_slot(i, win, PALETTE_ID, id)?; + if !classes(i)?.palettes.contains(&win) { + set_palettes(i, |p| p.push(win)); + } + handler(i, win, "onShow")?; + update_palette(i, win)?; + Ok(Value::Undefined) +} + +/// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the +/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and +/// gives the host every palette's controls afterward. An event for a palette that has closed does +/// nothing. +fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let f = host_fn(i, "paletteEvent")?; + let answer = i.call(&f, &Value::Undefined, &[])?; + let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; + let mark = i.temp_roots.len(); + i.temp_roots.push(answer.clone()); + let r = (|| { + let id = slot(i, ev, "palette")?; + let palettes = classes(i)?.palettes; + let mut win = None; + for p in palettes { + if matches!((slot(i, p, PALETTE_ID)?, &id), (Value::Number(a), Value::Number(b)) if a == *b) { + win = Some(p); + } + } + let Some(win) = win else { return Ok(Value::Undefined) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + close_palette(i, win)?; + } else { + let (_, nodes, ..) = describe(i, win)?; + i.temp_roots.push(Value::Object(nodes)); + let count = list_values(i, nodes)?.len(); + if !matches!(slot(i, ev, "id")?, Value::Number(n) if n >= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } + take_event(i, win, nodes, ev, &event, None)?; + } + update_palettes(i)?; + Ok(Value::Undefined) + })(); + i.temp_roots.truncate(mark); + r } fn host_fn(i: &mut Interp, name: &str) -> JsResult { @@ -633,9 +813,13 @@ fn set_showing(i: &mut Interp, showing: Option) { } } -/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). On a +/// palette: [`show_palette`]. fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { - let win = dialog_of(i, &this, "show")?; + let (win, palette) = window_of(i, &this, "show")?; + if palette { + return show_palette(i, win); + } match classes(i)?.showing { Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), @@ -745,75 +929,123 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { } return next(i, win); } - let id = match slot(i, ev, "id")? { - Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, - _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), - }; - let nodes = list_values(i, nodes)?; - let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { - return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); - }; - let value = slot(i, ev, "value")?; - match event.as_str() { - "click" => { - if kind == "checkbox" { - let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); - i.put(c, key("value"), Value::Bool(!on), true)?; - } else if kind == "radiobutton" { - let parent = object_slot(i, c, PARENT)?; - for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { - if !same(&other, &Value::Object(c)) - && let Some((o, k)) = kind_of(i, &other)? - && k == "radiobutton" - { - i.put(o, key("value"), Value::Bool(false), true)?; - } - } - i.put(c, key("value"), Value::Bool(true), true)?; - } - if handler(i, c, "onClick")?.is_none() && kind == "button" { - let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); - if is(2) { - set_slot(i, win, CLOSING, Value::Number(1.0))?; - } else if is(3) { - set_slot(i, win, CLOSING, Value::Number(2.0))?; - } - } - } - "change" => { - match kind.as_str() { - "edittext" => { - i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; - } - "slider" => { - i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; - } - _ => { - let n = match value { - Value::Number(n) => n, - _ => -1.0, - }; - // The index is into the items the person saw. - let shown = match arg(keep, 4).as_object() { - Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), - None => Value::Undefined, - }; - if !same(&slot(i, c, ITEMS)?, &shown) { - return Err(error(i, "show: a list's items changed before the person's choice was taken")); - } - set_slot(i, c, SELECTION, Value::Number(n))?; - } - } - handler(i, c, "onChange")?; - } - _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), - } + take_event(i, win, nodes, ev, &event, Some(keep))?; next(i, win) }) } +/// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of +/// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks +/// to close it with 1 when it is the default element and 2 when it is the cancel element, which +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event { + "click" => { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + let parent = object_slot(i, c, PARENT)?; + for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { + if !same(&other, &Value::Object(c)) + && let Some((o, k)) = kind_of(i, &other)? + && k == "radiobutton" + { + i.put(o, key("value"), Value::Bool(false), true)?; + } + } + i.put(c, key("value"), Value::Bool(true), true)?; + } + if handler(i, c, "onClick")?.is_none() + && kind == "button" + && let Some(keep) = keep + { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + handler(i, c, "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + handler(i, c, "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + match keep { + // The index is into the items the person saw. + Some(keep) => { + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + } + // A palette's list may have changed while the event waited: the host gives + // the items the person saw and the list's revision then. + None => { + let revised = match slot(i, ev, "revision")? { + Value::Number(r) => r != number_slot(i, c, REVISION)?, + _ => false, + }; + if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + return Err(error(i, "a palette's list changed before the person's choice was taken")); + } + } + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + Ok(()) +} + +/// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True +/// when `seen` is not an array. +fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { + let Some(seen) = seen.as_object() else { return Ok(true) }; + let seen = list_values(i, seen)?; + let items = items_of(i, c)?; + if seen.len() != items.len() { + return Ok(false); + } + i.rooted(&items, |i| { + for (item, want) in items.iter().zip(&seen) { + let Some(item) = item.as_object() else { return Ok(false) }; + let text = get(i, item, "text")?; + if i.to_str(&text)?.to_rust_string() != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + } + Ok(true) + }) +} + fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { let s = i.to_str(v)?; let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; @@ -963,8 +1195,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; let text = text_of(i, &text_v, "a control's text")?; + // A palette is described as a dialog is; the host knows which it shows. + let shown_kind = if kind == "palette" { "dialog" } else { kind.as_str() }; let mut d: Vec<(String, Data)> = vec![ - ("kind".into(), Data::String(kind.clone())), + ("kind".into(), Data::String(shown_kind.to_string())), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), @@ -981,7 +1215,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); - if matches!(kind.as_str(), "dialog" | "group" | "panel") { + if is_container(kind) { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); let ac = get_kept(i, o, "alignChildren")?; @@ -1026,6 +1260,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("items".into(), Data::Array(texts))); let sel = selection_index(i, o)?.filter(|n| *n < items.len()); d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + d.push(("revision".into(), Data::Number(number_slot(i, o, REVISION)?))); } _ => {} } @@ -1079,9 +1314,21 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul i.temp_roots.push(Value::Object(selection_get)); let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; i.temp_roots.push(Value::Object(selection_set)); - i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + i.script_ui = Some(Classes { + window_proto, + control_proto, + item_proto, + layout, + host, + selection_get, + selection_set, + showing: None, + palettes: Vec::new(), + }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; + let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; + i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; method(i, window_proto, "add", add, 4)?; method(i, window_proto, "findElement", find_element, 1)?; method(i, window_proto, "close", close, 1)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7d0d8376a3..76a70d331d 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -232,7 +232,8 @@ fn a_dialog_can_be_shown_again_after_it_closed() { #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ - ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('window')", "Window: a window of type window is not available yet; use dialog or palette"), + ("new Window('palette')", "Window: this host shows no palettes"), ("new Window('dialog { b: Button {} }')", "Window: resource specifications are not available yet; build the dialog with add()"), ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), @@ -373,6 +374,129 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() { assert_eq!(seen.borrow().ends, vec![(1.0, true)]); } +/// What a palette host was asked: each call's name and its palette id (0 for none). +type Calls = Rc>>; + +/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives +/// the events in `events`, in order, then `null`. +fn palette_realm(events: Vec) -> (Realm, Calls) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let calls: Calls = Rc::default(); + let events = Rc::new(RefCell::new(VecDeque::from(events))); + let id_of = |args: &[Data], at: usize| match args.get(at) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + let record = |name: &'static str, at: usize| -> HostFunction { + let c = calls.clone(); + Rc::new(move |args| { + c.borrow_mut().push((name.to_string(), id_of(&args, at))); + Ok(Data::Undefined) + }) + }; + let c = calls.clone(); + let show: HostFunction = Rc::new(move |args| { + let given = id_of(&args, 1); + let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 }; + c.borrow_mut().push(("paletteShow".into(), id)); + Ok(Data::Number(id)) + }); + let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); + let items = vec![ + ("open".into(), HostItem::Function(none.clone())), + ("wait".into(), HostItem::Function(none.clone())), + ("end".into(), HostItem::Function(none)), + ("palette".into(), HostItem::Function(record("palette", 0))), + ("paletteShow".into(), HostItem::Function(show)), + ("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))), + ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), + ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), + ("paletteEvent".into(), HostItem::Function(event)), + ]; + r.define_script_ui(items).unwrap(); + (r, calls) +} + +fn palette_event(palette: f64, event: Data) -> Data { + let Data::Object(mut fields) = event else { return Data::Null }; + fields.push(("palette".into(), Data::Number(palette))); + Data::Object(fields) +} + +fn names(calls: &Calls) -> Vec { + calls.borrow().iter().map(|(n, _)| n.clone()).collect() +} + +#[test] +fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]); + let made = r + .run( + "var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \ + var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \ + b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \ + t.onChange = function () { log.push('change ' + t.text); }; String(p.show())", + ) + .unwrap(); + assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting"); + assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); + assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event gives the host the new controls"); + assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); +} + +#[test] +fn closing_a_palette_runs_on_close_which_can_keep_it_open() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \ + var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_after_its_items_changed_throws() { + let seen = |index: f64| { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + // The two items the list was made with. + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) + }; + let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap(); + let message = "a palette's list changed before the person's choice was taken"; + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts"); + r.run("l.removeAll(); l.add('item', 'a');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "fewer items"); + r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(message.into()), "new items with the same texts"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); +} + +#[test] +fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap(); + let shows: Vec = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect(); + assert_eq!(shows, [1.0, 1.0, 1.0]); +} + #[test] fn findelement_items_and_selection_follow_the_list() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..9854310ff5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -179,7 +179,7 @@ features! { Reflection "reflection" HostOnly, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, - ScriptuiPalette "scriptui.palette" HostOnly, + ScriptuiPalette "scriptui.palette" Dialogs, ScriptuiWindow "scriptui.window" Dialogs, SelectTool "selectTool" HostOnly, Socket "socket" HostOnly, diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 2bd8c60fba..c0d626c998 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -119,8 +119,8 @@ pub enum Need { MenuCommands, /// Dialogs and windows of its own. Dialogs, - /// Features only the reference app has (palettes, messages to other apps, network - /// connections, native code, E4X, actions). + /// Features only the reference app has (messages to other apps, network connections, native + /// code, E4X, actions). HostOnly, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..8b216bcc48 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1369,6 +1369,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { assert_eq!(notify(five, &Limits::default()).0, Vec::::new()); } +#[test] +fn palettes_need_dialogs() { + let r = report("#targetengine tools\nvar w = new Window('palette');\nw.show();\n"); + assert_eq!(r.needs, [Need::Language, Need::Dialogs]); +} + #[test] fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..bd2bba2159 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -368,6 +368,11 @@ impl VectorcraftApp { crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::poll(self, ctx); + // A palette event whose run starts on the next frame. While a run goes on, the block below + // asks for its frames, and a run that waits for the person goes on at their next input. + if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint(); + } if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() @@ -638,6 +643,7 @@ impl VectorcraftApp { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); panels::learn::locate::tidy(self, &ctx); crate::doc_windows::show(self, &ctx); + crate::script_palettes::show(self, &ctx); dialogs::show(self, &ctx); updates_ui::show(self, &ctx); export_progress::show(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 158a86ea5b..9aea178b9a 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -215,7 +215,13 @@ pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { /// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place from `origin`. → the /// event it gives. -fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt): (usize, &UiNode, &str), default: bool) -> Option { +pub(crate) fn control( + ui: &mut egui::Ui, + d: &mut Dialog, + origin: egui::Pos2, + (i, n, prompt): (usize, &UiNode, &str), + default: bool, +) -> Option { let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); let t = Tokens::get(ui.ctx()); let mut event = None; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9d442848ce..51a518f798 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6582,6 +6582,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg `answers` must be a list of answers `answers` ha de ser una llista de respostes @msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes +@msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat @msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB @msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` @msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ee8b68af7d..9457178baf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8986,6 +8986,7 @@ breakText Glyphs Glyfy @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` musí uvádět indexy kotevních bodů (0, 1, 2…), ne {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí +@msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována @msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB @msg `answers` must be a list of answers `answers` musí být seznam odpovědí @msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cc03e6ef1b..1ef0d2169d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -225,6 +225,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name} @msg `answers` must be a list of answers `answers` skal være en liste med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt @msg `answers` is larger than 1 MiB `answers` er større end 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e92726501f..935a135c4b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8426,6 +8426,7 @@ breakText Glyphs Glyphen @msg `align` must be a string `align` muss ein String sein @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 12d3aba3c5..aa30a34709 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2779,6 +2779,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων @msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις +@msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε @msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB @msg `answers[{i}]` {e} το `answers[{i}]` {e} @msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c404d6ed6e..5cc8d86fdf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5054,6 +5054,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg `answers` must be a list of answers `answers` debe ser una lista de respuestas @msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas +@msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado @msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB @msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` @msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2ae421c004..1205c1dc9d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5295,6 +5295,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg `answers` must be a list of answers `answers` on oltava vastausten luettelo @msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty @msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB @msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` @msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index aa2a24c90d..dbdca9ca76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8853,6 +8853,7 @@ breakText Glyphs Glyphes @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé @msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio @msg `answers` must be a list of answers `answers` doit être une liste de réponses @msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5bdc231564..8c5e1f5602 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7728,6 +7728,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए @msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं +@msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई @msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af96effe62..6f7ce5a4ca 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8857,6 +8857,7 @@ breakText Glyphs Glifák @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz +@msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva @msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál @msg `answers` must be a list of answers `answers`: válaszok listája kell @msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 87d73912db..25e340bec0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -133,6 +133,7 @@ @msg {name}: `answers` has no answer left for this dialog {name}: `answers` tidak memiliki jawaban tersisa untuk dialog ini @msg `answers` must be a list of answers `answers` harus berupa daftar jawaban @msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan @msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB @msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` @msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5aab7c3e3d..ea73cf2b91 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8467,6 +8467,7 @@ breakText Glyphs Glifi @msg `align` must be a string `align` deve essere una stringa @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ef0740a8bb..0b73565e9a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7293,6 +7293,7 @@ axis Y Axis Y 軸 @msg `align` must be a string `align` には文字列を指定してください @msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています +@msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした @msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています @msg `answers` must be a list of answers `answers` には回答のリストを指定してください @msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e7223c60c8..541d871302 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -176,6 +176,7 @@ @msg `answer` for this {kind} dialog must be one of: {_1} დიალოგისთვის (ტიპი: {kind}) `answer` უნდა იყოს ერთ-ერთი: {_1} @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს +@msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა @msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია @msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია @msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e40e7055a2..07bde95166 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8625,6 +8625,7 @@ breakText Glyphs 글리프 @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`에는 앵커 인덱스(0, 1, 2…)를 나열해야 합니다: {v} @msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다 @msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다 @msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다 @msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d52992f4a9..9287dd44e3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6493,6 +6493,7 @@ imageTrace Outline Contour @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` moet ankerindexen bevatten (0, 1, 2…), niet {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden +@msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard @msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB @msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn @msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1a2148f0e1..fd7342da72 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8670,6 +8670,7 @@ breakText Glyphs Glify @msg `align` must be a string `align` musi być ciągiem znaków @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi +@msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 82cdb0a2b2..4aa2697468 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9039,6 +9039,7 @@ swatch Yellow Green Verde-amarelado @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` deve listar índices de pontos de ancoragem (0, 1, 2…), não {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas +@msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 6f351f1d76..ac74d5747a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5076,6 +5076,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg `answers` must be a list of answers `answers` должен быть списком ответов @msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено @msg `answers` is larger than 1 MiB `answers` больше 1 МиБ @msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` @msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 532e1ade50..dc74ea16ce 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4951,6 +4951,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg `answers` must be a list of answers `answers` måste vara en lista med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte @msg `answers` is larger than 1 MiB `answers` är större än 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index daba147a6d..955a2662d8 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5760,6 +5760,39 @@ fn f(p: &Value) -> Result<()> { assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]); } +/// The status a ScriptUI palette's click shows when the line of waiting events is full is +/// translated in every language that translates every message, with the count kept. +#[test] +fn script_palette_line_full_is_translated() { + use serde_json::json; + use vectorcraft_engine::script::UiEvent; + let template = "{MAX_WAITING} script palette events already wait; this one was not kept"; + assert!(message_literals().contains(template)); + let mut s = vectorcraft_engine::Session::new(); + let source = "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();"; + s.execute("script.run", &json!({"source": source})).unwrap(); + let id = s.script_palettes()[0].id; + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": "confirm('Go?');"})).unwrap()["running"], true); + while s.script_dialog().is_none() { + assert!(s.script_pump().is_none(), "the run waits at its confirm"); + } + let mut full = None; + for c in 1..=70 { + if let Err(e) = s.script_palette_event(id, UiEvent::Click(c)) { + full = Some(e); + break; + } + } + let full = full.expect("the line filled"); + assert_eq!(full, template.replace("{MAX_WAITING}", "64")); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &full); + assert_ne!(shown, full, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// `script.run`'s refusals of `answers`, the list's own, an answer's at its index and the refusal /// of `answers` in the app, are translated in every language that translates every message, with /// the index, the counts and the code names kept. The command's error stays in English. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 22568734be..109ef0345a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7669,6 +7669,7 @@ axis Y Axis Y ekseni @msg `align` must be a string `align` bir dize olmalıdır @msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var +@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı @msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük @msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır @msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1c44123d26..20e6a222ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8626,6 +8626,7 @@ breakText Glyphs Гліфи @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` має містити індекси опорних точок (0, 1, 2…), а не {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей +@msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2758865931..173c74895c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5575,6 +5575,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời @msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời +@msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại @msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB @msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` @msg must have exactly `kind` and `value` phải có đúng `kind` và `value` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index dac4499a58..129b2fff68 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8676,6 +8676,7 @@ breakText Glyphs 字形 @msg `align` must be a string `align` 必须是字符串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bf6ee14a81..b11084d879 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8621,6 +8621,7 @@ breakText Glyphs 字符 @msg `align` must be a string `align` 必須是字串 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個 +@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留 @msg `answers` is larger than 1 MiB `answers` 大於 1 MiB @msg `answers` must be a list of answers `answers` 必須是答案清單 @msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..5bbfae206c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -70,6 +70,7 @@ pub mod print; pub mod recovery; pub mod render_worker; pub mod screen_color; +pub mod script_palettes; pub mod script_runs; pub mod scripts_menu; mod scrub; diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs new file mode 100644 index 0000000000..125adf0365 --- /dev/null +++ b/crates/ui-egui/src/script_palettes.rs @@ -0,0 +1,93 @@ +//! The ScriptUI palettes a script shows with `new Window("palette")` in a named engine +//! ([`vectorcraft_engine::script::palettes`]): each shown palette is a window beside the documents +//! that stays open after the run, with the controls the engine laid out. A click, a change or the +//! window's close box waits in the session's line and runs as a script run of its own once no run +//! is going ([`crate::script_runs::poll`]); the palette stays usable while a run goes on, and its +//! events wait for it. A palette does not take the keyboard focus when it opens or changes. An edit +//! field's text is given when it loses the focus, at Enter in a one-line field, or before a click +//! or a close; a text the script would refuse stays in its field with the error in the status bar. + +use serde_json::json; +use vectorcraft_engine::script::{ScriptPalette, UiEvent}; + +use crate::VectorcraftApp; +use crate::dialogs::script_window; +use crate::state::Dialog; + +/// The largest part of a palette's content shown at once; a larger palette scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +/// Where the text typed in a palette's fields is kept between frames. +fn drafts_id(id: u64) -> egui::Id { + egui::Id::unique(("script-palette-drafts", id)) +} + +/// Draws each shown palette, and puts the events the person gives in line. +pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); + for p in shown { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut events = Vec::new(); + let mut open = true; + let title = p.dialog.title(); + let title = if title.is_empty() { tl!("Script Alert").to_string() } else { vectorcraft_engine::script::dialogs::shown_text(title, false) }; + let (width, height) = p.dialog.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::Window::new(title).id(egui::Id::unique(("script-palette", p.id))).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { + let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + for (i, n) in p.dialog.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = script_window::control(ui, &mut drafts, area.min, (i, n, script_window::prompt_of(&p.dialog, i)), false) + { + events.push(e); + } + } + }); + }); + if !open { + events.push(UiEvent::Close); + } + drafted(app, &p, &mut drafts, &mut events); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + give(app, ctx, p.id, events); + } +} + +/// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in +/// `events`. A text the script would refuse stays in its field with its error in the status bar, +/// and a click or a close waits for the person to fix it. +pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut Dialog, events: &mut Vec) { + if let Some(e) = script_window::keep_refused_texts(&p.dialog, drafts, events) { + app.status(e); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close)) + && let Err(e) = script_window::commit_drafts(&p.dialog, drafts, events) + { + events.retain(|e| !matches!(e, UiEvent::Click(_) | UiEvent::Close)); + app.status(e); + } +} + +/// Puts the events the person gave the palette `id` in line, or shows why one was refused. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { + for e in events { + match app.session.script_palette_event(id, e) { + // The next frame starts its run. + Ok(_) => ctx.request_repaint(), + Err(e) => app.status(e), + } + } +} + +/// Starts the run of the oldest waiting palette event when no run is going. → whether one started. +pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { + match app.session.script_palette_start() { + None => false, + Some(Ok(_)) => true, + Some(Err(e)) => { + crate::script_runs::failed(app, e.to_string()); + false + } + } +} diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 27e74d820e..c40c4a2f6e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -2,7 +2,8 @@ //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with //! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, -//! waits for the person's answer. +//! waits for the person's answer. With no run going, the oldest event a ScriptUI palette waits +//! with starts its run ([`crate::script_palettes`]). use serde_json::json; @@ -13,7 +14,8 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(app); - if !app.session.script_running() { + // With no run going, a waiting palette event starts its run. + if !app.session.script_running() && !crate::script_palettes::start_next(app) { return; } script_run::settle_close(app); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index ac934f6d18..2c79788097 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -42,6 +42,7 @@ mod screenmode; mod screenshots; mod script_check; mod script_dialogs; +mod script_palettes; mod script_run; mod script_window; mod scripts_menu; diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs new file mode 100644 index 0000000000..113c501162 --- /dev/null +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -0,0 +1,109 @@ +//! A script's ScriptUI palette in the app: it stays open after the run, and a click on it waits in +//! line and starts its handler's run on the next frame. + +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_window; +use crate::state::Dialog; +use crate::{VectorcraftApp, menus, script_palettes, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn run_to_end(app: &mut VectorcraftApp) { + for _ in 0..10_000 { + if !app.session.script_running() { + return; + } + script_runs::poll(app); + } + panic!("the script did not end"); +} + +/// One headless frame in which `f` runs. → whether the frame asked for the next one at once. +fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) +} + +#[test] +fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + for _ in 0..3 { + frame(&ctx, |_| {}); + } + assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); + assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "the click asks for the next frame"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + +#[test] +fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "vc.log(confirm('Go?'));", "name": "d.js"})).unwrap().unwrap(); + for _ in 0..10_000 { + if app.session.script_dialog().is_some() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_dialog().is_some(), "the run waits at its confirm"); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames while the run waits for its answer"); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); +} + +#[test] +fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { + let mut app = app(); + let source = "#targetengine texts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log(t.text); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let p = app.session.script_palettes()[0].clone(); + let long = "x".repeat(16 * 1024 + 1); + let mut drafts = Dialog::new(script_window::KIND, json!({})); + drafts.fields.insert("text1".into(), json!(long)); + let mut events = vec![UiEvent::Change(1, UiValue::Text(long.clone())), UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert!(events.is_empty(), "neither the long text nor the click is given: {events:?}"); + assert_eq!(drafts.fields.get("text1"), Some(&json!(long)), "the refused text stays in its field"); + drafts.fields.insert("text1".into(), json!("fine")); + let mut events = vec![UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("fine".into())), UiEvent::Click(2)]); + assert!(!drafts.fields.contains_key("text1"), "the text is given once"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 951edebb05..36f0993663 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2547,9 +2547,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's - document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions - and `selectTool`). + document model), `files`, `menuCommands`, `dialogs` (dialogs and palettes), and `hostOnly` (features only the + reference app has: BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, + reflection, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. @@ -2902,8 +2902,9 @@ https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it: -- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) or a - resource string throws an `Error` that says it is not available yet. +- `new Window("dialog"[, title, bounds, properties])` makes a dialog, and `new Window("palette", ...)` a palette, + which is described after the dialogs below. The type `window` and a resource string throw an `Error` that says + it is not available yet. - `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, @@ -2967,6 +2968,45 @@ an error in a handler ends `show()`, with steps it did not use. vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' ``` +A palette is a ScriptUI window that stays open beside the documents after the script that showed it has ended, and +that the person can use while they work (the window-object help page above). A script builds it like a dialog, with +the same controls, handlers and limits: + +- A palette needs a named engine, which keeps its controls and handlers after the run. In a script without + `#targetengine`, or with `#targetengine main`, `new Window("palette")` throws an `Error` that says to add a + `#targetengine` line (see [Script engines](#script-engines)). +- `show()` runs `onShow` and returns `undefined` at once. `hide()` hides the palette, and `show()` shows it again. + `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. + A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, + and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each + run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. + A handler's run reads and writes the files the person allowed the script that first showed the palette. +- Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's + engine, with its own report and, when it changes a document, its own Run Script undo step. While another run + goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a + newer click on the same control, change of the same control or close of the same palette takes its place, + with the newer value. A list's change ends its run with an error when a script added or removed the list's + items after the person chose, even if the list again holds the same texts. A text typed in a palette's field + that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits + until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and + leaves the palette open. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a + handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. +- A session keeps at most 16 palettes, shown or hidden, past which `show()` throws a `RangeError`, and at most 64 + waiting events, past which an event is refused. Hiding or closing a palette drops its waiting events. These + limits are VectorCraft's own. + +`script.palettes {}` lists the palettes in the order they were first shown: `{palettes: [{id, engine, title, +visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, selection?}]}], waiting, limit: 16, +waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a +`change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's +index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in +`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one, +or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}' +``` + The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A script reads files with them: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 939047032e..c8f4bb0095 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,7 +1066,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_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`. - - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. + - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). From a8174f2ae5cfd1dbe30f7a8867fa3922f6ac59da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:33:43 -0800 Subject: [PATCH 028/533] JavaScript: spreading a string counts the strings it makes for its characters Spreading a string makes a new one- or two-unit string for each code point, but the spread held only the bytes of each element's property, so a long string could make the host build every character string past the heap limit in one instruction. Each element now holds the bytes of its string as well, and the strings stay in the heap estimate once the array holds them. --- crates/js/src/es2015_tests.rs | 40 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 12 ++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index d717ba2090..f7b704b210 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -513,6 +513,46 @@ fn spreading_a_rope_counts_its_flattened_length_first() { assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel"); } +#[test] +fn spreading_a_string_counts_the_string_it_makes_for_each_character() { + // Each of the 16,384 elements is a property and a one-character string of its own. The + // smaller heap has room for the properties alone but not for the strings as well, so the + // spread stops with the heap limit after about 83% of the characters, before the fuel for + // 90% of them runs out. The larger heap holds the array, its keys and the strings. + const N: usize = 16_384; + let property = crate::heap::PROP_BYTES; + let string = crate::heap::string_bytes(1); + let setup = "var s = 'x'; for (var i = 0; i < 14; i++) s = s + s; s[0]; 0"; + let cases = [(property + string / 2, N * 9 / 10, Err(LimitKind::Heap)), (2 * (property + string) + 8, N * 2, Ok(N as f64))]; + for (per_element, fuel, expected) in cases { + let mut r = es(); + assert_eq!(r.run(setup), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let heap_bytes = r.interp().heap.bytes + N * per_element; + r.set_limits(Limits { heap_bytes, fuel: fuel as u64, ..Limits::default() }); + match (r.run("var a = [...s]; a.length"), expected) { + (Ok(JsValue::Number(n)), Ok(m)) if n == m => {} + (Err(e), Err(kind)) if e.kind == RunErrorKind::Limit(kind) => {} + (result, expected) => panic!("{per_element} bytes for each element: {result:?}, expected {expected:?}"), + } + } +} + +#[test] +fn the_strings_a_string_spread_makes_stay_counted_while_the_array_holds_them() { + const N: u32 = 4096; + let mut r = es(); + assert_eq!(r.run("var s = 'x'; for (var i = 0; i < 12; i++) s = s + s; s[0]; 0"), Ok(JsValue::Number(0.0))); + r.interp().collect_garbage(); + let before = r.interp().heap.bytes; + assert_eq!(r.run("var a = [...s]; a.length"), Ok(JsValue::Number(f64::from(N)))); + // Takes the bytes the spread held while it ran off the estimate. + r.interp().reserve_heap(0).unwrap(); + let element = |i: u32| crate::heap::PROP_BYTES + crate::heap::string_bytes(i.to_string().len()) + crate::heap::string_bytes(1); + let least = before + (0..N).map(element).sum::(); + assert!(r.interp().heap.bytes >= least, "{} < {least}", r.interp().heap.bytes); +} + #[test] fn a_rest_parameter_checks_the_heap_before_its_array_is_made() { // The 20,000 arguments fit in the room left over, and the rest array of them does not, so diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0b75dab588..286302d021 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2404,8 +2404,9 @@ impl Interp { /// index (holes read as `undefined`), with its length read again before each one as its /// iterator reads it, a string's or a `String` object's characters by code point, and an /// object with a `length` by index. Any other value is a `TypeError`. Each element takes a - /// unit of fuel, and a concatenated string's flattened copy is counted against the heap before - /// it is made. + /// unit of fuel, a concatenated string's flattened copy is counted against the heap before + /// it is made, and so is each string a string's spread makes for its characters, while the + /// spread runs and after the array holds it. fn op_array_spread(&mut self) -> JsResult<()> { let v = self.peek(0)?; let Value::Object(a) = self.peek(1)? else { return internal("spread into something that is not an array") }; @@ -2417,6 +2418,8 @@ impl Interp { }, _ => None, }; + // The bytes of the strings a string's spread makes, which the array keeps once it holds them. + let mut made = 0usize; let items: Vec = match boxed.as_ref().unwrap_or(&v) { Value::String(s) => { let units = crate::string_builtins::flat_charged(self, s)?; @@ -2425,9 +2428,11 @@ impl Interp { let mut i = 0; while let Some(&u) = units.get(i) { self.use_fuel()?; - held.add(self, PROP_BYTES)?; let pair = (0xD800..0xDC00).contains(&u) && units.get(i + 1).is_some_and(|n| (0xDC00..0xE000).contains(n)); let len = if pair { 2 } else { 1 }; + // Each element is a new string of its own as well as a property. + held.add(self, PROP_BYTES + string_bytes(len))?; + made = made.saturating_add(string_bytes(len)); out.push(Value::String(Str::from_units(units.get(i..i + len).unwrap_or_default().to_vec()))); i += len; } @@ -2490,6 +2495,7 @@ impl Interp { for (i, item) in (start..end).zip(items) { self.define(a, index_key(i), Prop::Data { value: item, flags: OPEN })?; } + self.heap.bytes = self.heap.bytes.saturating_add(made); self.pop().map(drop) } From 41625f2c88c3b9d9d481e9182448a6ef80588886 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:36:31 -0800 Subject: [PATCH 029/533] Scripts: controlBounds takes in direction points, and a profile is read from the file checked - controlBounds gives the visible bounds together with the anchors and direction points of the paths in the object, taking the members its geometric bounds take. A blend, envelope or other live object gives its visible bounds. Before, every object gave its visible bounds. - A New Document profile is opened once. After the open, the roots in force must still allow its path and the path must still name the plain file that was opened, so a file put in its place between the checks and the open is not read. - Array methods visit every index of an object of a host class with an indexer, also past 4,096 indices. Before, a long range was listed from the object's properties, and its indexed elements were skipped. - An assignment to a document's selection checks each item against a set of the ids taken, so a long list is not searched once for each item. - A test shows that a failed selection assignment leaves the selection within the same run, and the link test removes its files when an assertion fails. --- crates/engine/src/cmd/newdoc.rs | 21 ++++++++++++++- crates/engine/src/cmd/recovery.rs | 2 +- crates/engine/src/script/dom.rs | 37 +++++++++++++++++++++++++-- crates/engine/src/store.rs | 10 ++++++++ crates/engine/src/tests/newdoc.rs | 13 +++++++--- crates/engine/src/tests/script_dom.rs | 30 ++++++++++++++++++++++ crates/js/src/builtins/array.rs | 4 ++- crates/js/src/host_tests.rs | 21 +++++++++++++++ docs/mcp.md | 3 ++- 9 files changed, 132 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 073de104cc..617a4f8b16 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -996,8 +996,15 @@ impl Session { Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), _ => {} } + // The file is opened once and checked after it is open: the roots in force must allow + // its path then, and the path must still name the plain file that was opened, so a file + // put in its place between the checks and the open is not read. + let opened = std::fs::File::open(&path).map_err(|e| e.to_string())?; crate::file_access::check_read(&file).map_err(denied)?; - crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + if !opened.metadata().is_ok_and(|m| m.is_file()) || !still_names(&opened, &path) { + return Err("not a plain file".to_string()); + } + crate::store::read_open_capped(opened, MAX_PROFILE_BYTES).map(Some) })?; let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs @@ -1010,6 +1017,18 @@ impl Session { } } +/// Whether `path` still names `file` ([`super::recovery::FolderStore::still_named`]). +#[cfg(not(target_arch = "wasm32"))] +fn still_names(file: &std::fs::File, path: &std::path::Path) -> bool { + super::recovery::FolderStore::still_named(file, path) +} + +/// The web build has no profile folder. +#[cfg(target_arch = "wasm32")] +fn still_names(_: &std::fs::File, _: &std::path::Path) -> bool { + false +} + /// The shipped profile of category `name`: the defaults, as a document of the category's first /// preset. fn shipped_profile(s: &Session, name: &str) -> Document { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 193e86b600..7719496fac 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -420,7 +420,7 @@ impl FolderStore { /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on /// Windows they must be the same file (volume serial number and file index); elsewhere `path` /// must exist. When either file can't be read, it does not. - fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { + pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { #[cfg(unix)] { use std::os::unix::fs::MetadataExt as _; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9063f4d868..feb87f1a4c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1155,6 +1155,8 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + // The ids taken so far, so a long list is not searched once for each item. + let mut taken: std::collections::HashSet = std::collections::HashSet::with_capacity(list.len()); for d in list { let item = item_of(h, d)?; let ok = item.doc.uid == doc.uid @@ -1163,7 +1165,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { bounds(h, a, true) } +/// The visible bounds with the control points of the item's paths, or of the paths in it. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let controls = st.doc.node(item.id).and_then(control_points_box); + let r = vectorcraft_geom::union_opt(st.doc.bounds_of(&[item.id], true), controls) + .ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok((r, frame(st)?)) + })?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + +/// The box of the anchors and direction points of every path in `n`, taking the members its +/// geometric bounds take: a clipping group or layer counts its clipping path only, a group or +/// compound path its editing children (not a Shaper group's source shapes), and a layer its +/// visible ones. +fn control_points_box(n: &vectorcraft_doc::Node) -> Option { + let union = |nodes: &mut dyn Iterator>| { + nodes.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, control_points_box(c))) + }; + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => union(&mut children.iter().take(1)), + NodeKind::Layer { .. } => union(&mut n.editing_children().iter().filter(|c| c.visible)), + NodeKind::Group { .. } | NodeKind::Compound { .. } => union(&mut n.editing_children().iter()), + // A live object (a blend, envelope, repeat and the like) draws other paths than the ones it + // holds, so it adds its visible bounds only. + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1908,7 +1941,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9c555d82f7..784a7ae2d8 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -179,6 +179,16 @@ pub(crate) fn read_capped(path: &Path, max: u64) -> Result, String> { Ok(bytes) } +/// [`read_capped`] of a file already open. +pub(crate) fn read_open_capped(file: std::fs::File, max: u64) -> Result, String> { + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err(too_large(max)); + } + Ok(bytes) +} + /// The first `max + 1` bytes of `path` at most, so that a result longer than `max` shows the file is /// over its cap. fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 11330bac10..a5718deb1b 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -909,17 +909,24 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { #[cfg(unix)] #[test] fn a_profile_that_is_a_link_is_not_followed() { + /// Removes the folder and the file when dropped, also when an assertion fails. + struct Removed(std::path::PathBuf, std::path::PathBuf); + impl Drop for Removed { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + let _ = std::fs::remove_file(&self.1); + } + } let (mut s, dir) = 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 _removed = Removed(dir.clone(), outside.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); 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 bb283e7dab..6d64b4a123 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,18 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +#[test] +fn control_bounds_take_in_the_direction_points() { + let (mut s, _, _) = doc(); + // An arch whose top is at y 40 and whose direction points are at y 20. + let id = s.execute("path.create", &json!({"d": "M100 100C100 20 200 20 200 100"})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap_or(f64::NAN); + assert!(top(&out[0]) < 265.0, "{out:?}"); + assert_eq!(top(&out[1]), 280.0, "{out:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -229,6 +241,24 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +#[test] +fn a_failed_selection_assignment_leaves_the_selection_within_the_run() { + let (mut s, _, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + // The run goes on after the failed assignment, so nothing it ends with puts the selection back. + let c = rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, open, shut;\ + for (var i = 0; i < p.length; i++) { if (p[i].locked) shut = p[i]; else if (!p[i].selected) open = p[i]; }\ + try { d.selection = [open, shut]; vc.log('assigned'); } catch (e) { vc.log(String(e.message).indexOf('Cannot select') >= 0); }\ + vc.log([d.selection.length, open.selected, d.selection[0].locked]);", + ); + assert_eq!(out, vec![json!(true), json!([1, false, false])]); + assert_eq!(s.active().unwrap().selection.objects, vec![c]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..3b6806ea20 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -113,7 +113,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 has elements that are not properties, so each + // index of its 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)?); diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..be840c6ddc 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -676,6 +676,27 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn array_methods_visit_every_element_of_a_long_host_list() { + let mut r = realm(10_000_000); + // `list[i]` is `i` below 5,000, past the span the array methods visit without listing. + let index: HostFunction = Rc::new(|a| { + let i = a.get(1).and_then(|i| if let Data::Number(n) = i { Some(*n) } else { None }); + Ok(i.filter(|n| *n < 5_000.0).map_or(Data::Undefined, Data::Number)) + }); + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let members = vec![("length".to_string(), HostMember::Get(length))]; + let class = HostClass { name: "List".into(), parent: None, members, index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap(); + let out = r + .run( + "var n = 0; Array.prototype.forEach.call(list, function () { n++; });\ + [Array.prototype.indexOf.call(list, 4999), Array.prototype.lastIndexOf.call(list, 0), n].join()", + ) + .unwrap(); + assert_eq!(out, JsValue::String("4999,0,5000".into())); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/docs/mcp.md b/docs/mcp.md index aa65793760..07ca7284f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2655,7 +2655,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds together with the anchors and direction points of the paths in the object; a clipping group counts + its clipping path only, and a blend, envelope or other live object gives its visible bounds), `editable`, `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 From 9beb3bb5f9c579eee1ba86e45e5dfa5ff9207090 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:57:39 -0800 Subject: [PATCH 030/533] Scripts: a ScriptUI dialog shown in place of another gives its first field the focus A dialog a script shows right after closing the open one now counts as newly opened: the control used in the first dialog gives up the keyboard focus, and the first editable field of the new dialog takes it. ScriptUI edit fields now take the first-field focus like the app's other dialogs. --- crates/ui-egui/src/dialogs.rs | 23 +++++++--- crates/ui-egui/src/dialogs/script_window.rs | 12 +++++- crates/ui-egui/src/tests/script_window.rs | 47 +++++++++++++++++++++ 3 files changed, 76 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6b59f7bd88..20f57ad04f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -929,7 +929,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { revolve_gizmo::clear(ctx); app.ui.dialog_file = None; ctx.data_mut(|m| { - m.remove::(shown_id); + m.remove::<(String, Option)>(shown_id); m.remove::(focus_id); }); return; @@ -937,13 +937,26 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !revolve_gizmo::active(&d) { revolve_gizmo::clear(ctx); } - let focus_first = ctx.data_mut(|m| { - if m.get_temp::(shown_id).as_deref() != Some(d.kind.as_str()) { - m.insert_temp(shown_id, d.kind.clone()); + // A ScriptUI dialog that a script showed in place of the one open is a new dialog too. + let shown_as = (d.kind.clone(), script_window::shown_of(&d)); + let (focus_first, replaced) = ctx.data_mut(|m| { + let before = m.get_temp::<(String, Option)>(shown_id); + let replaced = before.as_ref().is_some_and(|b| b.0 == shown_as.0 && *b != shown_as); + if before.as_ref() != Some(&shown_as) { + m.insert_temp(shown_id, shown_as); m.insert_temp(focus_id, true); } - m.get_temp::(focus_id).unwrap_or(false) + (m.get_temp::(focus_id).unwrap_or(false), replaced) }); + // It draws in the same window with the same control ids, so the control used in the dialog + // before it gives up the keyboard focus. + if replaced { + ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + } // Not in the frame of a click (the one on the menu item that opened it): egui takes the focus // from a field the click missed, so the field takes it a frame later (#1367). let clicked = ctx.input(|i| i.pointer.any_click()); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 9aea178b9a..a1ea69f620 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -54,6 +54,11 @@ pub(crate) fn is_open_for(d: &Dialog, w: &ScriptUiDialog) -> bool { d.kind == KIND && d.fields.get(SHOWN_KEY).and_then(Value::as_u64) == Some(w.shown) } +/// Which `show()` of the run `d` is open for, when it is a ScriptUI dialog. +pub(crate) fn shown_of(d: &Dialog) -> Option { + if d.kind == KIND { d.fields.get(SHOWN_KEY).and_then(Value::as_u64) } else { None } +} + fn heading(d: &Dialog) -> String { let title = d.str("title"); if title.is_empty() { tl!("Script Alert").into() } else { vectorcraft_engine::script::dialogs::shown_text(&title, false) } @@ -357,8 +362,13 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (usize, &UiNode, &str)) -> Option { let key = draft_key(i); let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); + let id = ui.make_persistent_id("edit"); + // The first field that can be typed in takes the keyboard focus as the dialog opens. + if !n.readonly { + widgets::take_dialog_focus(ui, id, &text); + } let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; - let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); + let r = ui.put(rect, field.id(id).interactive(!n.readonly).desired_width(rect.width())); name_for_screen_readers(ui, &r, n, prompt); if r.changed() { d.fields.insert(key.clone(), json!(text)); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 2e2cd186ca..5a0b7aeeac 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -210,6 +210,53 @@ fn a_second_dialog_replaces_the_first() { assert_eq!(log(&app), json!([[1, "y"]])); } +/// Draws one frame of the dialog layer for screen readers. → The role of the control with the +/// keyboard focus. +fn focused_role(app: &mut VectorcraftApp) -> Option { + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update?; + update.nodes.iter().find(|(id, _)| *id == update.focus).map(|(_, n)| n.role()) +} + +#[test] +fn a_dialog_shown_in_place_of_another_gives_its_first_field_the_focus() { + use egui::accesskit::Role; + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('statictext', undefined, 'Name'); b.add('button', undefined, 'Back'); \ + b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log(b.show());", + ); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the first dialog's field has the focus, not {role:?}"); + let mut on_button = false; + for _ in 0..4 { + frame(&mut app, vec![key(egui::Key::Tab)]); + on_button = focused_role(&mut app) == Some(Role::Button); + if on_button { + break; + } + } + assert!(on_button, "Tab puts the focus on the first dialog's button"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "B"); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the second dialog's field has the focus, not {role:?}"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn a_dialog_function_after_show_opens_its_own_dialog() { let mut app = app(); From dc569257e1515b9bd36b167d858bbcf2fdb4afe4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:58:38 -0800 Subject: [PATCH 031/533] Scripts: a Copy the run puts back leaves the clipboard as it was edit.copy, artboard.copy and artboard.cut now have the clipboard saved before them, as edit.cut and command.batch do. Before, a Copy whose result could not reach the script was put back without its clipboard, so the copy stayed on the clipboard and the run reported copied: true. --- crates/engine/src/script/mod.rs | 2 +- crates/engine/src/tests/script_dom_prefs.rs | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 61f4f9d2ba..a6162b8b3c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -630,7 +630,7 @@ impl World { /// The commands that can change the clipboard and still fail, or still be put back because their /// result cannot reach the script, and that do not put it back themselves. The clipboard can hold /// a great deal, so a savepoint copies it only for these. -const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "command.batch", "edit.cut"]; +const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "artboard.copy", "artboard.cut", "command.batch", "edit.copy", "edit.cut"]; /// The commands that remove a document's undo history, or the document: a savepoint keeps a whole /// copy of the histories for these. Any other command that removes or changes a step under the diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index bac0981ccc..dc2bacdff0 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -521,11 +521,13 @@ fn a_copy_or_cut_the_run_puts_back_is_not_reported() { let r = run( &mut s, "try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\ - try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }", + try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }\ + try { vc.run('edit.copy'); } catch (e) { vc.log(e.name); }\ + try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }", ); crate::script::TEST_RESULT_BYTES.with(|b| b.set(None)); let r = r.unwrap(); - assert_eq!(r["log"], json!(["RangeError", "RangeError"]), "{r}"); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError"]), "{r}"); assert_eq!(r.get("copied"), None, "{r}"); assert_eq!(s.copies, copies); assert!(s.clipboard_copied); From 64e7f4e893fecf67946a9fa753073b46e76bb6df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:36:23 -0800 Subject: [PATCH 032/533] Scripts: move leaves art on a locked artboard, and a move to the same place runs nothing - move() on an object on a locked artboard throws "cannot move objects on a locked artboard", as remove() refuses to delete such an object. - move() works out the index node.move puts the object at, with art kept below the layer's ruler guides, before it decides whether the object moves. Before, moving the topmost art to the top of a layer with ruler guides ran node.move and added an undo step that changed nothing. --- crates/engine/src/script/dom.rs | 13 ++++++++++- crates/engine/src/tests/script_dom.rs | 31 +++++++++++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index feb87f1a4c..73f00536a2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1588,6 +1588,9 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { /// The error of `remove()` and `removeAll()` for an object on a locked artboard. const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +/// The error of `move` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD_MOVE: &str = "cannot move objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; @@ -1670,6 +1673,9 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } + if !copy && d.on_locked_artboard(item.id) { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD_MOVE}: {}", item.id.0))); + } Ok(Destination { parent, beside, how }) }) } @@ -1696,7 +1702,12 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + let at = if clips { at.max(1) } else { at }; + // The index `node.move` puts the object at: art stays below the ruler guides. + let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let rest: Vec> = + d.children(Some(to.parent)).map(|c| c.iter().filter(|n| n.id != id).cloned().collect()).unwrap_or_default(); + Ok::<_, HostError>(crate::doc::Node::insert_index(&rest, at, node)) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6d64b4a123..a1ea190b57 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1051,6 +1051,37 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it +/// is runs no command, also in a layer whose ruler guides are above its art. +#[test] +fn move_refuses_art_on_a_locked_artboard_and_skips_a_move_to_the_same_place() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + let steps = undo_steps(&s); + // The topmost art, moved to the top of its layer, stays where it is. + log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, top = p[0];\ + for (var i = 1; i < p.length; i++) { if (p[i].zOrderPosition > top.zOrderPosition) top = p[i]; }\ + top.move(top.parent);", + ); + assert_eq!(undo_steps(&s), steps, "a move to the same place adds no step"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let order = |s: &Session| format!("{:?}", (s.active().unwrap().doc.position(a), s.active().unwrap().doc.position(b))); + let before = order(&s); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);"); + assert!(e.contains("cannot move objects on a locked artboard"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1].parent, ElementPlacement.PLACEATEND);"); + assert!(e.contains("cannot move objects on a locked artboard"), "{e}"); + assert_eq!(order(&s), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 07ca7284f5..c480155de3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2662,7 +2662,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `edit.duplicate` and then `node.move` on the copy. 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 + directly below it. `move` on an object on a locked artboard throws `cannot move objects on a locked artboard`, and a + move that leaves the object where it is runs no command. An object of another document throws `Cross-document + placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws From d814cb77f3cf3431b6b8ac50a34d927459777a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:09:54 -0800 Subject: [PATCH 033/533] Scripts: palette events and typed texts stay with their control when a run adds controls A click or change that waits for a palette's run now keeps where its control sits in the palette, and a text typed in a palette's field keeps where its field sits, so both reach the same control after a run adds controls before it. A waiting event whose control is gone is dropped. ScriptUiDialog::place_of and control_at move to the engine so the palette queue and the dialog's queued events use the same rule. --- crates/engine/src/script/palettes.rs | 45 ++++++++++++++------ crates/engine/src/script/scriptui.rs | 27 ++++++++++++ crates/engine/src/tests/script_palettes.rs | 21 ++++++++++ crates/ui-egui/src/dialogs/script_window.rs | 46 +++++---------------- crates/ui-egui/src/script_palettes.rs | 18 +++++++- crates/ui-egui/src/tests/script_palettes.rs | 23 +++++++++++ docs/mcp.md | 7 ++-- 7 files changed, 133 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index d6ff578f29..5da1b6e888 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -61,6 +61,10 @@ pub enum Waiting { pub(crate) struct Queued { pub(crate) palette: u64, pub(crate) event: UiEvent, + /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), + /// by which the event finds its control again when a run adds controls before it; empty for a + /// close. + place: Vec, /// For a list's change, the list's items as the palette showed them when the event was given and /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list /// still has. @@ -80,12 +84,21 @@ pub(crate) struct Palettes { pub(crate) starting: Option, } -/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? -fn same_place(a: &UiEvent, b: &UiEvent) -> bool { - match (a, b) { - (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, - (UiEvent::Close, UiEvent::Close) => true, - _ => false, +/// Does `event`, for the control at `place`, share the waiting `q`'s place in line: a click on the +/// same control, a change of it, or a close? +fn same_place(q: &Queued, event: &UiEvent, place: &[usize]) -> bool { + let same_kind = matches!( + (&q.event, event), + (UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close) + ); + same_kind && q.place == place +} + +/// The control of a click or a change. +fn control_of(event: &mut UiEvent) -> Option<&mut usize> { + match event { + UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c), + UiEvent::Close => None, } } @@ -151,12 +164,13 @@ impl Palettes { if !p.visible { return Err(format!("the script palette {id} is hidden")); } - let event = scriptui::check_event(&p.dialog, event)?; + let mut event = scriptui::check_event(&p.dialog, event)?; let list = match &event { UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)), _ => None, }; - if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + let place = control_of(&mut event).map_or_else(Vec::new, |c| p.dialog.place_of(*c)); + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, &place)) { slot.event = event; slot.list = list; return Ok(Waiting::Merged); @@ -164,16 +178,21 @@ impl Palettes { if self.waiting.len() >= MAX_WAITING { return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept")); } - self.waiting.push_back(Queued { palette: id, event, list, grants: None }); + self.waiting.push_back(Queued { palette: id, event, place, list, grants: None }); Ok(Waiting::Added) } - /// The oldest waiting event whose palette is still shown, and that palette. + /// The oldest waiting event whose palette is still shown, given to the control at its place in + /// the palette as the runs since left it, and that palette. An event whose control the palette + /// no longer has is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { - while let Some(q) = self.waiting.pop_front() { - if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { - return Some((p.clone(), q)); + while let Some(mut q) = self.waiting.pop_front() { + let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; + if let Some(c) = control_of(&mut q.event) { + let Some(at) = p.dialog.control_at(&q.place) else { continue }; + *c = at; } + return Some((p.clone(), q)); } None } diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 8ca7154e47..fd3bda32a4 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -201,6 +201,33 @@ impl ScriptUiDialog { }; by(true).or_else(|| by(false)) } + + /// Where control `i` sits: its position among its container's controls, after its container's + /// own position, and so on up to the dialog. `add` puts a new control after the others in its + /// container, so adding controls leaves the place of every other one as it was, while its index + /// in [`Self::nodes`] can move. Empty for the dialog and for an index it does not have. + pub fn place_of(&self, mut i: usize) -> Vec { + let mut place = Vec::new(); + while i > 0 { + let Some(n) = self.nodes.get(i) else { return Vec::new() }; + place.push(self.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); + if n.parent >= i { + return Vec::new(); + } + i = n.parent; + } + place.reverse(); + place + } + + /// The index of the control at `place` ([`Self::place_of`]), if the dialog has one there. + pub fn control_at(&self, place: &[usize]) -> Option { + let mut at = 0; + for &k in place { + at = self.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; + } + (at > 0).then_some(at) + } } /// A value a control takes in a change. diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 006f022627..9c4b7be294 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,27 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); + let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; + assert_eq!(run(&mut s, added).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2662e30d87..2c8f35365e 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -143,7 +143,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if let Value::Object(mut fields) = next { // The control the event was given to, found again in the dialog as the handlers that ran // since left it. - let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); + let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,36 +152,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } -/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). +/// The field of a queued event that holds where its control sits in the dialog +/// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; -/// Where control `i` sits in the dialog `w`: its position among its container's controls, after -/// its container's own position, and so on up to the dialog. `add` puts a new control after the -/// others in its container, so a handler that adds controls leaves the place of every other one -/// as it was, while its index in the dialog's list of elements can move. -fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { - let mut place = Vec::new(); - while i > 0 { - let Some(n) = w.nodes.get(i) else { return Vec::new() }; - place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); - if n.parent >= i { - return Vec::new(); - } - i = n.parent; - } - place.reverse(); - place -} - -/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. -fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { - let mut at = 0; - for &k in place { - at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; - } - (at > 0).then_some(at) -} - /// The field that holds the events the person gave in one frame that the script has not had yet; /// the script takes one event each time it waits. const QUEUE_KEY: &str = "queued"; @@ -245,14 +219,14 @@ fn draft_key(i: usize) -> String { format!("text{i}") } -/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) -/// in the dialog the text was typed in. +/// The field that holds, for each text typed in an edit field, where the field sat +/// ([`ScriptUiDialog::place_of`]) in the dialog the text was typed in. const DRAFT_PLACES_KEY: &str = "draftPlaces"; /// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. -fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { let places: serde_json::Map = - (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(w.place_of(i)))).collect(); if places.is_empty() { d.fields.remove(DRAFT_PLACES_KEY); } else { @@ -263,12 +237,12 @@ fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { /// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the /// dialog `w`, which moves when a handler adds controls before the field. A text whose field the /// dialog no longer has is dropped. -fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; let mut moved = Vec::new(); for (key, place) in places { let Some(text) = d.fields.remove(&key) else { continue }; - let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + let at = serde_json::from_value::>(place).ok().and_then(|p| w.control_at(&p)); if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { moved.push((draft_key(i), text)); } @@ -466,7 +440,7 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { }; let mut fields = json!({"event": name, "control": control, "value": value}); if let Some(i) = control { - fields[PLACE_KEY] = json!(place_of(w, i)); + fields[PLACE_KEY] = json!(w.place_of(i)); } fields } diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 125adf0365..ec2e8773dd 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -26,7 +26,7 @@ fn drafts_id(id: u64) -> egui::Id { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); for p in shown { - let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut drafts = drafts(ctx, &p); let mut events = Vec::new(); let mut open = true; let title = p.dialog.title(); @@ -49,11 +49,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); - ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + keep_drafts(ctx, &p, drafts); give(app, ctx, p.id, events); } } +/// The text typed in palette `p`'s fields, each under the index its field has in `p` now, which +/// moves when a run adds controls before the field. +pub(crate) fn drafts(ctx: &egui::Context, p: &ScriptPalette) -> Dialog { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + script_window::move_drafts(&p.dialog, &mut drafts); + drafts +} + +/// Keeps the text typed in palette `p`'s fields for the next frame, with where each field sits. +pub(crate) fn keep_drafts(ctx: &egui::Context, p: &ScriptPalette, mut drafts: Dialog) { + script_window::note_draft_places(&p.dialog, &mut drafts); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); +} + /// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in /// `events`. A text the script would refuse stays in its field with its error in the status bar, /// and a click or a close waits for the person to fix it. diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 113c501162..56cd162316 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,29 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[test] +fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { + let mut app = app(); + let source = "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var t = p.add('edittext', undefined, ''); p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let before = app.session.script_palettes()[0].clone(); + assert_eq!(before.dialog.nodes[3].kind, vectorcraft_engine::script::UiKind::EditText); + let ctx = egui::Context::default(); + let mut drafts = script_palettes::drafts(&ctx, &before); + drafts.fields.insert("text3".into(), json!("typed")); + script_palettes::keep_drafts(&ctx, &before, drafts); + let added = "#targetengine places\ng.add('button', undefined, 'Added');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": added, "name": "a.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let after = app.session.script_palettes()[0].clone(); + assert_eq!(after.dialog.nodes[4].kind, vectorcraft_engine::script::UiKind::EditText, "the added button comes before the field"); + let drafts = script_palettes::drafts(&ctx, &after); + assert_eq!(drafts.fields.get("text4"), Some(&json!("typed")), "{:?}", drafts.fields); + assert!(!drafts.fields.contains_key("text3")); +} + #[test] fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 1fd0e6d865..eee919e83c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2988,9 +2988,10 @@ the same controls, handlers and limits: engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, - with the newer value. A list's change ends its run with an error when a script added or removed the list's - items after the person chose, even if the list again holds the same texts. A text typed in a palette's field - that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits + with the newer value. A waiting click or change, and a text typed in a field, stay with their control when a + run adds controls before it; a waiting event whose control is gone is dropped. A list's change ends its run + with an error when a script added or removed the list's items after the person chose, even if the list again + holds the same texts. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and leaves the palette open. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. From ce0da4122fa1be126d6a2059a8a4139cb4929100 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:12:51 -0800 Subject: [PATCH 034/533] Scripts: a loop over groups and their page items lists each collection once The object model kept only the last list of art it built, so a loop that read doc.groupItems[i] and then that group's pageItems rebuilt the document-wide list of groups on every step. It now keeps the last four lists, each while its document is unchanged, and drops a document's older lists when it builds one for a newer version of that document. --- crates/engine/src/script/dom.rs | 6 +++--- crates/engine/src/script/dom/layers.rs | 29 ++++++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 24 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8123566196..a3d49ddd26 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -94,9 +94,9 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, - /// The last list of art one of [`layers`]' collections gave, kept while its document is - /// unchanged. - art: RefCell>, + /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently + /// used first, each kept while its document is unchanged. + art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, presets: RefCell>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index bd0046a4b4..b6c82ab1f1 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -572,17 +572,23 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { /// and the ids it listed then. pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); +/// How many lists of art [`super::State`] keeps at once. +pub(super) const ART_LISTS: usize = 4; + /// The objects of `kind` in `container` (directly), or in the whole document at any depth, in -/// paint order. The last list is kept while the document is unchanged, and each new one is charged -/// by the objects it looks at. +/// paint order. The last [`ART_LISTS`] lists are kept while their documents are unchanged, so a +/// loop over groups that reads each group's `pageItems` builds each list once. Each new list is +/// charged by the objects it looks at. fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { - if let Some((uid, doc, k, c, ids)) = &*h.dom.art.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - && *k == kind as u8 - && *c == container { - return Ok(ids.clone()); + let mut lists = h.dom.art.borrow_mut(); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.4.clone(); + lists.push(list); + return Ok(ids); + } } let ids: Vec = match container { None => { @@ -597,7 +603,12 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R } }; let ids = Rc::new(ids); - *h.dom.art.borrow_mut() = Some((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + let mut lists = h.dom.art.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); Ok(ids) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c44ecb4887..7597da4da3 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1250,6 +1250,30 @@ fn art_collections_follow_edits_between_reads() { assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); } +#[test] +fn a_loop_over_groups_and_their_items_lists_each_collection_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..5 { + let x = f64::from(i) * 20.0; + let (a, b) = (rect(&mut s, x, 0.0, 10.0, 10.0), rect(&mut s, x, 20.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + // Both scripts make the same calls. The first reads the groups and each group's items in + // turn; the second reads every group before any group's items, so it builds each list once. + let nested = "var gs = app.activeDocument.groupItems, n = 0;\ + for (var i = 0; i < gs.length; i++) { var p = gs[i].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let in_order = "var gs = app.activeDocument.groupItems, all = [], n = 0;\ + for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\ + for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap()); + assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); + assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); From fba91c32e6c780f50860be6994c81c21f163f0f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:24:16 -0800 Subject: [PATCH 035/533] Scripts: new layers and groups keep large ids, and runs keep the active artboard in step - layers.add, groupItems.add and artboards.add read the new object's id or index from the command's own result. Read from the script's copy, an id past 2^53 lost precision, and the new layer or group came back stale or null. - script.run's activeArtboards also lists a document whose active artboard has another index at the end of the run, because artboards were inserted, removed or reordered before it, so the view shows the same artboard. - After a run, the Artboard tool takes the view's active artboard again. The end of a run starts the tool afresh, which made artboard 0 the tool's active artboard whatever the view or the script had chosen. --- crates/engine/src/script/dom.rs | 7 ++++ crates/engine/src/script/dom/layers.rs | 46 +++++++++++++++----------- crates/engine/src/script/mod.rs | 4 +-- crates/engine/src/tests/script_dom.rs | 32 ++++++++++++++++++ crates/ui-egui/src/script_runs.rs | 9 ++++- crates/ui-egui/src/tests/script_run.rs | 18 ++++++++++ docs/mcp.md | 3 +- 7 files changed, 96 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a3d49ddd26..4c89cc5a4c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -99,10 +99,17 @@ pub(super) struct State { art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// Each open document's uid and the index of its active artboard when the run started. + pub(super) boards_at_start: Vec<(u64, usize)>, presets: RefCell>>, } impl State { + /// The state of a run that starts with the documents `docs` open. + pub(super) fn new(docs: &[DocState]) -> Self { + Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index b6c82ab1f1..108fe7f2e8 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -28,7 +28,9 @@ //! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global //! rulers, setting it moves the document's zero point. //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report -//! lists it in `activeArtboards` for the app to show. +//! lists it in `activeArtboards` for the app to show. The report also lists a document whose +//! active artboard has another index at the end of the run, because artboards were inserted, +//! removed or reordered before it. use std::rc::Rc; use std::sync::Arc; @@ -37,9 +39,9 @@ use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ - Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, doc_of, - doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, number, on_doc, - page_items, placement_of, property, text, typename, whole, with_doc, + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, + command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, + number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -86,13 +88,10 @@ fn type_error(what: &str) -> HostError { HostError::Type(format!("this is not a {what}")) } -/// The id a command's result gives under `key`. -fn result_id(d: &Data, key: &str) -> Option { - let Data::Object(o) = d else { return None }; - match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { - Some(Data::Number(n)) => whole(*n), - _ => None, - } +/// The whole number under `key` in a command's own result (not the script's copy, whose numbers +/// are exact only up to 2^53), such as the id of the object it made. +fn result_id(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64) } // ---- Layer ---- @@ -523,9 +522,9 @@ fn layers_add(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the layer is hidden or locked".into())); } } - let r = on_doc(h, doc.uid, true, |h| match parent { - None => command(h, "layer.new", &json!({"top": true})), - Some(p) => command(h, "layer.newSublayer", &json!({"parent": p.0})), + let (_, r) = on_doc(h, doc.uid, true, |h| match parent { + None => command_value(h, "layer.new", &json!({"top": true})), + Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), })?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; Ok(layer_ref(h, doc.uid, NodeId(id))) @@ -776,7 +775,7 @@ fn groups_add(h: &Host, a: &[Data]) -> Answer { } } let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); - let r = on_doc(h, doc.uid, true, |h| command(h, "object.newGroup", ¶ms))?; + let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; @@ -1194,7 +1193,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { } let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { - let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; let index = result_id(&made, "index") .and_then(|i| usize::try_from(i).ok()) .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; @@ -1258,9 +1257,18 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { /// The documents whose active artboard the run changed, as `script.run`'s report gives them: /// `[{document, artboard}]`, each an index, with the active artboard each document has at the end -/// of the run, or `None` when there are none. -pub(crate) fn active_artboards(moved: &[u64], docs: &[DocState]) -> Option { - let list: Vec = moved +/// of the run, or `None` when there are none. They are the documents in `moved`, then those whose +/// active artboard's index differs from the one in `start` (an artboard added, inserted, removed or +/// reordered before it). +pub(crate) fn active_artboards(moved: &[u64], start: &[(u64, usize)], docs: &[DocState]) -> Option { + let mut uids = moved.to_vec(); + for (uid, at) in start { + let shifted = docs.iter().find(|d| d.uid == *uid).is_some_and(|st| active_artboard(st) != *at); + if shifted && !uids.contains(uid) { + uids.push(*uid); + } + } + let list: Vec = uids .iter() .filter_map(|uid| { let document = docs.iter().position(|d| d.uid == *uid)?; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 34779c7b5e..725e566f12 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2064,7 +2064,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(self.documents()), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2290,7 +2290,7 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); - if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), self.documents()) { + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { report["activeArtboards"] = boards; } close_run(self, host, &mut report, console::Ending::Finished); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7597da4da3..f0862963b4 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1093,6 +1093,22 @@ fn layers_list_top_first_and_add_makes_the_new_layer_current() { assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); } +#[test] +fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The new ids, 2^53 + 1 and 2^53 + 3, are not exact as numbers. + for (id, source) in + [(1, "var l = app.activeDocument.layers.add(); l.name = 'made';"), (3, "var g = app.activeDocument.groupItems.add(); g.name = 'made';")] + { + let big = (1u64 << 53) + id; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + run(&mut s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("made"), "{source}"); + } +} + #[test] fn layer_properties_round_trip_and_reject_bad_values() { let (mut s, _, _) = doc(); @@ -1402,6 +1418,22 @@ fn the_report_gives_the_active_artboard_the_run_leaves() { assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); } +#[test] +fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.setActiveArtboardIndex(1);").unwrap(); + // An artboard inserted or removed before the active one moves it to another index. + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([2])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 2}])); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.remove(0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + // One added after it leaves its index as it was. + let r = run(&mut s, "app.activeDocument.artboards.add([1000, 300, 1100, 100]);").unwrap(); + assert!(r.get("activeArtboards").is_none(), "{r}"); +} + #[test] fn an_artboard_rectangle_stays_inside_the_canvas() { let (mut s, _, _) = doc(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index e8ae5d8a94..62e90ad97f 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -48,7 +48,9 @@ pub fn poll(app: &mut VectorcraftApp) { } /// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view -/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). The end of a run +/// starts the tool afresh, so the Artboard tool then takes the active document's active artboard as +/// its only selected one, as choosing it in the Artboards panel does. fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { for b in boards { let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); @@ -60,6 +62,11 @@ fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { view.artboard = board; } } + if app.session.tool_id() == "artboard" + && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0) + { + crate::panels::artboards::select(app, crate::panels::artboards::selected(app, n)); + } } /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index d74b9e1699..f0cf5fa877 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -126,6 +126,24 @@ fn set_active_artboard_index_shows_the_artboard_in_the_view() { assert_eq!(app.views[0].artboard, 1); } +#[test] +fn the_artboard_tool_follows_the_artboard_a_script_makes_active() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 2); + // A run starts the tool afresh; it keeps the view's active artboard, then the one the script chose. + for (source, active) in [("vc.log(1);", 2), ("app.activeDocument.artboards.setActiveArtboardIndex(1);", 1)] { + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, active, "{source}"); + assert_eq!(app.session.tool_options()["active"], json!(active), "{source}"); + assert_eq!(app.session.tool_options()["selected"], json!([active]), "{source}"); + } +} + #[test] fn a_script_error_goes_to_the_status_bar() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 7296adf023..a1d9a1a0ee 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2735,7 +2735,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the - run leaves it). An index outside the list throws a + run leaves it). The report also lists a document whose active artboard has another index when the run ends because + artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. From 9d9c23f6106bcb38959c1e9964e3292694141551 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:51:20 -0800 Subject: [PATCH 036/533] Scripts: a layer's or group's removeAll refuses art on a locked artboard The removeAll() of a layer's or group's pageItems, and of groupItems and compoundPathItems, checked only for hidden or locked objects, so it deleted art on a locked artboard that remove() and the document's pageItems.removeAll() refuse. It now refuses those objects with the same error before anything is deleted, and records no undo step. --- crates/engine/src/script/dom/layers.rs | 21 +++++++++----- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 108fe7f2e8..1251972f64 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -39,9 +39,9 @@ use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ - Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, - command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, method, named, num, - number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, + boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, + method, named, num, number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -664,11 +664,12 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { } /// `removeAll()`: deletes every object the collection lists (those inside another listed one go -/// with it) in one command. A hidden or locked one, or one in a hidden or locked layer or group, -/// stops it before anything is deleted. +/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or +/// one on a locked artboard stops it before anything is deleted, as the document's +/// `pageItems.removeAll()` is stopped. fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let all = art_list(h, st, kind, c)?; let d = &st.doc; let listed: std::collections::HashSet = all.iter().copied().collect(); @@ -676,12 +677,18 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + let locks = d.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f0862963b4..99fd7ae784 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,46 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// The `removeAll()` of a layer's or group's collections, and of `groupItems` and +/// `compoundPathItems`, refuses art on a locked artboard as the document's `pageItems.removeAll()` +/// does, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for scope in [ + "app.activeDocument.layers[0].pageItems", + "app.activeDocument.layers[0].groupItems", + "app.activeDocument.groupItems", + "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.layers[0].compoundPathItems", + "app.activeDocument.compoundPathItems", + ] { + let err = failure(&mut s, &format!("{scope}.removeAll();")); + assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); + assert_eq!(undo_steps(&s), steps, "{scope}"); + } + lock(&mut s, false); + let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From 54cd14b3cd615e5d7096eeee9674351e3f30b101 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:50:35 -0800 Subject: [PATCH 037/533] Plug-ins: react to selection, layer, open and save events A plug-in at API level 2 with the new `events` permission can name any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest's `events` list. Its `vc_event` export is then called with a small JSON event after each change of that kind has finished, outside any undo step. Changes between two deliveries are one event. The desktop app delivers twice a frame, after the work that finished in the background and at the end of the frame after the canvas, panels and dialogs ran; control-channel requests run in the desktop app and are delivered by the frame. vectorcraft-cli and headless MCP deliver after each request. A plug-in installed after a change is not given it, and a change made after an install reaches the new plug-in at the next delivery. - A handler only reads. It may call ten commands that read (dataset.list, graphicStyle.list, guide.list, image.info, object.blend.info, swatch.list, symbol.list, text.getRange, transparency.info and variable.list); any other call fails before it runs with an error naming the event. After each call every document with its selection, current layer and undo history, the active document, the paint defaults, the active Appearance row and the preferences are put back, and a call that changed a document is refused. - A handler gets 5 M instructions and 200 ms, shared by the module's start function, `vc_alloc` and `vc_event`. A handler that fails 3 times in a row gets no more events until VectorCraft starts again. - An event raised while a handler runs waits for the next delivery. - Events carry the document number and counts; selected ids (at most 2,048) only with `doc.read`. No paths or file contents. - A save that finishes after its document closed is still reported. - A document opened or created since the last delivery is compared with its state when the command that added it ended, so the first change made to it is an event. - A waiting event is dropped for a plug-in that was removed, so the same module installed again is not given it. - The desktop app delivers the events of a script in the frame the script ends in. plugin.list and plugin.info report `events`, `eventsOff` and `lastEventError`. Docs: docs/plugins.md (Events), docs/mcp.md and one progress line in docs/target-app-parity.md. The new plug-in messages, the status lines for a failed handler and the permission's words in Install Plug-in... have rows in every complete catalog. --- crates/engine/src/cmd/fileio/load.rs | 3 +- crates/engine/src/cmd/fileio/save.rs | 2 + crates/engine/src/cmd/plugin.rs | 16 +- crates/engine/src/cmd/plugin_call.rs | 118 ++++++ crates/engine/src/lib.rs | 7 + crates/engine/src/plugin_events.rs | 515 +++++++++++++++++++++++ crates/engine/src/session/documents.rs | 6 + crates/engine/src/session/execute.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/plugin_events.rs | 459 ++++++++++++++++++++ crates/plugins/src/events.rs | 94 +++++ crates/plugins/src/lib.rs | 5 +- crates/plugins/src/manifest.rs | 101 ++++- crates/plugins/src/permissions.rs | 16 +- crates/plugins/src/runtime.rs | 104 ++++- crates/plugins/src/wat.rs | 12 + crates/plugins/tests/abi.rs | 73 ++++ crates/ui-egui/src/app.rs | 34 ++ crates/ui-egui/src/dialogs/tests.rs | 1 + crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tests.rs | 27 ++ crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/io/open.rs | 1 + crates/ui-egui/src/tests/plugins.rs | 40 ++ crates/ui-egui/src/tests/script_run.rs | 32 ++ docs/mcp.md | 5 +- docs/plugins.md | 67 ++- docs/target-app-parity.md | 1 + 54 files changed, 1976 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/plugin_events.rs create mode 100644 crates/engine/src/tests/plugin_events.rs create mode 100644 crates/plugins/src/events.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1818816842..128d91c4f6 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1003,7 +1003,8 @@ fn open_loaded( st.import_losses = losses; st.links_from = read_from; let opened = &s.documents()[index]; - let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string()); + let (title, file_info_title, uid) = (opened.title(), opened.doc.info_title().to_string(), opened.uid); + s.note_plugin_event(vectorcraft_plugins::Event::DocumentOpened, uid); Ok(super::merge( json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }), links.to_json(), diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..830378e28a 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1201,6 +1201,8 @@ impl SaveJob { } if saved { crate::cmd::recovery::forget(s, uid); + // Also when the document closed while its file was being written. + s.note_plugin_event(vectorcraft_plugins::Event::DocumentSaved, uid); } if let Some(path) = written { if native { diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..5cd4686afb 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -104,6 +104,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if !m.events.is_empty() { + v["events"] = json!(m.events); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -886,6 +889,7 @@ fn install(s: &mut Session, p: &Value) -> Result { s.store_disabled_plugins_in(&turn); } drop(turn); + s.plugins_changed_for_events(); let mut v = describe_installed(&installed); if !unknown.is_empty() { v["unknownCommands"] = json!(unknown); @@ -1198,12 +1202,17 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result { Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::>()})) } -fn info(_: &mut Session, p: &Value) -> Result { +fn info(s: &mut Session, p: &Value) -> Result { let plugin = plugin_by_id("plugin.info", p)?; let mut v = describe_installed(&plugin); v["manifest"] = serde_json::to_value(plugin.manifest()).unwrap_or(Value::Null); v["defaults"] = Value::Object(plugin.manifest().defaults()); v["lastError"] = json!(effect::last_error(plugin.id())); + if !plugin.manifest().events.is_empty() { + let (off, last) = s.plugin_event_status(&plugin); + v["eventsOff"] = json!(off); + v["lastEventError"] = json!(last); + } Ok(v) } @@ -1241,6 +1250,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { if !stored && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } + s.plugins_changed_for_events(); Ok(json!({"removed": id})) } @@ -1270,7 +1280,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md; events: it reacts to the events it names, see events), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), events?: [\"selection.changed\"|\"document.opened\"|\"document.saved\"|\"layer.changed\"] (the events its vc_event handler is given after each change of that kind, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1279,7 +1289,7 @@ pub fn specs() -> Vec { "Plug-in Info", [], None, - "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width)}", + "{id} → plugin.list's entry plus {manifest, defaults, lastError (a live effect's last failure, null; for a live effect with paintOutput, its name and the refused field, such as objects[1].strokes[0].width), eventsOff? (with events: true once 3 handlers in a row failed, until the app starts again or another module is installed with its id), lastEventError? (with events: its handler's last failure, null)}", always, info ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 867c1f2ff0..21d515163f 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -461,6 +461,78 @@ pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std: Ok(value) } +/// The commands a plug-in's event handler may call ([`event_call`]), in order: each one only reads +/// the document and returns what it found. Every other command is refused before it runs. +pub(crate) const EVENT_READS: &[&str] = &[ + "dataset.list", + "graphicStyle.list", + "guide.list", + "image.info", + "object.blend.info", + "swatch.list", + "symbol.list", + "text.getRange", + "transparency.info", + "variable.list", +]; + +/// Makes call `id` with `args` from a plug-in's handler of event `event` ([`crate::plugin_events`]) +/// as [`call`] does, for a command in [`EVENT_READS`]; any other command is refused before it runs, +/// with an error that names the event. The call runs inside [`read_only`]: every document and the +/// session state the commands a plug-in may call change go back to how they were afterwards, and a +/// call that changed a document, its selection, current layer or layer rows, or which document is +/// active, is refused. +pub(crate) fn event_call(s: &mut Session, run: &Calls, event: &str, id: &str, args: &Value) -> std::result::Result { + if super::find_command(id).is_none() { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + } + if !EVENT_READS.contains(&id) { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` is not a command it may call") }); + } + let (r, changed) = read_only(s, |s| call(s, run, id, args)); + if changed { + return Err(CallFailure { code: CALL_DENIED_COMMAND, why: format!("a {event} handler only reads: `{id}` changed the document") }); + } + r +} + +/// Runs `f` and then puts every open document (its art, selection, current layer, rows and +/// history), which document is active and the session state the commands a plug-in may call change +/// ([`Saved`]) back to how they were → `f`'s result, and whether `f` changed a document, its +/// selection, current layer or layer rows, opened or closed one, or changed which one is active. +/// A document `f` changed is given a newer revision, so it redraws. +fn read_only(s: &mut Session, f: impl FnOnce(&mut Session) -> R) -> (R, bool) { + let saved = Saved::of(s); + let pending_paint = s.pending_paint.clone(); + let start = s.docs.clone(); + let active = s.active; + let r = f(s); + let now = std::mem::replace(&mut s.docs, start); + let mut changed = s.active != active || now.len() != s.docs.len(); + for st in &mut s.docs { + let Some(n) = now.iter().find(|d| d.uid == st.uid) else { + changed = true; + continue; + }; + if n.revision != st.revision + || !Arc::ptr_eq(&n.doc, &st.doc) + || n.selection != st.selection + || n.active_layer != st.active_layer + || n.layer_rows != st.layer_rows + { + st.revision = st.revision.max(n.revision).saturating_add(1); + changed = true; + } + } + s.active = active; + saved.restore(s); + s.pending_paint = pending_paint; + if changed { + s.sync_front_profiles(); + } + (r, changed) +} + /// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the /// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever /// param carries it. @@ -917,4 +989,50 @@ mod tests { assert!(!names_key("{pathData: 1}", "path")); assert!(names_key("path: x", "path")); } + + /// Each command an event handler may call is one a plug-in may call and one the journal does + /// not record, listed once, in order. + #[test] + fn event_reads_are_reviewed_reads() { + for id in EVENT_READS { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused to every plug-in"); + assert!(!spec.journal, "{id} is journaled"); + } + assert!(EVENT_READS.windows(2).all(|w| w[0] < w[1]), "in order, once each"); + } + + /// [`read_only`] puts back what its function changed: the document, its selection, the + /// preferences and the paint defaults, and says that the document changed; a function that + /// changes nothing is no change. + #[test] + fn read_only_puts_everything_back() { + use serde_json::json; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (prefs, paint) = (s.prefs.history_states, s.paint.clone()); + let ((), changed) = read_only(&mut s, |s| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + s.prefs.history_states += 1; + s.paint.stroke_width += 3.0; + }); + assert!(changed); + let st = s.doc().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert!(st.selection.objects.is_empty(), "the selection as it was"); + assert_eq!(st.history.undo.len(), history, "no undo step"); + assert!(st.revision > revision, "a newer revision, so it redraws"); + assert_eq!((s.prefs.history_states, &s.paint), (prefs, &paint)); + let revision = st.revision; + let ((), changed) = read_only(&mut s, |s| { + s.execute("variable.list", &json!({})).unwrap(); + }); + assert!(!changed, "a read changes nothing"); + assert_eq!(s.doc().unwrap().revision, revision); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..ed85ece069 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod guard; pub mod inspect; pub mod journal; pub mod link_watch; +pub mod plugin_events; pub mod schemas; pub mod steps; pub mod store; @@ -317,6 +318,12 @@ pub struct Session { /// While the active tool's actions run: their commands aren't "a command from outside the /// tool" ([`Session::after_command`]). pub(crate) in_tool_actions: bool, + /// The events plug-ins react to that wait for delivery, and how the documents were at the last + /// check ([`plugin_events`]). + pub(crate) plugin_events: plugin_events::PluginEvents, + /// The frontend delivers plug-in events by the frame ([`Session::deliver_plugin_events`]). Off, + /// each top-level command delivers them when it ends. + pub plugin_event_frames: bool, /// The warnings of the previews that settling an interaction applied, while a top-level command /// or the tool's actions collect them ([`Session::collect_settled_warnings`]). settled_warnings: Option>, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs new file mode 100644 index 0000000000..9951904991 --- /dev/null +++ b/crates/engine/src/plugin_events.rs @@ -0,0 +1,515 @@ +//! Events plug-ins react to ([`vectorcraft_plugins::events`]): the session notices a changed +//! selection, current layer or set of layers by comparing each open document with how it was at the +//! last check, and hears of each successful open and save ([`Session::note_plugin_event`]). It then +//! calls the `vc_event` handler of each installed plug-in whose manifest names the event, after the +//! change has finished and outside any undo step. +//! +//! - A check runs after each top-level command, or when a frontend that sets +//! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. +//! Changes between two checks are one event: a burst of selection changes is one +//! `selection.changed` with the final selection. No check runs while an interaction is open (a +//! drag being previewed). A document opened or created since the last check is compared with how +//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a +//! handler runs waits for the next delivery: handlers never run inside one another. +//! - A handler only reads. The host applies nothing it returns, and it may call only the commands +//! in [`super::cmd::plugin_call::EVENT_READS`]; any other call is refused with an error that names +//! the event, and what a call changes is put back ([`super::cmd::plugin_call::event_call`]). +//! - A handler that fails is reported once a streak; after +//! [`vectorcraft_plugins::events::MAX_EVENT_FAILURES`] failures in a row the plug-in's events stop +//! until the session ends, or until another module is installed under its id. +//! - When no installed plug-in reacts to events, a check returns before comparing anything. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection}; +use vectorcraft_plugins::events::{Event, MAX_EVENT_FAILURES, MAX_EVENT_IDS}; +use vectorcraft_plugins::permissions::Permission; +use vectorcraft_plugins::{LogLevel, Plugin, registry}; + +use crate::Session; + +/// Most events that wait for delivery. +pub const MAX_PENDING: usize = 32; + +/// Most notices kept for the frontend to show; older ones are dropped. +pub const MAX_NOTICES: usize = 64; + +/// The reasons a `layer.changed` event gives, in the order it lists them. +pub const LAYER_REASONS: [&str; 5] = ["current", "added", "deleted", "reordered", "options"]; + +/// A document as the last check saw it. +struct Seen { + uid: u64, + doc: Arc, + selection: Selection, + layer: Option, +} + +/// A plug-in an event is for: its id and the hash of its module. +type Recipient = (String, String); + +/// The recipient `p` is. +fn recipient(p: &Plugin) -> Recipient { + (p.id().to_string(), p.hash().to_string()) +} + +/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and +/// the plug-ins it is for: those installed when it happened. +#[derive(Clone, Debug, PartialEq)] +struct Pending { + event: Event, + document: u64, + reasons: Vec<&'static str>, + to: Vec, +} + +/// One plug-in's failed handlers in a row, for the module with `hash`. +#[derive(Clone, Debug, Default)] +struct Failures { + hash: String, + count: u32, + disabled: bool, + last_error: Option, +} + +/// A line a handler wrote with `vc_log`, or a handler's failure, for the frontend to show. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notice { + /// The plug-in's id and name. + pub plugin: String, + pub name: String, + /// The event its handler was given. + pub event: &'static str, + pub level: LogLevel, + /// The text, in English for a failure. + pub text: String, +} + +/// The session's plug-in event state. +#[derive(Default)] +pub struct PluginEvents { + seen: Vec, + /// The plug-ins that reacted to events when `seen` was taken. + seen_by: Vec, + pending: VecDeque, + dispatching: bool, + failures: BTreeMap, + notices: VecDeque, + /// The installed plug-ins that react to events, as of a registry revision. + subscribers: Option<(u64, Vec>)>, +} + +impl PluginEvents { + /// The installed plug-ins that react to events (none in Safe Mode). + fn subscribers(&mut self) -> Vec> { + if vectorcraft_plugins::safe_mode::active() { + return Vec::new(); + } + let revision = registry::revision(); + if let Some((at, subs)) = &self.subscribers + && *at == revision + { + return subs.clone(); + } + let subs: Vec> = registry::list().into_iter().filter(|p| !p.manifest().events.is_empty()).collect(); + self.subscribers = Some((revision, subs.clone())); + subs + } + + /// Queues `event` for document `uid`, for the plug-ins `to`. A `selection.changed` or + /// `layer.changed` already waiting for that document takes it in (a layer event adds the new + /// reasons to its own, and the new plug-ins to its own); past [`MAX_PENDING`] the oldest event is + /// dropped. + fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { + if matches!(event, Event::SelectionChanged | Event::LayerChanged) + && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) + { + for r in reasons { + if !p.reasons.contains(&r) { + p.reasons.push(r); + } + } + p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); + for r in to { + if !p.to.contains(&r) { + p.to.push(r); + } + } + return; + } + if self.pending.len() >= MAX_PENDING + && let Some(dropped) = self.pending.pop_front() + { + log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); + } + self.pending.push_back(Pending { event, document: uid, reasons, to }); + } + + fn notice(&mut self, n: Notice) { + if self.notices.len() >= MAX_NOTICES { + self.notices.pop_front(); + } + self.notices.push_back(n); + } + + /// The failures of plug-in `p`, started again when another module was installed under its id. + fn failures_of(&mut self, p: &Plugin) -> &mut Failures { + let f = self.failures.entry(p.id().to_string()).or_default(); + if f.hash != p.hash() { + *f = Failures { hash: p.hash().to_string(), ..Failures::default() }; + } + f + } +} + +/// A layer or sublayer: its id, its parent (`None` at the top), the layer itself without its +/// contents (for comparing its options) and the ids of the rows directly in it, in order. +type LayerRow = (NodeId, Option, vectorcraft_doc::Node, Vec); + +/// Each layer and sublayer of `doc`, in order. +fn layer_rows(doc: &Document) -> Vec { + let mut out = Vec::new(); + let mut stack: Vec<(&Arc, Option)> = doc.layers.iter().rev().map(|l| (l, None)).collect(); + while let Some((n, parent)) = stack.pop() { + let NodeKind::Layer { children, .. } = &n.kind else { continue }; + stack.extend(children.iter().rev().filter(|c| c.is_layer()).map(|c| (c, Some(n.id)))); + let rows = children.iter().map(|c| c.id).collect(); + let mut bare = (**n).clone(); + if let Some(c) = bare.children_mut() { + c.clear(); + } + out.push((n.id, parent, bare, rows)); + } + out +} + +/// Whether a layer's place among the rows beside it differs between `old` (of `before`) and `new` +/// (of `after`), counting only the rows on both sides, so an object added or deleted next to a +/// sublayer is not a move. +fn layers_moved_among_rows(before: &Document, old: &[LayerRow], after: &Document, new: &[LayerRow]) -> bool { + use std::collections::{HashMap, HashSet}; + let layers: HashSet = old.iter().map(|r| r.0).collect(); + let lists = |doc: &Document, rows: &[LayerRow]| { + let mut m: HashMap, Vec> = rows.iter().map(|r| (Some(r.0), r.3.clone())).collect(); + m.insert(None, doc.layers.iter().map(|l| l.id).collect()); + m + }; + let (a, b) = (lists(before, old), lists(after, new)); + a.iter().any(|(parent, xs)| { + let Some(ys) = b.get(parent) else { return false }; + let (in_x, in_y): (HashSet, HashSet) = (xs.iter().copied().collect(), ys.iter().copied().collect()); + let places = |list: &[NodeId], other: &HashSet| { + list.iter().filter(|id| other.contains(id)).enumerate().filter(|(_, id)| layers.contains(id)).map(|(i, id)| (i, *id)).collect::>() + }; + places(xs, &in_y) != places(ys, &in_x) + }) +} + +/// Why the layers of `after` (with current layer `layer_after`) differ from those of `before` +/// (with `layer_before`), in [`LAYER_REASONS`] order; empty when they don't. +fn layer_reasons(before: &Arc, layer_before: Option, after: &Arc, layer_after: Option) -> Vec<&'static str> { + let mut reasons = Vec::new(); + if layer_before != layer_after { + reasons.push("current"); + } + if Arc::ptr_eq(before, after) { + return reasons; + } + let (old, new) = (layer_rows(before), layer_rows(after)); + if new.iter().any(|(id, ..)| !old.iter().any(|(o, ..)| o == id)) { + reasons.push("added"); + } + if old.iter().any(|(id, ..)| !new.iter().any(|(n, ..)| n == id)) { + reasons.push("deleted"); + } + let kept = + |rows: &[LayerRow], other: &[LayerRow]| rows.iter().filter(|r| other.iter().any(|o| o.0 == r.0)).map(|r| (r.0, r.1)).collect::>(); + if kept(&old, &new) != kept(&new, &old) || layers_moved_among_rows(before, &old, after, &new) { + reasons.push("reordered"); + } + if old.iter().any(|r| new.iter().any(|o| o.0 == r.0 && o.2 != r.2)) { + reasons.push("options"); + } + reasons +} + +impl Session { + /// Hears that `event` (`document.opened` or `document.saved`) happened to document `uid`, which + /// the next delivery hands the plug-ins that react to it. Nothing is kept when none does. + pub(crate) fn note_plugin_event(&mut self, event: Event, uid: u64) { + let to: Vec = self.plugin_events.subscribers().iter().filter(|p| p.manifest().reacts_to(event)).map(|p| recipient(p)).collect(); + if to.is_empty() { + return; + } + self.plugin_events.queue(event, uid, Vec::new(), to); + } + + /// Compares each open document with how the last check saw it and queues the events its changes + /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the + /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in + /// installed since the last check is given none: the + /// change may have come before it. A waiting event is no longer for a plug-in that is not + /// installed now, so a module removed and installed again is not given it. Nothing is compared + /// while an interaction is open, nor when no plug-in reacts to events. + fn check_plugin_events(&mut self) { + let subs = self.plugin_events.subscribers(); + if subs.is_empty() { + self.plugin_events.seen.clear(); + self.plugin_events.seen_by.clear(); + self.plugin_events.pending.clear(); + return; + } + let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); + self.plugin_events.pending.retain_mut(|p| { + p.to.retain(|r| installed.contains(r)); + !p.to.is_empty() + }); + if self.docs.iter().any(|d| d.interaction.is_some()) { + return; + } + let mut events = std::mem::take(&mut self.plugin_events); + let before = std::mem::take(&mut events.seen); + let before_by = std::mem::take(&mut events.seen_by); + let to = |e: Event| -> Vec { + subs.iter().filter(|p| p.manifest().reacts_to(e)).map(|p| recipient(p)).filter(|r| before_by.contains(r)).collect() + }; + let (selection, layers) = (to(Event::SelectionChanged), to(Event::LayerChanged)); + let mut seen = Vec::with_capacity(self.docs.len()); + for st in &self.docs { + if let Some(old) = before.iter().find(|s| s.uid == st.uid) { + if !selection.is_empty() && old.selection != st.selection { + events.queue(Event::SelectionChanged, st.uid, Vec::new(), selection.clone()); + } + if !layers.is_empty() { + let reasons = layer_reasons(&old.doc, old.layer, &st.doc, st.active_layer); + if !reasons.is_empty() { + events.queue(Event::LayerChanged, st.uid, reasons, layers.clone()); + } + } + } + seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + events.seen = seen; + events.seen_by = subs.iter().map(|p| recipient(p)).collect(); + events.pending.retain(|p| p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)); + self.plugin_events = events; + } + + /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the + /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, + /// this returns at once: what the handler's calls change waits for the next delivery. + pub fn deliver_plugin_events(&mut self) { + if self.plugin_events.dispatching { + return; + } + self.check_plugin_events(); + if self.plugin_events.pending.is_empty() { + return; + } + let subs = self.plugin_events.subscribers(); + self.plugin_events.dispatching = true; + // The commands a handler calls run nested, never journaled; a panic in one leaves the depth + // as it was found. + let depth = self.depth; + self.depth += 1; + while let Some(p) = self.plugin_events.pending.pop_front() { + if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { + continue; + } + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.to.contains(&recipient(s))) { + if self.plugin_events.failures_of(plugin).disabled { + continue; + } + self.run_handler(plugin, &p); + } + } + self.depth = depth; + self.plugin_events.dispatching = false; + } + + /// The JSON event `p` as plug-in `plugin` is given it: the selected object ids of a + /// `selection.changed` only with `doc.read`. + fn event_json(&self, plugin: &Plugin, p: &Pending) -> Value { + let mut v = json!({ "type": p.event.name(), "document": p.document }); + let Some(st) = self.docs.iter().find(|d| d.uid == p.document) else { return v }; + match p.event { + Event::SelectionChanged => { + let objects = &st.selection.objects; + v["count"] = json!(objects.len()); + v["truncated"] = json!(false); + v["ids"] = Value::Null; + if plugin.manifest().permissions().contains(&Permission::DocRead) { + v["ids"] = json!(objects.iter().take(MAX_EVENT_IDS).map(|i| i.0).collect::>()); + v["truncated"] = json!(objects.len() > MAX_EVENT_IDS); + } + } + Event::LayerChanged => { + v["layer"] = json!(st.active_layer.map(|l| l.0)); + v["reasons"] = json!(p.reasons); + } + Event::DocumentOpened | Event::DocumentSaved => {} + } + v + } + + /// Calls `plugin`'s handler with event `p` and records what it wrote and whether it failed. + fn run_handler(&mut self, plugin: &Arc, p: &Pending) { + let event = p.event.name(); + let text = serde_json::to_vec(&self.event_json(plugin, p)).unwrap_or_default(); + let m = plugin.manifest(); + let may = m.permissions(); + let (r, report) = if may.contains(&Permission::Commands) && !m.command_allowlist.is_empty() { + let calls = crate::cmd::plugin_call::Calls::of(self, may.contains(&Permission::DocRead), false); + let mut bridge = |id: &str, args: &Value| crate::cmd::plugin_call::event_call(self, &calls, event, id, args); + plugin.run_event(&text, Some(&mut bridge)) + } else { + plugin.run_event(&text, None) + }; + let (id, name) = (plugin.id().to_string(), m.name.clone()); + for line in report.lines { + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: line.level, text: line.text }); + } + let failures = self.plugin_events.failures_of(plugin); + let e = match r { + Ok(()) => { + failures.count = 0; + return; + } + Err(e) => e.to_string(), + }; + failures.count += 1; + failures.last_error = Some(e.clone()); + let (count, first) = (failures.count, failures.count == 1); + log::warn!("plug-in {id}: its {event} handler failed: {e}"); + if first { + let text = format!("its {event} handler failed: {e}"); + self.plugin_events.notice(Notice { plugin: id.clone(), name: name.clone(), event, level: LogLevel::Error, text }); + } + if count >= MAX_EVENT_FAILURES { + self.plugin_events.failures_of(plugin).disabled = true; + let text = format!("its events are off until VectorCraft starts again, after {count} failed handlers in a row"); + self.plugin_events.notice(Notice { plugin: id, name, event, level: LogLevel::Error, text }); + } + } + + /// Takes each open document the last check didn't see, one opened or created since, as it is + /// now, so the next check compares it with this state: a change made to it before the next + /// delivery gives its event. Called after each top-level command and when a document is added + /// outside one. Nothing is kept when no plug-in reacted to events at the last check, nor for a + /// document in an interaction. + pub(crate) fn plugin_events_see_new_documents(&mut self) { + if self.plugin_events.seen_by.is_empty() { + return; + } + for st in &self.docs { + if st.interaction.is_none() && !self.plugin_events.seen.iter().any(|s| s.uid == st.uid) { + self.plugin_events.seen.push(Seen { uid: st.uid, doc: st.doc.clone(), selection: st.selection.clone(), layer: st.active_layer }); + } + } + } + + /// Delivers the events of a top-level command that just ended, unless the frontend delivers + /// them once a frame ([`Session::plugin_event_frames`]) or a script is running. + pub(crate) fn plugin_events_after_command(&mut self) { + self.plugin_events_see_new_documents(); + if !self.plugin_event_frames && !self.script_in_run { + self.deliver_plugin_events(); + } + } + + /// After a plug-in was installed or removed, compares the open documents with the last check + /// ([`Session::check_plugin_events`]): what changed before is given only to the plug-ins that + /// were installed then, and what changes from now on to every plug-in installed now, also + /// before the next delivery. + pub(crate) fn plugins_changed_for_events(&mut self) { + if !self.plugin_events.dispatching { + self.check_plugin_events(); + } + } + + /// The handlers' log lines and failures since the last call, oldest first. + pub fn take_plugin_event_notices(&mut self) -> Vec { + self.plugin_events.notices.drain(..).collect() + } + + /// Whether this session stopped delivering events to plug-in `p` after its handlers failed, and + /// the last failure's error. + pub fn plugin_event_status(&self, p: &Plugin) -> (bool, Option) { + match self.plugin_events.failures.get(p.id()).filter(|f| f.hash == p.hash()) { + Some(f) => (f.disabled, f.last_error.clone()), + None => (false, None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waiting_selection_and_layer_events_of_a_document_merge() { + let mut e = PluginEvents::default(); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); + e.queue(Event::SelectionChanged, 1, vec![], vec![]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); + e.queue(Event::SelectionChanged, 2, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + e.queue(Event::DocumentSaved, 1, vec![], vec![]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + assert_eq!( + got, + [ + (Event::SelectionChanged, 1, vec![]), + (Event::LayerChanged, 1, vec!["current", "options"]), + (Event::SelectionChanged, 2, vec![]), + (Event::DocumentSaved, 1, vec![]), + (Event::DocumentSaved, 1, vec![]), + ] + ); + } + + /// While a handler runs, a delivery returns at once; the change waits for the next one, which + /// hands it over once. + #[test] + fn an_event_raised_while_a_handler_runs_waits_for_the_next_delivery() { + use serde_json::json; + use vectorcraft_plugins::wat as tpl; + let id = "test.events.nested"; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.allow_plugin_grants_from_requests(); + let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap()["id"].clone(); + s.execute("select.none", &json!({})).unwrap(); + let manifest = + format!(r#"{{"id":"{id}","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let grant = json!(["progress", "events"]); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + s.plugin_event_frames = true; + let given = |s: &mut Session| s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).count(); + s.plugin_events.dispatching = true; + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "not inside the running handler"); + s.plugin_events.dispatching = false; + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 1); + s.deliver_plugin_events(); + assert_eq!(given(&mut s), 0, "once"); + s.execute("plugin.remove", &json!({"id": id})).unwrap(); + } + + #[test] + fn at_most_32_events_wait() { + let mut e = PluginEvents::default(); + for uid in 0..(MAX_PENDING as u64 + 5) { + e.queue(Event::DocumentOpened, uid, vec![], vec![]); + } + assert_eq!(e.pending.len(), MAX_PENDING); + assert_eq!(e.pending.front().map(|p| p.document), Some(5), "the oldest are dropped"); + } +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..684b2b881a 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -136,6 +136,8 @@ impl Session { screens_hand_off: None, recovery: Default::default(), in_tool_actions: false, + plugin_events: Default::default(), + plugin_event_frames: false, settled_warnings: None, previewing: false, decoded_images: Default::default(), @@ -365,6 +367,10 @@ impl Session { { self.begin_named_undo_group(label); } + if self.depth == 0 { + // Inside a command, this happens once the command has finished. + self.plugin_events_see_new_documents(); + } i } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..19cd41fdb0 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -249,6 +249,7 @@ impl Session { self.journal_in_undo_groups(doc, &grouped, journal); self.trim_histories(); self.after_command(Some(id)); + self.plugin_events_after_command(); } else if matches!(id, "edit.undo" | "edit.redo") { // A step of `command.batch`: the tool hears of it as it does of the command alone. self.notify_text_tool(id); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..36fb0b0f47 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -145,6 +145,7 @@ mod perspgrid; mod pixelalign; mod place; mod placed_document; +mod plugin_events; mod plugins; mod prefs; mod prefs_file; diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs new file mode 100644 index 0000000000..df8dd04cb4 --- /dev/null +++ b/crates/engine/src/tests/plugin_events.rs @@ -0,0 +1,459 @@ +//! Events plug-ins react to (`events`, `vc_event`): each event reaches the plug-ins that name it, +//! once, after the change; a burst of selection changes in one frame is one event; a handler only +//! reads; and a handler that keeps failing stops being called. + +use serde_json::{Value, json}; +use vectorcraft_plugins::LogLevel; +use vectorcraft_plugins::wat as tpl; + +use crate::*; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// A session with a 400 × 200 document that takes `grant` from requests. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.allow_plugin_grants_from_requests(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Installs plug-in `id` that reacts to `events` (a JSON list) with the vc_event body `handler`, +/// writes log lines and also has the permissions `more`; `imports` are module fields its handler +/// uses besides the host imports, and `allowlist` the commands it may call. +fn install(s: &mut Session, id: &str, events: &str, more: &[&str], imports: &str, handler: &str, allowlist: &[&str]) { + let mut grant = vec!["progress", "events"]; + grant.extend_from_slice(more); + let allow = if allowlist.is_empty() { String::new() } else { format!(r#","commandAllowlist":{}"#, json!(allowlist)) }; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{},"events":{events}{allow}}}"#, json!(grant)); + let wasm = wat::parse_str(tpl::reacting(&manifest, &format!("{} {imports}", tpl::HOST_IMPORTS), handler)).unwrap(); + run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); +} + +/// The events plug-in `id`'s handler was given since the last call, as it logged them. +fn given(s: &mut Session, id: &str) -> Vec { + let notices = s.take_plugin_event_notices(); + notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Info).map(|n| serde_json::from_str(&n.text).unwrap()).collect() +} + +fn types(events: &[Value]) -> Vec<&str> { + events.iter().map(|e| e["type"].as_str().unwrap()).collect() +} + +/// A selection change, a new layer, a save and an open each reach the plug-in that names them once, +/// after the change, with the document they happened in; a plug-in that names only `document.saved` +/// is given only the save. +#[test] +fn each_event_reaches_the_plugins_that_name_it_once() { + let (all, saves) = ("test.events.all", "test.events.saves"); + let mut s = session(); + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, all, r#"["selection.changed","document.opened","document.saved","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + install(&mut s, saves, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + assert!(given(&mut s, all).is_empty(), "installing replays nothing"); + let doc = s.doc().unwrap().uid; + + run(&mut s, "select.set", json!({"ids": [r.0]})); + let notices = s.take_plugin_event_notices(); + let got: Vec = notices.iter().filter(|n| n.plugin == all).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + assert!(notices.iter().all(|n| n.plugin != saves), "not named, not given"); + + run(&mut s, "select.set", json!({"ids": [r.0]})); + assert!(given(&mut s, all).is_empty(), "the same selection again is no change"); + + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + let got = given(&mut s, all); + assert_eq!(types(&got), ["layer.changed"]); + assert_eq!(got[0]["layer"], json!(layer)); + assert!(got[0]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[0]); + + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("events.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + let notices = s.take_plugin_event_notices(); + for id in [all, saves] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "document.saved", "document": doc})], "{id}"); + } + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + assert_ne!(opened, doc); + assert_eq!(given(&mut s, all), [json!({"type": "document.opened", "document": opened})], "a new document's own selection is no change"); + + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": all})); + run(&mut s, "plugin.remove", json!({"id": saves})); +} + +/// A save of a document that closes before the frame's delivery still reaches the plug-in, with +/// the document's number; its selection change does not. So does a save written on another thread +/// that finishes after its document closed. +#[test] +fn a_save_reaches_the_plugin_when_its_document_closes_first() { + let id = "test.events.closed"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed","document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [r.0]})); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-closed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("closed.vectorcraft").to_string_lossy()})); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != doc), "the document closed"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let later = s.doc().unwrap().uid; + let p = json!({"path": dir.join("later.vectorcraft").to_string_lossy()}); + let plan = crate::cmd::fileio::save_plan(&s, crate::cmd::fileio::SaveMode::SaveAs, &p).unwrap(); + let job = crate::cmd::fileio::save_job(&mut s, plan).unwrap(); + job.write(|path, bytes| std::fs::write(path, bytes).map_err(|e| EngineError::Other(e.to_string()))).unwrap(); + run(&mut s, "file.close", json!({})); + assert!(s.docs.iter().all(|d| d.uid != later), "the document closed"); + job.complete(&mut s, later); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": later})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed after a save or a selection change, before the frame's delivery, is given +/// neither; the plug-in installed before is given both, and the next change reaches both. +#[test] +fn a_plugin_installed_before_the_delivery_gets_no_earlier_events() { + let (early, late) = ("test.events.early", "test.events.late"); + let events = r#"["selection.changed","document.saved"]"#; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, early, events, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-late-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("late.vectorcraft").to_string_lossy()})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + install(&mut s, late, events, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let of = |id: &str| -> Vec { notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect() }; + assert_eq!(types(&of(early)), ["document.saved", "selection.changed"]); + assert!(of(late).is_empty(), "{:?}", of(late)); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + for id in [early, late] { + let got: Vec = notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(got, [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": null, "truncated": false})], "{id}"); + } + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// With delivery once a frame, a selection change made after a plug-in was installed, in the same +/// frame, reaches it. +#[test] +fn a_change_after_the_install_in_the_same_frame_reaches_the_plugin() { + let id = "test.events.same_frame"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.none", json!({})); + s.plugin_event_frames = true; + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": doc, "count": 1, "ids": [r.0], "truncated": false})]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, a change made to a document created or opened since the last +/// delivery gives its event at the next one; an opened document's `document.opened` comes first, +/// once. +#[test] +fn a_change_to_a_document_opened_since_the_last_delivery_gives_its_event() { + let id = "test.events.new_doc"; + let mut s = session(); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-new-doc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("new-doc.vectorcraft").to_string_lossy().into_owned(); + run(&mut s, "document.save", json!({"path": path})); + install(&mut s, id, r#"["selection.changed","document.opened","layer.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty()); + + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let created = s.doc().unwrap().uid; + let r = rect(&mut s, 10.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "selection.changed", "document": created, "count": 1, "ids": [r.0], "truncated": false})]); + + run(&mut s, "document.open", json!({"path": path})); + let opened = s.doc().unwrap().uid; + let layer = run(&mut s, "layer.new", json!({"name": "Notes"}))["id"].as_u64().unwrap(); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["document.opened", "layer.changed"], "{got:?}"); + assert_eq!((got[0]["document"].clone(), got[1]["document"].clone(), got[1]["layer"].clone()), (json!(opened), json!(opened), json!(layer))); + assert!(got[1]["reasons"].as_array().unwrap().contains(&json!("added")), "{}", got[1]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "once"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save waiting for delivery is not given to the same module removed and installed again before +/// the delivery. +#[test] +fn a_module_installed_again_gets_no_event_from_before_its_removal() { + let id = "test.events.again"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-again-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("again.vectorcraft").to_string_lossy()})); + run(&mut s, "plugin.remove", json!({"id": id})); + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one +/// with it lists the selected ids. +#[test] +fn selected_ids_need_doc_read() { + let id = "test.events.noread"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let got = given(&mut s, id); + assert_eq!(got.len(), 1); + assert_eq!((got[0]["count"].clone(), got[0]["ids"].clone()), (json!(2), Value::Null)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// With delivery once a frame, the selection changes of one frame are one event with the selection +/// the frame ended with, and changes that end where they started are none. +#[test] +fn selection_changes_in_one_frame_are_one_event() { + let id = "test.events.burst"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read"], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + for ids in [vec![a.0], vec![b.0], vec![], vec![a.0, b.0], vec![b.0]] { + run(&mut s, "select.set", json!({"ids": ids})); + } + assert!(given(&mut s, id).is_empty(), "nothing before the frame"); + s.deliver_plugin_events(); + let got = given(&mut s, id); + assert_eq!(types(&got), ["selection.changed"]); + assert_eq!(got[0]["ids"], json!([b.0])); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "back where the frame started"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// `layer.changed` names what changed: a new name is `options`, the same name again is no change, +/// another current layer is `current`, a moved layer `reordered` and a deleted one `deleted`. +#[test] +fn layer_changes_name_their_reasons() { + let id = "test.events.layers"; + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, id, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + let reasons = |s: &mut Session, cmd: &str, p: Value| { + run(s, cmd, p); + given(s, id).iter().map(|e| e["reasons"].clone()).collect::>() + }; + assert_eq!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})), [json!(["options"])]); + assert!(reasons(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})).is_empty(), "same name, no change"); + assert_eq!(reasons(&mut s, "layer.setCurrent", json!({"id": first.0})), [json!(["current"])]); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [first.0], "target": second.0, "place": "above"})), [json!(["reordered"])]); + let deleted = reasons(&mut s, "layer.delete", json!({"ids": [second.0]})); + assert_eq!(deleted.len(), 1); + assert!(deleted[0].as_array().unwrap().contains(&json!("deleted")), "{deleted:?}"); + + // A sublayer moved past an object beside it is reordered; an object drawn beside it is not. + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let sub = NodeId(run(&mut s, "layer.newSublayer", json!({"parent": first.0, "name": "Sub"}))["id"].as_u64().unwrap()); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + given(&mut s, id); + let r = rect(&mut s, 10.0); + assert!(given(&mut s, id).is_empty(), "drawing beside a sublayer moves no layer"); + assert_eq!(reasons(&mut s, "layer.move", json!({"ids": [sub.0], "target": r.0, "place": "above"})), [json!(["reordered"])]); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A handler may call a command listed for handlers, and is given its result; one that calls a +/// command that changes the document or the current layer, or a read not listed for handlers, is +/// refused with an error that names the event, and the selection, the current layer and the undo +/// history stay as the user left them. +#[test] +fn a_handler_only_reads() { + let (reads, edits) = ("test.events.reads", "test.events.edits"); + let (unlisted, layers) = ("test.events.unlisted", "test.events.layer"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let other = run(&mut s, "layer.new", json!({"name": "Other"}))["id"].as_u64().unwrap(); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + let expected = run(&mut s, "variable.list", json!({})); + // The read's result, copied with `vc_call_result`, is written as a log line. + let (imports, call) = calling("variable.list", "{}"); + let imports = format!(r#"{imports} (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32)))"#); + let handler = format!( + "(drop {call}) (drop (call $vc_log (i32.const 2) (i32.const 0x4000) (call $vc_call_result (i32.const 0x4000) (i32.const 0x4000)))) (i32.const 0)" + ); + install(&mut s, reads, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["variable.list"]); + assert!(!find_command("addon.cleanup.check").unwrap().journal, "a query the journal does not record"); + let (imports, handler) = calling("addon.cleanup.check", "{}"); + install(&mut s, unlisted, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["addon.cleanup.check"]); + let (imports, handler) = calling("select.all", "{}"); + install(&mut s, edits, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["select.all"]); + let (imports, handler) = calling("layer.setCurrent", &format!(r#"{{"id":{other}}}"#)); + install(&mut s, layers, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &["layer.setCurrent"]); + let (undo, rows) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().layer_rows.clone()); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let notices = s.take_plugin_event_notices(); + let read: Vec = notices.iter().filter(|n| n.plugin == reads).map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + assert_eq!(read, [expected], "the read call succeeds and gives its result: {notices:?}"); + for (id, cmd) in [(unlisted, "addon.cleanup.check"), (edits, "select.all"), (layers, "layer.setCurrent")] { + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + } + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, [a], "the selection the user made"); + assert_eq!((st.active_layer, &st.layer_rows), (Some(first), &rows), "the current layer the user chose"); + assert_eq!(st.history.undo.len(), undo, "no undo step"); + let info = run(&mut s, "plugin.info", json!({"id": edits})); + assert!(info["lastEventError"].as_str().unwrap().contains("only reads"), "{info}"); + assert_eq!(info["eventsOff"], json!(false)); + assert_eq!(info["events"], json!(["selection.changed"])); + run(&mut s, "plugin.remove", json!({"id": reads})); + run(&mut s, "plugin.remove", json!({"id": unlisted})); + run(&mut s, "plugin.remove", json!({"id": edits})); + run(&mut s, "plugin.remove", json!({"id": layers})); +} + +/// A handler that calls a query the journal does not record but that changes the selection (Select +/// All Instances) is refused before the query runs: the document, its revision, selection and undo +/// history, and the session's paint and Appearance state, are as the user left them. +#[test] +fn a_handler_query_that_selects_is_refused_before_it_runs() { + let id = "test.events.selects"; + let (cmd, args) = ("symbol.selectInstances", r#"{"name":"Dot"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let dot = rect(&mut s, 10.0); + run(&mut s, "symbol.new", json!({"name": "Dot", "ids": [dot.0]})); + let b = rect(&mut s, 40.0); + run(&mut s, "select.none", json!({})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["selection.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + s.plugin_event_frames = true; + run(&mut s, "select.set", json!({"ids": [b.0]})); + let st = s.doc().unwrap(); + let (doc, revision, undo) = (st.doc.clone(), st.revision, st.history.undo.len()); + let (paint, appearance, fill_active) = (s.paint.clone(), format!("{:?}", s.active_appearance_item), s.fill_active); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a selection.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the same document"); + assert_eq!((st.revision, st.history.undo.len()), (revision, undo), "the same revision and undo history"); + assert_eq!(st.selection.objects, [b], "the selection the user made"); + assert_eq!((&s.paint, format!("{:?}", s.active_appearance_item), s.fill_active), (&paint, appearance, fill_active)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A refused handler call leaves the Appearance panel's active row and the Fill or Stroke in +/// front as the user chose them, also when the query it called selected art. +#[test] +fn a_refused_handler_call_keeps_the_active_appearance_row() { + let id = "test.events.appearance"; + let (cmd, args) = ("addon.cleanup.show", r#"{"kind":"duplicateObjects","scope":"document"}"#); + assert!(!find_command(cmd).unwrap().journal, "a query the journal does not record"); + let mut s = session(); + let (a, _) = (rect(&mut s, 10.0), rect(&mut s, 10.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let (imports, handler) = calling(cmd, args); + install(&mut s, id, r#"["layer.changed"]"#, &["doc.read", "commands"], &imports, &handler, &[cmd]); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + let fill_active = s.fill_active; + run(&mut s, "layer.new", json!({"name": "Other"})); + let notices = s.take_plugin_event_notices(); + let failed: Vec<&str> = notices.iter().filter(|n| n.plugin == id && n.level == LogLevel::Error).map(|n| n.text.as_str()).collect(); + assert_eq!(failed.len(), 1, "{notices:?}"); + assert!(failed[0].contains(&format!("a layer.changed handler only reads: `{cmd}` is not a command it may call")), "{}", failed[0]); + assert_eq!(s.doc().unwrap().selection.objects, [a], "the selection the user made"); + assert!(s.active_appearance_item.is_some(), "the active Appearance row"); + assert_eq!(s.fill_active, fill_active); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// Module fields that import `vc_call` and hold `cmd` and `args`, and a `vc_event` body that calls +/// `cmd` with `args` and returns what the call returned. +fn calling(cmd: &str, args: &str) -> (String, String) { + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let handler = format!("(call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))", cmd.len(), args.len()); + (imports, handler) +} + +/// A handler that fails is reported once; after three failures in a row its events stop for the +/// session, while each selection the user makes stays. +#[test] +fn a_handler_that_keeps_failing_is_turned_off() { + let id = "test.events.failing"; + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 40.0)); + run(&mut s, "select.none", json!({})); + install(&mut s, id, r#"["selection.changed"]"#, &[], "", "unreachable", &[]); + let mut notices = Vec::new(); + for ids in [vec![a.0], vec![b.0], vec![a.0], vec![b.0], vec![a.0]] { + run(&mut s, "select.set", json!({"ids": ids.clone()})); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect::>(), ids, "the user's selection stays"); + notices.extend(s.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text)); + } + assert_eq!(notices.len(), 2, "{notices:?}"); + assert!(notices[0].starts_with("its selection.changed handler failed") && notices[0].contains("trapped"), "{}", notices[0]); + assert!(notices[1].contains("after 3 failed handlers in a row"), "{}", notices[1]); + let info = run(&mut s, "plugin.info", json!({"id": id})); + assert_eq!(info["eventsOff"], json!(true)); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/plugins/src/events.rs b/crates/plugins/src/events.rs new file mode 100644 index 0000000000..53a5ad2a2a --- /dev/null +++ b/crates/plugins/src/events.rs @@ -0,0 +1,94 @@ +//! Events a plug-in may react to, from plug-in API level 2 on: its manifest's `events` names them +//! ([`Event`]) and lists the `events` permission, and the module exports +//! `vc_event(event_ptr: i32, event_len: i32) -> i32`. After a change has finished, the host calls +//! `vc_event` in a fresh instance with a small JSON object that names the event and the document +//! ([`crate::Plugin::run_event`]). A handler only reads: the host applies nothing it returns, and +//! a command call that would change a document is refused ([`crate::host`]). +//! +//! The limits are VectorCraft's own values: [`EVENT_FUEL`] instructions and +//! [`EVENT_WALL_TIME_MS`] for one handler, an event of at most [`MAX_EVENT_BYTES`], and +//! [`MAX_EVENT_IDS`] selected ids in a `selection.changed` event. + +/// The plug-in API level that adds `events`, the `events` permission and `vc_event`. +pub const EVENTS_API: u32 = 2; + +/// Instructions one handler may use, or the plug-in's own budget when that is smaller. +pub const EVENT_FUEL: u64 = 5_000_000; + +/// Wall-clock budget of one handler, in milliseconds, or the plug-in's own when that is shorter. +pub const EVENT_WALL_TIME_MS: u64 = 200; + +/// Largest event JSON the host hands a handler, in bytes. +pub const MAX_EVENT_BYTES: usize = 64 * 1024; + +/// Most selected object ids a `selection.changed` event lists; a larger selection sends the first +/// ones with `truncated: true` and its whole `count`. That many ids of the largest value still fit +/// in [`MAX_EVENT_BYTES`]. +pub const MAX_EVENT_IDS: usize = 2048; + +/// Failed handlers in a row after which the host stops calling a plug-in's handler until the app +/// starts again. +pub const MAX_EVENT_FAILURES: u32 = 3; + +/// One thing a plug-in may react to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Event { + /// The selection in a document changed: other objects, anchors or segments, or nothing. + SelectionChanged, + /// A file opened as a document (File › Open, a recent file, New from Template). + DocumentOpened, + /// A document was saved to its own file (Save, Save As). + DocumentSaved, + /// The current layer changed, or a layer was added, deleted, moved or given other options. + LayerChanged, +} + +impl Event { + /// Every event, in the order the docs list them. + pub const ALL: [Event; 4] = [Event::SelectionChanged, Event::DocumentOpened, Event::DocumentSaved, Event::LayerChanged]; + + /// Its name in a manifest's `events`, which is also the event's `type`. + pub fn name(self) -> &'static str { + match self { + Event::SelectionChanged => "selection.changed", + Event::DocumentOpened => "document.opened", + Event::DocumentSaved => "document.saved", + Event::LayerChanged => "layer.changed", + } + } + + /// The event named `name`. + pub fn parse(name: &str) -> Option { + Event::ALL.into_iter().find(|e| e.name() == name) + } + + /// Whether the event is still delivered when its document has closed before the delivery: + /// an open or a save is, a selection or layer change is not. + pub fn outlives_document(self) -> bool { + matches!(self, Event::DocumentOpened | Event::DocumentSaved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_round_trip() { + for e in Event::ALL { + assert_eq!(Event::parse(e.name()), Some(e)); + } + assert_eq!(Event::parse("selection.change"), None); + assert_eq!(Event::parse(""), None); + } + + /// A `selection.changed` event that lists the most ids, each of the largest value, fits in the + /// largest event a handler is given. + #[test] + fn the_largest_selection_event_fits() { + let ids = vec![u64::MAX; MAX_EVENT_IDS]; + let event = serde_json::json!({"type": "selection.changed", "document": u64::MAX, "count": u64::MAX, "ids": ids, "truncated": true}); + let len = serde_json::to_vec(&event).unwrap().len(); + assert!(len <= MAX_EVENT_BYTES, "{len} bytes"); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..a77f243efb 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -31,12 +31,14 @@ //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host -//! runs through `vc_run` with the command's id in `_context`. +//! runs through `vc_run` with the command's id in `_context`. Any kind may also react to the +//! [`events`] its manifest names, through `vc_event`, without changing the document. #![forbid(unsafe_code)] pub mod deferred; pub mod dialog; pub mod effect; +pub mod events; pub mod export; pub mod host; pub mod import; @@ -51,6 +53,7 @@ pub mod storage; pub mod wat; pub use dialog::ParamUi; +pub use events::Event; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..493e0a3b63 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; +use crate::events::{EVENTS_API, Event}; use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; use crate::{Error, Result}; @@ -348,6 +349,11 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// The events it reacts to, by [`Event::name`]: only a module at `api` 2 or later whose + /// `permissions` list `events` lists any, and it exports `vc_event` ([`crate::events`]). Left + /// out or empty, it reacts to none. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "event_names")] + pub events: Vec, } impl Manifest { @@ -383,6 +389,7 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), } } @@ -440,7 +447,42 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_events() + } + + /// `events` names each [`Event`] at most once, and a list needs `api` 2 or later and the + /// permission `events`, which needs a list. + fn validate_events(&self) -> Result<()> { + for (i, name) in self.events.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if Event::parse(name).is_none() { + return Err(Error::Manifest(format!( + "`events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed" + ))); + } + if self.events.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`events` lists `{shown}` twice"))); + } + } + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Events.name())); + if self.events.is_empty() == listed { + return Err(Error::Manifest("`events` needs the permission `events`, and `events` needs a list of `events`".into())); + } + if listed && self.api < EVENTS_API { + return Err(Error::Manifest(format!("`events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API}"))); + } + Ok(()) + } + + /// The events it reacts to (`events`). + pub fn event_kinds(&self) -> Vec { + self.events.iter().filter_map(|n| Event::parse(n)).collect() + } + + /// Does it react to `event`? + pub fn reacts_to(&self, event: Event) -> bool { + self.events.iter().any(|n| n == event.name()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids @@ -733,6 +775,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`events` must be a list of event names, such as selection.changed"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads the `commands` list one entry at a time from the manifest itself, so each command's /// `params` keep their declaration order and a repeated parameter is refused. A malformed entry /// is an error that names it (its id when the id comes before the fault, otherwise its place in @@ -1394,6 +1447,52 @@ mod tests { assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all"); } + /// Any kind at `api` 2 that lists the permission `events` names the events it reacts to; an + /// unknown or repeated name, a list without the permission or the permission without a list, + /// and a list at `api` 1 are refused, and the error names the fault. + #[test] + fn events_are_listed_with_their_permission_at_api_2() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","selection.changed"]}"#, + ) + .unwrap(); + assert_eq!(m.event_kinds(), [Event::LayerChanged, Event::SelectionChanged]); + assert!(m.reacts_to(Event::SelectionChanged) && !m.reacts_to(Event::DocumentSaved)); + assert_eq!(m.permissions(), [Permission::Events]); + assert_eq!(serde_json::to_value(&m).unwrap()["events"], json!(["layer.changed", "selection.changed"])); + let effect = + br#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","events"],"events":["document.saved"]}"#; + assert_eq!(Manifest::parse(effect).unwrap().event_kinds(), [Event::DocumentSaved]); + let importer = + br#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["q"],"permissions":["import.read","events"],"events":["document.opened"]}"#; + assert!(Manifest::parse(importer).is_ok()); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter","events":null}"#).unwrap(); + assert!(plain.events.is_empty() && serde_json::to_value(&plain).unwrap().get("events").is_none()); + for (bad, says) in [ + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["selection.change"]}"#, + "unknown event `selection.change`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":["layer.changed","layer.changed"]}"#, + "lists `layer.changed` twice", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"events":["layer.changed"]}"#, "needs the permission `events`"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"events":["layer.changed"]}"#, + "needs the permission `events`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[]}"#, "needs the permission `events`"), + (r#"{"id":"a","name":"x","kind":"filter","permissions":["events"],"events":["layer.changed"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":"layer.changed"}"#, "must be a list"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["events"],"events":[1]}"#, "must be a list"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + #[test] fn rejects_bad_manifests() { for bad in [ diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..01a0d00b3a 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -7,7 +7,8 @@ //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of //! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, //! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a -//! manifest lists them. +//! manifest lists them. Nor is `events`, which lets a plug-in of any kind react to the events its +//! manifest names ([`crate::events`]). use serde::{Deserialize, Serialize}; @@ -74,10 +75,14 @@ pub enum Permission { /// ([`crate::host::IMPORTS`]): a filter only. #[serde(rename = "commands")] Commands, + /// Run on its own after the changes its manifest's `events` names ([`crate::events`]), with + /// `vc_event`: any kind. + #[serde(rename = "events")] + Events, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 10] = [ +pub const ALL: [Permission; 11] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -88,6 +93,7 @@ pub const ALL: [Permission; 10] = [ Permission::Settings, Permission::Cache, Permission::Commands, + Permission::Events, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in @@ -109,6 +115,7 @@ impl Permission { Permission::Settings => "settings", Permission::Cache => "cache", Permission::Commands => "commands", + Permission::Events => "events", } } @@ -130,13 +137,14 @@ impl Permission { Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", Permission::Commands => "Run these commands", + Permission::Events => "Run on its own when the selection, a document or a layer changes", } } /// May a plug-in of `kind` that declares `commands` or not list it: one [`Permission::allowed`] - /// gives it, or one of the host imports' ([`HOST`]), which any kind may list. + /// gives it, one of the host imports' ([`HOST`]) or `events`, which any kind may list. pub fn applies(self, kind: Kind, commands: bool) -> bool { - HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) + self == Permission::Events || HOST.contains(&self) || Permission::allowed(kind, commands).contains(&self) } /// The permissions a manifest of `kind` without `permissions` gets. A manifest may also list diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 7c4262dd4e..699fe15161 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -219,6 +219,9 @@ fn wasm_err(e: wasmi::Error) -> Error { /// `vc_run(input_ptr, input_len, params_ptr, params_len) -> len << 32 | ptr` (negative: error). type RunArgs = (i32, i32, i32, i32); +/// `vc_event(event_ptr, event_len) -> 0` (anything else: the handler failed). +type EventArgs = (i32, i32); + impl Plugin { /// Validates and loads a module: checks the ABI version, the exports and reads the manifest, and /// checks that each host import it asks for is one the host offers ([`crate::host::IMPORTS`]) @@ -269,6 +272,9 @@ impl Plugin { // The other exports must exist with the right types. live.func::("vc_alloc")?; live.func::("vc_run")?; + if !p.manifest.events.is_empty() { + live.func::("vc_event")?; + } Ok(p) } @@ -315,13 +321,19 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + self.instantiate_with(run, granted, report, self.limits.fuel_base) + } + + /// [`Plugin::instantiate`] with the start function given at most `start_fuel` instructions; + /// the instance's store holds what it left. + fn instantiate_with(&self, run: Run, granted: &[Permission], report: &mut Report, start_fuel: u64) -> Result { let limits = StoreLimitsBuilder::new().memory_size(self.limits.max_memory_bytes).memories(1).tables(4).table_elements(100_000).instances(1).build(); let mut store = Store::new(&self.engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. - store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; + store.set_fuel(start_fuel.min(FUEL_SLICE)).map_err(wasm_err)?; let linker = host::linker(&self.engine, granted); let instance = match linker.instantiate_and_start(&mut store, &self.module) { Ok(instance) => instance, @@ -360,16 +372,34 @@ impl Plugin { params: P, fuel: u64, deadline: &Deadline, + bridge: Option<&mut Bridge<'_>>, + ) -> Result { + let mut budget = fuel; + self.call_budget(live, f, params, &mut budget, deadline, bridge) + } + + /// [`Plugin::call_with`] on at most `budget` instructions, which holds what the call left + /// unused when it returns `Ok`, for the next call to share. + fn call_budget( + &self, + live: &mut Live, + f: &TypedFunc, + params: P, + budget: &mut u64, + deadline: &Deadline, mut bridge: Option<&mut Bridge<'_>>, ) -> Result { - let mut left = fuel; + let mut left = *budget; let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { - TypedResumableCall::Finished(r) => return Ok(r), + TypedResumableCall::Finished(r) => { + *budget = left.saturating_add(live.store.get_fuel().map_err(wasm_err)?); + return Ok(r); + } TypedResumableCall::HostTrap(inv) => { if inv.host_error().downcast_ref::().is_some() { return Err(stop_reason(&mut live.store)); @@ -505,4 +535,72 @@ impl Plugin { } live.read_packed(packed, "the output", limits.max_output_bytes) } + + /// Its limits for one event handler: at most [`crate::events::EVENT_FUEL`] instructions and + /// [`crate::events::EVENT_WALL_TIME_MS`], or its own budgets when they are smaller, and every + /// other limit as it is. + pub fn event_limits(&self) -> Limits { + Limits { + fuel_base: self.limits.fuel_base.min(crate::events::EVENT_FUEL), + wall_time_ms: self.limits.wall_time_ms.min(crate::events::EVENT_WALL_TIME_MS), + ..self.limits.clone() + } + } + + /// Calls `vc_event` with `event` (the event JSON) in a fresh instance under + /// [`Plugin::event_limits`] → `Ok` when it returned 0, and what it reported through the host + /// imports. With `bridge`, each `vc_call` of a command its `commandAllowlist` names is made with + /// it; a failed call fails the handler. A module that doesn't react to events, an event past + /// [`crate::events::MAX_EVENT_BYTES`] and Safe Mode run nothing. + pub fn run_event(&self, event: &[u8], bridge: Option<&mut Bridge<'_>>) -> (Result<()>, Report) { + let mut report = Report::default(); + if let Err(e) = crate::safe_mode::check() { + return (Err(e), report); + } + if self.manifest.events.is_empty() { + return (Err(Error::Abi("the module reacts to no events".into())), report); + } + if event.len() > crate::events::MAX_EVENT_BYTES { + let (len, max) = (event.len(), crate::events::MAX_EVENT_BYTES); + return (Err(Error::Limit(format!("event size ({len} bytes, limit {max})"))), report); + } + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.event_inner(event, &mut report, bridge))); + (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) + } + + fn event_inner(&self, event: &[u8], report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result<()> { + let limits = self.event_limits(); + let deadline = Deadline::new(limits.wall_time_ms); + let m = &self.manifest; + let run = Run::new(&m.id, false, true, deadline).with_storage(crate::registry::storage(&m.id)); + let mut live = self.instantiate_with(run, &m.permissions(), report, limits.fuel_base)?; + // The start function, `vc_alloc` and `vc_event` share the one budget. + let mut budget = live.store.get_fuel().map_err(wasm_err)?; + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = (|| { + let alloc: TypedFunc = live.func("vc_alloc")?; + let handler: TypedFunc = live.func("vc_event")?; + let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; + if ptr == 0 { + return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); + } + let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); + let end = ptr.checked_add(event.len()).ok_or_else(outside)?; + live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; + deadline.check()?; + if code != 0 { + return Err(Error::Failed(format!("vc_event returned {code}"))); + } + Ok(()) + })(); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + match (state.call_failure.take(), out) { + (Some(e), _) => Err(e), + (None, out) => out, + } + } } diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 936d5d9e53..a1348242d7 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -34,6 +34,18 @@ pub fn module(manifest: &str, run: &str, extra: &str, pages: u32) -> String { /// A `vc_run` body returning the input unchanged. pub const ECHO: &str = "(i64.or (i64.shl (i64.extend_i32_u (local.get $il)) (i64.const 32)) (i64.extend_i32_u (local.get $in)))"; +/// A plug-in that reacts to events ([`crate::events`]): `manifest` (JSON that lists `events`), the +/// module fields `imports` before the others, a `vc_event` whose body is `handler` (parameters +/// `$ep $el`, result i32) and a `vc_run` that returns its input. +pub fn reacting(manifest: &str, imports: &str, handler: &str) -> String { + let extra = format!(r#"{imports} (func (export "vc_event") (param $ep i32) (param $el i32) (result i32) {handler})"#); + module(manifest, ECHO, &extra, 1) +} + +/// A `vc_event` body that writes the event it is given as an information log line (with +/// [`HOST_IMPORTS`]) and returns 0. +pub const LOG_EVENT: &str = "(drop (call $vc_log (i32.const 2) (local.get $ep) (local.get $el))) (i32.const 0)"; + /// A plug-in that always returns `output` (whatever it is given). pub fn returning(manifest: &str, output: &str) -> String { then_returning(manifest, "", output) diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index f4cb2e103b..bb28afd450 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1025,6 +1025,79 @@ fn a_plugin_reaches_only_its_own_storage() { registry::set_storage("test.storage.theirs", None); } +/// The manifest of an event plug-in `id` that writes log lines and reacts to `events` (JSON list). +fn reacting_manifest(id: &str, events: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["progress","events"],"events":{events}}}"#) +} + +/// A module that lists `events` needs a `vc_event` export of the right type; one that lists none +/// may leave it out. +#[test] +fn an_event_plugin_exports_vc_event() { + let manifest = reacting_manifest("test.events.export", r#"["selection.changed"]"#); + let e = Plugin::load(&build(&tpl::reporting(&manifest, "", INPUT)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let wrong = format!(r#"{} (func (export "vc_event") (param i32) (result i32) (i32.const 0))"#, tpl::HOST_IMPORTS); + let e = Plugin::load(&build(&tpl::module(&manifest, tpl::ECHO, &wrong, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); + assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); +} + +/// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a +/// handler past its instruction budget fail it. A module without events runs no handler. +#[test] +fn vc_event_is_given_the_event_and_its_code_is_checked() { + let manifest = reacting_manifest("test.events.run", r#"["layer.changed"]"#); + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).unwrap(); + let event = br#"{"type":"layer.changed","document":7}"#; + let (r, report) = p.run_event(event, None); + r.unwrap(); + assert_eq!(report.lines.iter().map(|l| l.text.as_str()).collect::>(), [std::str::from_utf8(event).unwrap()]); + for (handler, says) in [ + ("(i32.const 3)", "vc_event returned 3"), + ("unreachable", "trapped"), + // The instruction budget, or the time budget on a loaded machine. + ("(loop $l (br $l)) (i32.const 0)", "budget"), + ] { + let p = Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, handler)), Limits::default()).unwrap(); + let e = p.run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains(says), "{handler}: {e}"); + } + let e = p.run_event(&vec![b' '; vectorcraft_plugins::events::MAX_EVENT_BYTES + 1], None).0.unwrap_err(); + assert!(e.to_string().contains("event size"), "{e}"); + let plain = Plugin::load(&ok_module(tpl::ECHO), Limits::default()).unwrap(); + assert!(plain.run_event(event, None).0.is_err()); + let limits = p.event_limits(); + assert_eq!((limits.fuel_base, limits.wall_time_ms), (vectorcraft_plugins::events::EVENT_FUEL, vectorcraft_plugins::events::EVENT_WALL_TIME_MS)); +} + +/// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the +/// handler alone fits it no longer when the start function has done as much first. +#[test] +fn a_handler_and_its_start_function_share_the_event_budget() { + let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); + let burn = r#"(func $burn (param $k i32) (block $b (loop $l + (br_if $b (i32.eqz (local.get $k))) + (local.set $k (i32.sub (local.get $k) (i32.const 1))) + (br $l))))"#; + let plugin = |start: u32, handler: u32| { + let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); + let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + }; + let event = br#"{"type":"layer.changed","document":1}"#; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. + let mut k = 1u32 << 16; + while plugin(0, k * 2).run_event(event, None).0.is_ok() { + k *= 2; + assert!(k < 1 << 30, "a handler that never runs out of its budget"); + } + assert!(plugin(0, k).run_event(event, None).0.is_ok()); + let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); + assert!(e.contains("budget"), "{e}"); +} + /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped /// and reported. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..79296d8b40 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -55,6 +55,9 @@ impl VectorcraftApp { session.place_cursor_requests = true; // A script runs a slice per frame, so the window keeps drawing and Stop can be pressed. session.script_frames = true; + // Plug-in events are delivered by the frame: after the work that finished in the + // background, and at the end of the UI pass ([`VectorcraftApp::deliver_plugin_events`]). + session.plugin_event_frames = true; let views = session.documents().iter().map(View::of).collect(); let view_uids = session.documents().iter().map(|d| d.uid).collect(); let known = session.documents().iter().map(|d| d.uid).collect(); @@ -270,6 +273,25 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + let _ = self.deliver_plugin_events(); + } + + /// Hands the plug-ins that react to events the changes of this frame + /// ([`vectorcraft_engine::Session::deliver_plugin_events`]). The last warning or error a handler + /// wrote, or the last handler failure, shows in the status bar after the plug-in's name. → Whether + /// the status bar shows one. + fn deliver_plugin_events(&mut self) -> bool { + self.session.deliver_plugin_events(); + let shown = self + .session + .take_plugin_event_notices() + .into_iter() + .rev() + .find(|n| matches!(n.level, vectorcraft_plugins::LogLevel::Error | vectorcraft_plugins::LogLevel::Warn)); + let Some(n) = shown else { return false }; + let name = vectorcraft_plugins::permissions::display_text(&n.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + self.status(format!("{name}: {}", n.text)); + true } /// The language the UI is drawn in: the Preferences dialog's choice while it is open (so a @@ -362,8 +384,14 @@ impl VectorcraftApp { // them, even if the worker below finishes them during this same tick. ctx.data_mut(|d| d.insert_temp(egui::Id::unique("clipboard.pending-at-tick"), self.clipboard_publishing.is_pending())); screen_color::poll(self, ctx); + let script_was_running = self.session.script_running(); self.poll_finished_work(); crate::script_runs::poll(self); + if script_was_running && !self.session.script_running() { + // The work that waited for the script, and the plug-in events its changes give, are + // taken in the frame it ended in: no repaint is asked for once it has ended. + self.poll_finished_work(); + } // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); @@ -670,6 +698,12 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the UI phase's input flush. Publish it now for the same reason as there. self.flush_clipboard_out(&ctx); + // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react + // to it now, since an idle app draws no further frame; a line a handler wrote shows in the + // next one. + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } if opening::long_operation_busy(self) { ctx.set_cursor_icon(egui::CursorIcon::Progress); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..0f4fb39940 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + events: Vec::new(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..4014b51fc8 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6690,6 +6690,7 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите + Run on its own when the selection, a document or a layer changes Изпълняване самостоятелно, когато се промени селекцията, документ или слой Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..84fecd5884 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6718,6 +6718,7 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti + Run on its own when the selection, a document or a layer changes Pokretati se samostalno kada se promijeni odabir, dokument ili sloj Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..f2a186f792 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7842,6 +7842,7 @@ variable-list-end {0}, {1} {0} i {1} Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar + Run on its own when the selection, a document or a layer changes Executar-se per si sol quan canvia la selecció, un document o una capa Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7873,6 +7874,15 @@ variable-list-end {0}, {1} {0} i {1} @msg only a filter declares `inputs` només un filtre declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades +@msg `events` lists `{shown}` twice `events` inclou `{shown}` dues vegades +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anomena un esdeveniment desconegut `{shown}`: feu servir selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necessita el nivell d’API de complements {EVENTS_API}: indiqueu `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necessita el permís `events`, i `events` necessita una llista d’`events` +@msg event size ({len} bytes, limit {max}) mida de l’esdeveniment ({len} bytes, límit {max}) +@msg the module reacts to no events el mòdul no reacciona a cap esdeveniment +@msg vc_event returned {code} vc_event ha retornat {code} +@msg {name}: its {event} handler failed: {e} {name}: el seu gestor de {event} ha fallat: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: els seus esdeveniments estan desactivats fins que VectorCraft torni a iniciar-se, després de {count} gestors fallits seguits @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) pressupost de memòria (l’objecte {_1} necessita {size} bytes d’entrada, en queden {left}) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..394d8b42a7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7452,6 +7452,7 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat + Run on its own when the selection, a document or a layer changes Spouštět se samostatně, když se změní výběr, dokument nebo vrstva Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7483,6 +7484,15 @@ axis Y Axis osa Y @msg only a filter declares `inputs` `inputs` deklaruje pouze filtr @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát +@msg `events` lists `{shown}` twice `events` uvádí `{shown}` dvakrát +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` uvádí neznámou událost `{shown}`: použijte selection.changed, document.opened, document.saved nebo layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vyžaduje úroveň API zásuvných modulů {EVENTS_API}: uveďte `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potřebuje oprávnění `events` a `events` potřebuje seznam `events` +@msg event size ({len} bytes, limit {max}) velikost události ({len} bajtů, limit {max}) +@msg the module reacts to no events modul nereaguje na žádné události +@msg vc_event returned {code} vc_event vrátila {code} +@msg {name}: its {event} handler failed: {e} {name}: jeho obslužná rutina {event} selhala: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jeho události jsou vypnuté, dokud se VectorCraft znovu nespustí, po {count} neúspěšných obslužných rutinách za sebou @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) rozpočet paměti (objekt {_1} potřebuje {size} bajtů vstupu, zbývá {left}) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..b8415a4299 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -695,6 +695,15 @@ liquify-list-end {0}, {1} {0} og {1} @msg only a filter declares `inputs` kun et filter angiver `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange +@msg `events` lists `{shown}` twice `events` angiver `{shown}` to gange +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` angiver en ukendt hændelse `{shown}`: brug selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kræver plug-in-API-niveau {EVENTS_API}: angiv `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` kræver tilladelsen `events`, og `events` kræver en liste `events` +@msg event size ({len} bytes, limit {max}) hændelsesstørrelse ({len} byte, grænse {max}) +@msg the module reacts to no events modulet reagerer ikke på nogen hændelser +@msg vc_event returned {code} vc_event returnerede {code} +@msg {name}: its {event} handler failed: {e} {name}: dens {event}-handler mislykkedes: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dens hændelser er slået fra, indtil VectorCraft starter igen, efter {count} mislykkede handlere i træk @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) @@ -9609,6 +9618,7 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde + Run on its own when the selection, a document or a layer changes Køre af sig selv, når markeringen, et dokument eller et lag ændres Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..99a8424807 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7035,6 +7035,7 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können + Run on its own when the selection, a document or a layer changes Von selbst ausgeführt werden, wenn sich die Auswahl, ein Dokument oder eine Ebene ändert Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7066,6 +7067,15 @@ axis Y Axis Y-Achse @msg only a filter declares `inputs` nur ein Filter deklariert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf +@msg `events` lists `{shown}` twice `events` führt `{shown}` doppelt auf +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nennt ein unbekanntes Ereignis `{shown}`: verwenden Sie selection.changed, document.opened, document.saved oder layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` braucht die Plug-in-API-Stufe {EVENTS_API}: Geben Sie `api` {EVENTS_API} an +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` braucht die Berechtigung `events`, und `events` braucht eine Liste `events` +@msg event size ({len} bytes, limit {max}) Ereignisgröße ({len} Byte, Grenze {max}) +@msg the module reacts to no events das Modul reagiert auf keine Ereignisse +@msg vc_event returned {code} vc_event hat {code} zurückgegeben +@msg {name}: its {event} handler failed: {e} {name}: sein Handler für {event} ist fehlgeschlagen: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seine Ereignisse sind aus, bis VectorCraft neu startet, nach {count} fehlgeschlagenen Handlern in Folge @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) Speicherbudget (Objekt {_1} benötigt {size} Byte Eingabe, {left} verbleiben) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..34be251bb2 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7442,6 +7442,7 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε + Run on its own when the selection, a document or a layer changes Εκτέλεση από μόνο του όταν αλλάζει η επιλογή, ένα έγγραφο ή ένα επίπεδο Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7473,6 +7474,15 @@ axis Y Axis Άξονας Y @msg only a filter declares `inputs` μόνο ένα φίλτρο δηλώνει `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance το `inputs` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές +@msg `events` lists `{shown}` twice το `events` αναφέρει το `{shown}` δύο φορές +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed το `events` αναφέρει άγνωστο συμβάν `{shown}`: χρησιμοποιήστε selection.changed, document.opened, document.saved ή layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} το `events` χρειάζεται το επίπεδο API προσθέτων {EVENTS_API}: δώστε `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` το `events` χρειάζεται το δικαίωμα `events`, και το `events` χρειάζεται μια λίστα `events` +@msg event size ({len} bytes, limit {max}) μέγεθος συμβάντος ({len} byte, όριο {max}) +@msg the module reacts to no events η λειτουργική μονάδα δεν αντιδρά σε κανένα συμβάν +@msg vc_event returned {code} η vc_event επέστρεψε {code} +@msg {name}: its {event} handler failed: {e} {name}: ο χειριστής {event} του απέτυχε: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: τα συμβάντα του είναι απενεργοποιημένα μέχρι να ξεκινήσει ξανά το VectorCraft, μετά από {count} αποτυχημένους χειριστές στη σειρά @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) προϋπολογισμός μνήμης (το αντικείμενο {_1} χρειάζεται {size} byte εισόδου, απομένουν {left}) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..3e8a481554 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7428,6 +7428,7 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar + Run on its own when the selection, a document or a layer changes Ejecutarse por sí solo cuando cambia la selección, un documento o una capa Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7459,6 +7460,15 @@ axis Y Axis Eje Y @msg only a filter declares `inputs` solo un filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces +@msg `events` lists `{shown}` twice `events` incluye `{shown}` dos veces +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nombra un evento desconocido `{shown}`: use selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` necesita el nivel de API de plugins {EVENTS_API}: indique `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` necesita el permiso `events`, y `events` necesita una lista de `events` +@msg event size ({len} bytes, limit {max}) tamaño del evento ({len} bytes, límite {max}) +@msg the module reacts to no events el módulo no reacciona a ningún evento +@msg vc_event returned {code} vc_event devolvió {code} +@msg {name}: its {event} handler failed: {e} {name}: su controlador de {event} falló: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sus eventos están desactivados hasta que VectorCraft se inicie de nuevo, tras {count} controladores fallidos seguidos @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) presupuesto de memoria (el objeto {_1} necesita {size} bytes de entrada, quedan {left}) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..8324910fae 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7519,6 +7519,7 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää + Run on its own when the selection, a document or a layer changes Käynnistyä itsestään, kun valinta, asiakirja tai taso muuttuu Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7550,6 +7551,15 @@ axis Y Axis Y-akseli @msg only a filter declares `inputs` vain suodatin voi määrittää `inputs`-avaimen @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti +@msg `events` lists `{shown}` twice `events` luettelee kohteen `{shown}` kahdesti +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nimeää tuntemattoman tapahtuman `{shown}`: käytä arvoa selection.changed, document.opened, document.saved tai layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vaatii laajennus-API:n tason {EVENTS_API}: anna `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` tarvitsee käyttöoikeuden `events`, ja `events` tarvitsee `events`-luettelon +@msg event size ({len} bytes, limit {max}) tapahtuman koko ({len} tavua, raja {max}) +@msg the module reacts to no events moduuli ei reagoi mihinkään tapahtumaan +@msg vc_event returned {code} vc_event palautti {code} +@msg {name}: its {event} handler failed: {e} {name}: sen {event}-käsittelijä epäonnistui: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: sen tapahtumat ovat pois päältä, kunnes VectorCraft käynnistyy uudelleen, {count} peräkkäin epäonnistuneen käsittelijän jälkeen @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) muistibudjetti (objekti {_1} tarvitsee {size} tavua syötettä, jäljellä {left}) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..84b857b264 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7448,6 +7448,7 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider + Run on its own when the selection, a document or a layer changes S’exécuter de lui-même quand la sélection, un document ou un calque change Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler @msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} @@ -7480,6 +7481,15 @@ axis Y Axis Axe Y @msg only a filter declares `inputs` seul un filtre déclare `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois +@msg `events` lists `{shown}` twice `events` mentionne `{shown}` deux fois +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` désigne un événement inconnu `{shown}`, utilisez selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` nécessite le niveau d’API de module externe {EVENTS_API}, indiquez `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` a besoin de l’autorisation `events`, et `events` a besoin d’une liste `events` +@msg event size ({len} bytes, limit {max}) taille de l’événement ({len} octets, limite {max}) +@msg the module reacts to no events le module ne réagit à aucun événement +@msg vc_event returned {code} vc_event a renvoyé {code} +@msg {name}: its {event} handler failed: {e} {name} : son gestionnaire {event} a échoué : {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name} : ses événements sont désactivés jusqu’au prochain démarrage de VectorCraft, après {count} gestionnaires en échec d’affilée @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget mémoire (l’objet {_1} nécessite {size} octets d’entrée, il en reste {left}) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..69e14c4fd3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2023,6 +2023,7 @@ Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો Keep a cache of its own, which you can clear તેનું પોતાનું કેશ રાખો, જે તમે સાફ કરી શકો છો + Run on its own when the selection, a document or a layer changes પસંદગી, દસ્તાવેજ અથવા લેયર બદલાય ત્યારે આપમેળે ચાલો Keep a link to an image file instead of only embedding it ઇમેજ ફાઇલને ફક્ત એમ્બેડ કરવાને બદલે તેની લિંક રાખો Keep both sides the same width બંને બાજુ સમાન પહોળાઈ રાખો Keep data of its own with the document દસ્તાવેજ સાથે પોતાનો ડેટા રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..e068bda2aa 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6636,6 +6636,7 @@ arrowhead Feather पंख Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं + Run on its own when the selection, a document or a layer changes सिलेक्शन, कोई डॉक्यूमेंट या कोई लेयर बदलने पर अपने आप चलना Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -6667,6 +6668,15 @@ arrowhead Feather पंख @msg only a filter declares `inputs` केवल फ़िल्टर `inputs` घोषित करता है @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है +@msg `events` lists `{shown}` twice `events` में `{shown}` दो बार सूचीबद्ध है +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` में अज्ञात इवेंट `{shown}` है: selection.changed, document.opened, document.saved या layer.changed का उपयोग करें +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` के लिए प्लग-इन API स्तर {EVENTS_API} चाहिए: `api` {EVENTS_API} दें +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` को `events` अनुमति चाहिए, और `events` को `events` की सूची चाहिए +@msg event size ({len} bytes, limit {max}) इवेंट का आकार ({len} बाइट्स, सीमा {max}) +@msg the module reacts to no events मॉड्यूल किसी भी इवेंट पर प्रतिक्रिया नहीं करता +@msg vc_event returned {code} vc_event ने {code} लौटाया +@msg {name}: its {event} handler failed: {e} {name}: इसका {event} हैंडलर विफल हुआ: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: लगातार {count} हैंडलर विफल होने के बाद, VectorCraft के फिर से शुरू होने तक इसके इवेंट बंद हैं @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है @msg memory budget (object {_1} needs {size} bytes of input, {left} left) मेमोरी बजट (ऑब्जेक्ट {_1} को इनपुट के {size} बाइट चाहिए, {left} शेष हैं) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..d2eaaf10b8 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7437,6 +7437,7 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet + Run on its own when the selection, a document or a layer changes Magától futhat, amikor a kijelölés, egy dokumentum vagy egy réteg megváltozik Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7468,6 +7469,15 @@ axis Y Axis Y tengely @msg only a filter declares `inputs` `inputs` kulcsot csak szűrő adhat meg @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance az `inputs` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` +@msg `events` lists `{shown}` twice az `events` kétszer sorolja fel ezt: `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed az `events` ismeretlen eseményt nevez meg: `{shown}`; használja a selection.changed, document.opened, document.saved vagy layer.changed értéket +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} az `events` listához {EVENTS_API}. szintű bővítmény-API kell: adja meg az `api` {EVENTS_API} értéket +@msg `events` needs the permission `events`, and `events` needs a list of `events` az `events` listához az `events` engedély szükséges, az `events` engedélyhez pedig `events` lista +@msg event size ({len} bytes, limit {max}) esemény mérete ({len} bájt, korlát {max}) +@msg the module reacts to no events a modul egyetlen eseményre sem reagál +@msg vc_event returned {code} a vc_event {code} értéket adott vissza +@msg {name}: its {event} handler failed: {e} {name}: a(z) {event} kezelője sikertelen volt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: az eseményei ki vannak kapcsolva a VectorCraft következő indításáig, {count} egymást követő sikertelen kezelő után @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges @msg memory budget (object {_1} needs {size} bytes of input, {left} left) memóriakeret (a(z) {_1} objektumnak {size} bájt bemenet kell, {left} maradt) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..936f46e0ad 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -577,6 +577,15 @@ @msg only a filter declares `inputs` hanya filter yang mendeklarasikan `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali +@msg `events` lists `{shown}` twice `events` mencantumkan `{shown}` dua kali +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` menyebut peristiwa yang tidak dikenal `{shown}`: gunakan selection.changed, document.opened, document.saved atau layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` memerlukan API plug-in tingkat {EVENTS_API}: berikan `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` memerlukan izin `events`, dan `events` memerlukan daftar `events` +@msg event size ({len} bytes, limit {max}) ukuran peristiwa ({len} byte, batas {max}) +@msg the module reacts to no events modul tidak bereaksi terhadap peristiwa apa pun +@msg vc_event returned {code} vc_event mengembalikan {code} +@msg {name}: its {event} handler failed: {e} {name}: handler {event}-nya gagal: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: event-nya dimatikan hingga VectorCraft dimulai lagi, setelah {count} handler gagal berturut-turut @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) anggaran memori (objek {_1} memerlukan {size} byte masukan, tersisa {left}) @@ -7394,6 +7403,7 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan + Run on its own when the selection, a document or a layer changes Berjalan sendiri saat seleksi, dokumen, atau lapisan berubah Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c3fbb39ac9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare + Run on its own when the selection, a document or a layer changes Eseguirsi da solo quando cambia la selezione, un documento o un livello Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Asse Y @msg only a filter declares `inputs` solo un filtro dichiara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte +@msg `events` lists `{shown}` twice `events` elenca `{shown}` due volte +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` indica un evento sconosciuto `{shown}`: usa selection.changed, document.opened, document.saved o layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` richiede il livello API dei plug-in {EVENTS_API}: indicare `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` richiede l’autorizzazione `events`, e `events` richiede un elenco `events` +@msg event size ({len} bytes, limit {max}) dimensione dell’evento ({len} byte, limite {max}) +@msg the module reacts to no events il modulo non reagisce ad alcun evento +@msg vc_event returned {code} vc_event ha restituito {code} +@msg {name}: its {event} handler failed: {e} {name}: il suo gestore di {event} non è riuscito: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: i suoi eventi sono disattivati finché VectorCraft non si riavvia, dopo {count} gestori non riusciti di fila @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budget di memoria (l’oggetto {_1} richiede {size} byte di input, ne restano {left}) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..f505fe6e6a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7149,6 +7149,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 + Run on its own when the selection, a document or a layer changes 選択、ドキュメント、またはレイヤーが変わったときの自動実行 Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7180,6 +7181,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` `inputs` を宣言できるのはフィルターだけです @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています +@msg `events` lists `{shown}` twice `events` に `{shown}` が 2 回指定されています +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` に不明なイベント `{shown}` があります。selection.changed、document.opened、document.saved、layer.changed のいずれかを使ってください +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` にはプラグイン API レベル {EVENTS_API} が必要です。`api` {EVENTS_API} を指定してください +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` には権限 `events` が必要で、`events` には `events` のリストが必要です +@msg event size ({len} bytes, limit {max}) イベントサイズ ({len} バイト、上限 {max}) +@msg the module reacts to no events このモジュールはどのイベントにも反応しません +@msg vc_event returned {code} vc_event が {code} を返しました +@msg {name}: its {event} handler failed: {e} {name}: {event} のハンドラーが失敗しました: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: ハンドラーが {count} 回続けて失敗したため、VectorCraft を再起動するまでイベントはオフです @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です @msg memory budget (object {_1} needs {size} bytes of input, {left} left) メモリ予算 (オブジェクト {_1} には {size} バイトの入力が必要ですが、残りは {left} です) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..4f8df8bba8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9555,6 +9555,7 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ + Run on its own when the selection, a document or a layer changes თავისით გაშვება, როცა იცვლება მონიშნული, დოკუმენტი ან შრე Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -9586,6 +9587,15 @@ axis Y Axis Y ღერძი @msg only a filter declares `inputs` `inputs`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` lists `{shown}` twice `events`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` უცნობ მოვლენას ასახელებს `{shown}`: გამოიყენეთ selection.changed, document.opened, document.saved ან layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`-ს სჭირდება პლაგინის API-ის დონე {EVENTS_API}: მიუთითეთ `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`-ს სჭირდება ნებართვა `events`, ხოლო `events`-ს სჭირდება `events`-ის სია +@msg event size ({len} bytes, limit {max}) მოვლენის ზომა ({len} ბაიტი, ლიმიტი {max}) +@msg the module reacts to no events მოდული არცერთ მოვლენაზე არ რეაგირებს +@msg vc_event returned {code} vc_event-მა დააბრუნა {code} +@msg {name}: its {event} handler failed: {e} {name}: მისი {event} დამმუშავებელი ვერ შესრულდა: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: მისი მოვლენები გამორთულია VectorCraft-ის ხელახლა გაშვებამდე, ზედიზედ {count} წარუმატებელი დამმუშავებლის შემდეგ @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) მეხსიერების ბიუჯეტი (ობიექტს {_1} სჭირდება შეყვანის {size} ბაიტი, დარჩენილია {left}) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..684c27a922 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7046,6 +7046,7 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 + Run on its own when the selection, a document or a layer changes 선택 영역, 문서 또는 레이어가 바뀔 때 자동 실행 Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7077,6 +7078,15 @@ axis Y Axis Y축 @msg only a filter declares `inputs` 필터만 `inputs`를 선언할 수 있습니다 @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` lists `{shown}` twice `events`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events`에 알 수 없는 이벤트 `{shown}`이(가) 있습니다. selection.changed, document.opened, document.saved 또는 layer.changed를 사용하세요 +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events`에는 플러그인 API 수준 {EVENTS_API}이(가) 필요합니다. `api` {EVENTS_API}을(를) 지정하십시오 +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events`에는 `events` 권한이 필요하고, `events`에는 `events` 목록이 필요합니다 +@msg event size ({len} bytes, limit {max}) 이벤트 크기({len}바이트, 제한 {max}) +@msg the module reacts to no events 이 모듈은 어떤 이벤트에도 반응하지 않습니다 +@msg vc_event returned {code} vc_event가 {code}을(를) 반환했습니다 +@msg {name}: its {event} handler failed: {e} {name}: {event} 처리기가 실패했습니다: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: 처리기가 {count}번 연속 실패하여 VectorCraft를 다시 시작할 때까지 이벤트가 꺼집니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 메모리 예산(개체 {_1}에 입력 {size}바이트가 필요하지만 {left}바이트 남음) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..685d671ff7 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -541,6 +541,15 @@ liquify-list-end {0}, {1} {0} en {1} @msg only a filter declares `inputs` alleen een filter declareert `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` noemt een onbekend objectsoort `{shown}`: gebruik type, image of symbolInstance @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer +@msg `events` lists `{shown}` twice `events` noemt `{shown}` twee keer +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` noemt een onbekende gebeurtenis `{shown}`: gebruik selection.changed, document.opened, document.saved of layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` vereist plug-in-API-niveau {EVENTS_API}: geef `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` vereist de machtiging `events`, en `events` vereist een lijst `events` +@msg event size ({len} bytes, limit {max}) gebeurtenisgrootte ({len} bytes, limiet {max}) +@msg the module reacts to no events de module reageert op geen enkele gebeurtenis +@msg vc_event returned {code} vc_event gaf {code} terug +@msg {name}: its {event} handler failed: {e} {name}: de handler voor {event} is mislukt: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: de gebeurtenissen staan uit tot VectorCraft opnieuw start, na {count} mislukte handlers op rij @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) geheugenbudget (object {_1} heeft {size} bytes invoer nodig, {left} over) @@ -9447,6 +9456,7 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen + Run on its own when the selection, a document or a layer changes Vanzelf worden uitgevoerd wanneer de selectie, een document of een laag verandert Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..f38ee32d93 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7307,6 +7307,7 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić + Run on its own when the selection, a document or a layer changes Uruchamiać się samodzielnie, gdy zmieni się zaznaczenie, dokument lub warstwa Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7338,6 +7339,15 @@ axis Y Axis Oś Y @msg only a filter declares `inputs` tylko filtr deklaruje `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy +@msg `events` lists `{shown}` twice `events` wymienia `{shown}` dwa razy +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` wymienia nieznane zdarzenie `{shown}`: użyj selection.changed, document.opened, document.saved lub layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` wymaga poziomu API wtyczek {EVENTS_API}: podaj `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` potrzebuje uprawnienia `events`, a `events` potrzebuje listy `events` +@msg event size ({len} bytes, limit {max}) rozmiar zdarzenia ({len} bajtów, limit {max}) +@msg the module reacts to no events moduł nie reaguje na żadne zdarzenia +@msg vc_event returned {code} vc_event zwróciła {code} +@msg {name}: its {event} handler failed: {e} {name}: jego procedura obsługi {event} nie powiodła się: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: jego zdarzenia są wyłączone do ponownego uruchomienia VectorCraft, po {count} nieudanych procedurach obsługi z rzędu @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) budżet pamięci (obiekt {_1} wymaga {size} bajtów danych wejściowych, pozostało {left}) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..71dc272146 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7351,6 +7351,7 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar + Run on its own when the selection, a document or a layer changes Executar-se sozinho quando a seleção, um documento ou uma camada muda Run these commands on the document: {ids} Executar estes comandos no documento: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7382,6 +7383,15 @@ axis Y Axis Eixo Y @msg only a filter declares `inputs` somente um filtro declara `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes +@msg `events` lists `{shown}` twice `events` lista `{shown}` duas vezes +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` cita um evento desconhecido `{shown}`: use selection.changed, document.opened, document.saved ou layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` exige o nível de API de plug-in {EVENTS_API}: informe `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` precisa da permissão `events`, e `events` precisa de uma lista de `events` +@msg event size ({len} bytes, limit {max}) tamanho do evento ({len} bytes, limite {max}) +@msg the module reacts to no events o módulo não reage a nenhum evento +@msg vc_event returned {code} vc_event retornou {code} +@msg {name}: its {event} handler failed: {e} {name}: seu manipulador de {event} falhou: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: seus eventos estão desativados até o VectorCraft iniciar de novo, após {count} manipuladores com falha seguidos @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) orçamento de memória (o objeto {_1} precisa de {size} bytes de entrada, restam {left}) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..da28f599bf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7074,6 +7074,7 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить + Run on its own when the selection, a document or a layer changes Запускаться самостоятельно, когда меняется выделение, документ или слой Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7105,6 +7106,15 @@ axis Y Axis Ось Y @msg only a filter declares `inputs` `inputs` может объявлять только фильтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды +@msg `events` lists `{shown}` twice в `events` `{shown}` указано дважды +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано неизвестное событие `{shown}`: используйте selection.changed, document.opened, document.saved или layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` нужен уровень API модулей {EVENTS_API}: укажите `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` нужно разрешение `events`, а для `events` нужен список `events` +@msg event size ({len} bytes, limit {max}) размер события ({len} байт, предел {max}) +@msg the module reacts to no events модуль не реагирует ни на какие события +@msg vc_event returned {code} vc_event вернула {code} +@msg {name}: its {event} handler failed: {e} {name}: его обработчик {event} завершился ошибкой: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: его события отключены до следующего запуска VectorCraft после {count} неудачных обработчиков подряд @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет памяти (объекту {_1} нужно {size} байт входных данных, осталось {left}) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..c83e6ef5f1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7464,6 +7464,7 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma + Run on its own when the selection, a document or a layer changes Köras av sig själv när markeringen, ett dokument eller ett lager ändras Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7495,6 +7496,15 @@ axis Y Axis Y-axel @msg only a filter declares `inputs` bara ett filter anger `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger +@msg `events` lists `{shown}` twice `events` anger `{shown}` två gånger +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` anger en okänd händelse `{shown}`: använd selection.changed, document.opened, document.saved eller layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` kräver plugin-API-nivå {EVENTS_API}: ange `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` behöver behörigheten `events`, och `events` behöver en lista `events` +@msg event size ({len} bytes, limit {max}) händelsestorlek ({len} byte, gräns {max}) +@msg the module reacts to no events modulen reagerar inte på några händelser +@msg vc_event returned {code} vc_event returnerade {code} +@msg {name}: its {event} handler failed: {e} {name}: dess {event}-hanterare misslyckades: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: dess händelser är avstängda tills VectorCraft startas igen, efter {count} misslyckade hanterare i rad @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) minnesbudget (objekt {_1} behöver {size} byte indata, {left} återstår) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..679e207708 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -949,6 +949,33 @@ fn artboard_add_button_tooltips_are_in_complete_catalogs() { } } +/// Install Plug-in… lists what each permission lets a plug-in do, so each complete catalog has a +/// row for the `events` permission's words. +#[test] +fn plugin_events_permission_words_are_in_complete_catalogs() { + let label = "Run on its own when the selection, a document or a layer changes"; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus || COMPLETE_MESSAGES.contains(&lang.code)) { + assert!(lang.catalog().plain(label).is_some_and(|t| !t.is_empty() && t != label), "{} is missing {label}", lang.code); + } +} + +/// The status bar's lines for a plug-in whose event handler failed, which the engine writes after +/// the plug-in's name, are translated in each language of [`COMPLETE_MESSAGES`]. +#[test] +fn plugin_event_handler_failures_are_translated() { + let failed = "Run Events: its selection.changed handler failed: vc_event returned 3"; + let off = "Run Events: its events are off until VectorCraft starts again, after 3 failed handlers in a row"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in [failed, off] { + let shown = message(lang, s); + assert!(shown != s && shown.starts_with("Run Events") && shown.contains('3'), "{code}: {shown}"); + } + } + assert_eq!(message(de(), failed), "Run Events: sein Handler für selection.changed ist fehlgeschlagen: vc_event hat 3 zurückgegeben"); + assert_eq!(message(de(), off), "Run Events: seine Ereignisse sind aus, bis VectorCraft neu startet, nach 3 fehlgeschlagenen Handlern in Folge"); +} + /// Preferences › Performance › Use Monitor Profile for Canvas and the note under it. #[test] fn monitor_profile_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..5beaea8907 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7524,6 +7524,7 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama + Run on its own when the selection, a document or a layer changes Seçim, bir belge veya bir katman değiştiğinde kendiliğinden çalışma Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7555,6 +7556,15 @@ axis Y Axis Y ekseni @msg only a filter declares `inputs` `inputs` yalnızca bir filtrede bildirilebilir @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor +@msg `events` lists `{shown}` twice `events` `{shown}` değerini iki kez listeliyor +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` bilinmeyen bir olay belirtiyor: `{shown}`; selection.changed, document.opened, document.saved veya layer.changed kullanın +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` için eklenti API düzeyi {EVENTS_API} gerekir: `api` {EVENTS_API} verin +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` için `events` izni, `events` izni için de bir `events` listesi gerekir +@msg event size ({len} bytes, limit {max}) olay boyutu ({len} bayt, sınır {max}) +@msg the module reacts to no events modül hiçbir olaya tepki vermiyor +@msg vc_event returned {code} vc_event {code} döndürdü +@msg {name}: its {event} handler failed: {e} {name}: {event} işleyicisi başarısız oldu: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: art arda {count} işleyici başarısız olduğundan, VectorCraft yeniden başlayana kadar olayları kapalı @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir @msg memory budget (object {_1} needs {size} bytes of input, {left} left) bellek bütçesi (nesne {_1} için {size} bayt girdi gerekiyor, {left} kaldı) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..d3db0a5137 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7056,6 +7056,7 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити + Run on its own when the selection, a document or a layer changes Запускатися самостійно, коли змінюється виділення, документ або шар Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7087,6 +7088,15 @@ axis Y Axis Вісь Y @msg only a filter declares `inputs` `inputs` може оголошувати лише фільтр @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance в `inputs` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі +@msg `events` lists `{shown}` twice в `events` `{shown}` указано двічі +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed в `events` указано невідому подію `{shown}`: використовуйте selection.changed, document.opened, document.saved або layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} для `events` потрібен рівень API модулів {EVENTS_API}: укажіть `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` для `events` потрібен дозвіл `events`, а для `events` потрібен список `events` +@msg event size ({len} bytes, limit {max}) розмір події ({len} байтів, межа {max}) +@msg the module reacts to no events модуль не реагує на жодні події +@msg vc_event returned {code} vc_event повернула {code} +@msg {name}: its {event} handler failed: {e} {name}: його обробник {event} завершився помилкою: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: його події вимкнено до наступного запуску VectorCraft після {count} невдалих обробників поспіль @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) бюджет пам’яті (об’єкту {_1} потрібно {size} байтів вхідних даних, залишилося {left}) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..806f7f509b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7103,6 +7103,7 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa + Run on its own when the selection, a document or a layer changes Tự chạy khi vùng chọn, một tài liệu hoặc một lớp thay đổi Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi @msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} @@ -7134,6 +7135,15 @@ axis Y Axis Trục Y @msg only a filter declares `inputs` chỉ bộ lọc mới khai báo `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần +@msg `events` lists `{shown}` twice `events` liệt kê `{shown}` hai lần +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` nêu một sự kiện không xác định `{shown}`: dùng selection.changed, document.opened, document.saved hoặc layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` cần API plug-in cấp {EVENTS_API}: hãy đặt `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` cần quyền `events`, và `events` cần một danh sách `events` +@msg event size ({len} bytes, limit {max}) kích thước sự kiện ({len} byte, giới hạn {max}) +@msg the module reacts to no events mô-đun không phản ứng với sự kiện nào +@msg vc_event returned {code} vc_event trả về {code} +@msg {name}: its {event} handler failed: {e} {name}: trình xử lý {event} của nó đã thất bại: {e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}: các sự kiện của nó bị tắt cho đến khi VectorCraft khởi động lại, sau {count} trình xử lý thất bại liên tiếp @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) ngân sách bộ nhớ (đối tượng {_1} cần {size} byte đầu vào, còn lại {left}) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..f752620e19 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7284,6 +7284,7 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 + Run on its own when the selection, a document or a layer changes 在所选对象、文档或图层发生变化时自动运行 Run these commands on the document: {ids} 在文档上运行这些命令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7315,6 +7316,15 @@ axis Y Axis Y 轴 @msg only a filter declares `inputs` 只有滤镜才能声明 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了两次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:请使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效工具 API 级别 {EVENTS_API}:请设置 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要权限 `events`,而 `events` 需要 `events` 列表 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 字节,上限 {max}) +@msg the module reacts to no events 该模块不响应任何事件 +@msg vc_event returned {code} vc_event 返回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 处理程序失败:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:处理程序连续 {count} 次失败,其事件已关闭,直到 VectorCraft 再次启动 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 内存预算(对象 {_1} 需要 {size} 字节的输入,剩余 {left}) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..d941e2cae4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7105,6 +7105,7 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 + Run on its own when the selection, a document or a layer changes 在選取範圍、文件或圖層變更時自動執行 Run these commands on the document: {ids} 在文件上執行這些指令:{ids} @msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` @msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} @@ -7136,6 +7137,15 @@ axis Y Axis Y 軸 @msg only a filter declares `inputs` 只有濾鏡才能宣告 `inputs` @msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` +@msg `events` lists `{shown}` twice `events` 列出了兩次 `{shown}` +@msg `events` names an unknown event `{shown}`: use selection.changed, document.opened, document.saved or layer.changed `events` 列出了未知的事件 `{shown}`:請使用 selection.changed、document.opened、document.saved 或 layer.changed +@msg `events` needs plug-in API level {EVENTS_API}: give `api` {EVENTS_API} `events` 需要增效模組 API 層級 {EVENTS_API}:請設定 `api` {EVENTS_API} +@msg `events` needs the permission `events`, and `events` needs a list of `events` `events` 需要權限 `events`,而 `events` 需要 `events` 清單 +@msg event size ({len} bytes, limit {max}) 事件大小({len} 位元組,上限 {max}) +@msg the module reacts to no events 此模組不回應任何事件 +@msg vc_event returned {code} vc_event 傳回了 {code} +@msg {name}: its {event} handler failed: {e} {name}:其 {event} 處理常式失敗:{e} +@msg {name}: its events are off until VectorCraft starts again, after {count} failed handlers in a row {name}:處理常式連續 {count} 次失敗,其事件已關閉,直到 VectorCraft 再次啟動 @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` @msg memory budget (object {_1} needs {size} bytes of input, {left} left) 記憶體預算(物件 {_1} 需要 {size} 位元組的輸入,剩餘 {left}) diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..2d20911711 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -239,6 +239,7 @@ fn permission_words(name: &str, commands: &[String]) -> String { Some(permissions::Permission::Progress) => tl!("Show its progress, see Cancel and write log lines"), Some(permissions::Permission::Settings) => tl!("Keep settings of its own"), Some(permissions::Permission::Cache) => tl!("Keep a cache of its own, which you can clear"), + Some(permissions::Permission::Events) => tl!("Run on its own when the selection, a document or a layer changes"), None => return permissions::display_text(name, permissions::MAX_SHOWN_FIELD), }; words.to_string() diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..ed18dd4015 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -720,3 +720,43 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// A selection made in the UI pass, after the frame's background work (as a click on the canvas or +/// a panel makes it), reaches a plug-in that reacts to `selection.changed` before that pass ends: +/// nothing is left for a later delivery. +#[test] +fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.ui_pass_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Pass Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + // The handler writes the event as an information line, which the status bar does not show, so + // the plug-in leaves the status bar of other tests' sessions alone. + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.none", json!({})).unwrap(); + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); + let pass = |app: &mut VectorcraftApp, select: bool| { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + app.tick(ui.ctx()); + if select { + app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); + } + app.ui(ui); + }); + out.textures_delta.clear(); + }; + // Fonts install on the first pass and are ready on the second. + pass(&mut app, false); + pass(&mut app, false); + pass(&mut app, true); + app.session.deliver_plugin_events(); + let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert!(left.is_empty(), "delivered in the pass that made the change, not later: {left:?}"); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1, "the selection was made"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..addee8c79a 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -244,6 +244,38 @@ fn finished_background_work_waits_for_the_run_to_end() { assert!(app.opening.activate.is_empty()); } +/// The selection a script changes reaches a plug-in that reacts to `selection.changed` in the +/// frame the script ends in: once it has ended, nothing asks for another frame. +#[test] +fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { + use vectorcraft_plugins::wat as tpl; + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.script_run_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + // The handler writes the event it is given as a warning, which the status bar shows. + let warn = "(drop (call $vc_log (i32.const 1) (local.get $ep) (local.get $el))) (i32.const 0)"; + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, warn)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + app.poll_finished_work(); + let source = format!("{DRAW} vc.run('select.all', {{}});"); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + let ctx = egui::Context::default(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + } + assert!(!app.session.script_running(), "the script did not end"); + assert!(app.ui.status.starts_with("Run Events: "), "{}", app.ui.status); + assert!(app.ui.status.contains("selection.changed"), "{}", app.ui.status); +} + #[test] fn quitting_asks_to_stop_and_stop_undoes_the_run() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..ed02d61332 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13262,7 +13262,10 @@ while it runs, through `vc_call`: the calls and its output are one undo step, an fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as -`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with +`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A plug-in at API level 2 +whose manifest lists the `events` permission and `events` (in its `plugin.list` entry) is given `selection.changed`, +`document.opened`, `document.saved` and `layer.changed` events through `vc_event` once the change has finished; +its handler only reads, and `plugin.info` gives `eventsOff` and `lastEventError` (see `docs/plugins.md`). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..8aba315c74 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -210,6 +210,7 @@ capability model proposed for PhotoCraft plug-ins | `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. | +| `events` | all | Run on its own when the selection, a document or a layer changes, for the `events` it names ([events](#events-api-level-2)). Needs `api` 2. | - A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter `doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state` @@ -219,9 +220,9 @@ capability model proposed for PhotoCraft plug-ins - An effect, an exporter or an importer that lists permissions lists all of its implied ones (`doc.read` and `effect.render`; `doc.read` and `export.write`; `import.read`). An effect with commands may add `doc.write` and `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. - Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a - name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` - below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is + Any kind may add `progress`, `settings`, `cache` and `events`, which no kind implies. An unknown name, a name listed + twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache`, `commands` or + `events` with an `api` below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of the file and each permission in plain words, and install it once the user clicks OK, if the file still has the @@ -371,6 +372,7 @@ pointers are offsets into the module's memory. | `vc_manifest` | `() -> i64` | `(len << 32) \| ptr` of the UTF-8 manifest JSON (≤ 64 KiB). | | `vc_alloc` | `(size) -> ptr` | A block of `size` bytes the host may write, or `0` on failure. Never freed: each run gets a fresh instance. | | `vc_run` | `(input, input_len, params, params_len) -> i64` | Runs the plug-in on the input JSON with the parameters JSON; returns `(len << 32) \| ptr` of the output JSON, or a negative error code. | +| `vc_event` | `(event, event_len) -> i32` | Only in a module whose manifest lists [`events`](#events-api-level-2): reacts to the event JSON; returns `0` when it handled it, anything else when it failed. | ### Host imports (API level 2) @@ -491,7 +493,8 @@ arguments as a JSON object, the params the command takes from any request: `-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected), `-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from -the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). +the module's start function, in a run that isn't a filter's run on a document or an [event](#events-api-level-2) +handler, or after a call in the run failed). - Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, traps, runs @@ -522,6 +525,57 @@ the module's start function, in a run that isn't a filter's run on a document, o - A filter that calls commands runs on the app's main thread, so it can't ask for a heavy budget: a manifest with `commandAllowlist` and `budget: "heavy"` is refused. +### Events (API level 2) + +A plug-in of any kind whose manifest gives `"api": 2`, lists the `events` permission and names events in `events` +exports `vc_event`, and VectorCraft calls it after each change of those kinds: + +```json +{"id": "org.example.watch", "name": "Watch", "kind": "filter", "api": 2, + "permissions": ["doc.read", "events"], "events": ["selection.changed", "document.saved"]} +``` + +| Event | When | The event JSON | +|---|---|---| +| `selection.changed` | The selection in a document changed: other objects, anchors or segments, or nothing (`count` 0). | `{"type", "document", "count", "ids", "truncated"}`: `ids` lists the selected objects, at most 2,048 of them (`truncated` is then `true`), and is `null` without `doc.read`. | +| `document.opened` | A file opened as a document (File › Open, Open Recent, New from Template). A new blank document is not one. | `{"type", "document"}` | +| `document.saved` | Save or Save As wrote the document's own file. Save a Copy, a template and an export are not. | `{"type", "document"}` | +| `layer.changed` | The current layer changed, or a layer or sublayer was added, deleted, moved or given other options. | `{"type", "document", "layer", "reasons"}`: `layer` is the current layer's id (`null` when there is none), `reasons` lists any of `current`, `added`, `deleted`, `reordered` and `options`. `reordered` means a layer's or sublayer's place among the rows beside it changed, also when an object moved past it. | + +`document` is a number that names the open document for the rest of the session. No event carries a path, a file name +or the document's contents. + +- VectorCraft calls `vc_event(event, event_len)` in a fresh instance with the UTF-8 event JSON in a block from + `vc_alloc`, after the change has finished: after the command, after Undo or Redo, after the file was written or the + document opened. Nothing happens while a drag is still being previewed, for a failed command, or for a command that + leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past + events, also none that were waiting for the next delivery when it was installed. A change made to a document opened + or created since the last delivery is an event at the next one, after that document's `document.opened`. +- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each + frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels + and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does + not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app + and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP + deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + document closed before the delivery. At most 32 events wait; past that the oldest is dropped. +- A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a + `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active + document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, + `symbol.list`, `text.getRange`, `transparency.info` and `variable.list`. A call of any other command fails with `-6` + before it runs, the error names the event (`a selection.changed handler only reads: …`), and the handler fails. + Afterwards VectorCraft puts back every document, its selection, current layer and undo history, which document is + active, and the session state a command call can change (paint defaults, the Appearance panel's active row, + preferences); a call that changed a document is refused the same way. An event raised while a handler runs waits + for the next delivery: handlers never run inside one another. +- A handler gets at most 5,000,000 instructions and 200 ms, or its plug-in's own budget when that is smaller, for the + module's start function, `vc_alloc` and `vc_event` together; its settings, cache and log lines work as in a run. + These limits are VectorCraft's own values. A handler that returns anything but `0`, traps or runs out of budget + leaves the change it was told of as it is. Every failure goes to the log, and the first failure in a row also shows + in the status bar; after 3 failures in a row, the plug-in gets no more events until VectorCraft + starts again or another module is installed with its id. A warning or error line a handler writes with `vc_log` + shows in the status bar after the plug-in's name. `plugin.info` gives `eventsOff` and `lastEventError`. +- In Safe Mode no handler runs. When no installed plug-in names an event, VectorCraft does not compare anything. + ### Manifest ```json @@ -574,6 +628,11 @@ the module's start function, in a run that isn't a filter's run on a document, o it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. +- `events` (any kind at `api` 2, and only with the `events` permission, which needs it): the + [events](#events-api-level-2) the plug-in reacts to, any of `"selection.changed"`, `"document.opened"`, + `"document.saved"` and `"layer.changed"`, each at most once. The module then exports `vc_event`. An unknown or + repeated name, an entry that isn't a string, `api` 1, a list without the permission, the permission without a list, + and a missing or wrongly typed `vc_event` are refused when the module is installed, and the error names the fault. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..540f5e8b1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2654,6 +2654,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. From b900ea2308034ec6ffe9a52613532fabd0026213 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:56:10 -0800 Subject: [PATCH 038/533] JavaScript: a block function skips its variable when a let has the name - A block function in script or eval code no longer stops the run with "redeclaration of" when a `let`, a `const` or a block function between the code and its variable environment has its name, or when the global object cannot take the variable (Annex B.3.3.2 and B.3.3.3). Its block still has the function, and a `var` of the name is still a SyntaxError. - A script stopped by the heap limit or the frame limit declares none of its `let` and `const` names, so a later script can declare them. The frame limit is checked, and the heap reserved for the names, before anything is declared. - An arrow function in an async arrow function's parameters reads `await` as an identifier, as its own body does. - With E4X, `async::name` is a qualified name. - `AsyncFunction` inherits from the built-in `Function` even after a script replaced `Function.prototype.constructor`. - The test262 reports list the older edition's panics, an async test passes only when one `print` call gives exactly the completion line, and the promise collection test checks that all 200 rejections arrive. --- crates/js/src/async_tests.rs | 20 +++++ crates/js/src/builtins.rs | 1 + crates/js/src/builtins/async_function.rs | 17 ++--- crates/js/src/bytecode.rs | 5 ++ crates/js/src/compiler.rs | 17 ++++- crates/js/src/es2015_tests.rs | 54 ++++++++++++++ crates/js/src/heap.rs | 3 +- crates/js/src/interp.rs | 95 +++++++++++++++++++++--- crates/js/src/interp/async_function.rs | 1 + crates/js/src/interp_tests.rs | 1 + crates/js/src/parser.rs | 6 +- crates/js/src/promise_tests.rs | 3 +- crates/js/tests/test262.rs | 48 +++++++----- 13 files changed, 223 insertions(+), 48 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index a473fd57da..0d78c4fd3c 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -84,6 +84,23 @@ fn async_functions_are_not_constructors_and_have_no_prototype() { assert_eq!(log(src), "false true true function true undefined true async function h() { await 0; } 5"); } +#[test] +fn async_function_inherits_from_the_built_in_function_after_a_script_replaced_its_constructor() { + let mut r = Realm::new(); + assert_eq!(r.run("Function.prototype.constructor = {}; 0"), Ok(JsValue::Number(0.0))); + r.add_es2015(); + r.set_es2017(true); + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor; Object.getPrototypeOf(AF) === Function && typeof AF.call"; + assert_eq!(r.run(src), Ok(JsValue::String("function".into()))); +} + +#[test] +fn with_e4x_async_before_a_double_colon_is_a_qualified_name() { + let options = Options { es2017: true, e4x: true, ..Options::default() }; + assert!(parse("async::b", &options).is_ok()); + assert!(parse("var x = ; x.async::b", &options).is_ok()); +} + #[test] fn await_is_an_identifier_outside_async_functions() { let src = "var await = 3; function f(await) { return await; } log.push(f(await));\n\ @@ -98,6 +115,9 @@ fn await_is_an_identifier_outside_async_functions() { async function await() { return 1; }\n\ log.push(typeof g, typeof h, typeof await);"; assert_eq!(log(nested), "function function function"); + // An arrow function in an async arrow function's parameters reads `await` as its own body does. + let arrow = "var await = 7; var f = async (cb = () => await) => cb(); f().then(function (v) { log.push(v); });"; + assert_eq!(log(arrow), "7"); let mut r = realm(); syntax_error(&mut r, "async function f() { var await; }"); syntax_error(&mut r, "async function f(await) {}"); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 09cb089e5b..f1f8c0a547 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -123,6 +123,7 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, object_proto, "propertyIsEnumerable", property_is_enumerable, 1)?; let function = native(interp, "Function", function_ctor, 1, NativeKind::Plain, true)?; + interp.intrinsics.function_ctor = function; constructor(interp, "Function", function, function_proto)?; let call = native(interp, "call", unreachable_native, 1, NativeKind::Call, false)?; data(interp, function_proto, "call", Value::Object(call), HIDDEN)?; diff --git a/crates/js/src/builtins/async_function.rs b/crates/js/src/builtins/async_function.rs index 43eea77b2a..4e3e65a906 100644 --- a/crates/js/src/builtins/async_function.rs +++ b/crates/js/src/builtins/async_function.rs @@ -4,7 +4,7 @@ //! reaches through it. `AsyncFunction` is not a global. use super::{data, dynamic_function, native}; -use crate::heap::{CONFIGURABLE, Class, NativeKind, ObjId, Object}; +use crate::heap::{CONFIGURABLE, Class, NativeKind, Object}; use crate::interp::{Interp, JsResult}; use crate::value::Value; @@ -16,10 +16,11 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { interp.promises.async_function_proto = Some(proto); let ctor = native(interp, "AsyncFunction", async_function_ctor, 1, NativeKind::Plain, true)?; interp.promises.async_function_ctor = Some(ctor); - // `Function` is the constructor's prototype (section 25.5.2). - let function_ctor = constructor_of(interp, function_proto); + // The built-in `Function` is the constructor's prototype (section 25.5.2), even after a + // script has replaced `Function.prototype.constructor`. + let function_ctor = interp.intrinsics.function_ctor; if let Some(o) = interp.heap.object_mut(ctor) { - o.proto = function_ctor.or(o.proto); + o.proto = Some(function_ctor); } data(interp, ctor, "prototype", Value::Object(proto), 0)?; // Configurable and not writable (section 25.5.3.1), unlike the `constructor` of the ordinary @@ -27,14 +28,6 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { data(interp, proto, "constructor", Value::Object(ctor), CONFIGURABLE) } -/// The `constructor` property `proto` has from the built-ins, when it is an object. -fn constructor_of(interp: &Interp, proto: ObjId) -> Option { - match interp.get_own_property(proto, &crate::heap::key("constructor")) { - Ok(Some(crate::heap::Prop::Data { value: Value::Object(o), .. })) => Some(o), - _ => None, - } -} - /// `AsyncFunction(p1, …, body)` and `new AsyncFunction(…)` (section 25.5.1.1). fn async_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { dynamic_function(interp, args, true) diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 723ad84b40..5dba6c540f 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -280,6 +280,11 @@ pub(crate) struct Code { pub(crate) vars: Vec, /// Function declarations to instantiate on entry: their names and indices in `functions`. pub(crate) fun_decls: Vec<(Key, u32)>, + /// In script and eval code, the variables of block functions (Annex B.3.3.2 and B.3.3.3) that + /// the code does not declare otherwise: each is declared, and its function assigned to it, only + /// when no `let`, `const` or block function between the code and its variable environment has + /// the name and the variable can be declared. + pub(crate) annex_vars: Vec, /// The body refers to `arguments` or calls `eval`. pub(crate) uses_arguments: bool, pub(crate) source: Rc, diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 3690ef3e28..aa0feff65f 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -106,6 +106,9 @@ struct FnCompiler<'a> { struct Hoisted { vars: Vec, fun_decls: Vec<(Key, u32)>, + /// The names of block functions (Annex B.3.3) that are neither a `var` nor a function at the + /// top of the body. + annex_vars: Vec, } fn key_of(name: &str) -> Key { @@ -244,7 +247,8 @@ impl<'a> FnCompiler<'a> { /// hoisted; one in a block is instantiated when the block is entered, and outside strict mode /// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with /// a `let` or a `const` of the body or of a block or loop around the declaration, or with a - /// function of a block around the one that holds it. + /// function of a block around the one that holds it. Such a name that the body does not also + /// declare with `var` or as a function at its top goes in [`Hoisted::annex_vars`]. fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult { let mut out = Hoisted::default(); let mut seen = HashSet::new(); @@ -259,6 +263,7 @@ impl<'a> FnCompiler<'a> { } }; let mut annex: Vec<(Key, usize, StmtId)> = Vec::new(); + let mut annex_seen = HashSet::new(); while let Some((id, nested, scope)) = work.pop() { let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") }; let inner = self.es2015; @@ -366,7 +371,9 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - add_var(&mut out, k); + if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + out.annex_vars.push(k); + } } } Ok(out) @@ -1800,6 +1807,7 @@ impl<'a> FnCompiler<'a> { params: meta.params, vars: hoisted.vars, fun_decls: hoisted.fun_decls, + annex_vars: hoisted.annex_vars, uses_arguments: self.uses_arguments, source: self.source.clone(), span: meta.span, @@ -1848,7 +1856,10 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let params: Vec = f.params.iter().map(|p| key_of(&p.name)).collect(); let rest = f.rest.as_ref().map(|r| key_of(&r.name)); let all_params: Vec = params.iter().chain(&rest).cloned().collect(); - let hoisted = c.hoist(&f.body, &all_params)?; + let mut hoisted = c.hoist(&f.body, &all_params)?; + // A function's block functions always have their variable (Annex B.3.3.1). + let annex = std::mem::take(&mut hoisted.annex_vars); + hoisted.vars.extend(annex); let top_scope = c.list_scope(&f.body, false)?; let param_init = !f.simple_params(); if param_init { diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index ec09876731..a8a77b723b 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -138,6 +138,28 @@ fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() { truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1"); } +#[test] +fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { + // A block function of a script or of eval code gets no variable when a `let`, a `const` or a + // block function out to the variable environment has its name, or when the global object + // cannot take it (Annex B.3.3.2 and B.3.3.3); its block still has it, and a `var` of the name + // is still a SyntaxError. + let mut realm = es(); + assert_eq!(realm.run("let f = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var inner; { function f() { return 2; } inner = f(); } inner + f"), Ok(JsValue::Number(3.0))); + assert!(is_thrown(&realm.run("{ function f() {} } var f;"), "SyntaxError")); + assert_eq!(realm.run("(0, eval)('{ function f() { return 4; } }'); f"), Ok(JsValue::Number(1.0))); + truth("function t() { let h = 1; { eval('{ function h() { return 2; } }'); } return h; } t() === 1"); + truth("function t() { let h = 1; eval('{ function h() {} }'); return h; } t() === 1"); + // A `catch` parameter does not stop the variable (Annex B.3.5). + truth("try { throw 1; } catch (c) { eval('{ function c() { return 5; } }'); } c() === 5"); + let mut realm = es(); + assert_eq!(realm.run("var out; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0))); + let kept = realm.run("{ function n() { return 6; } out = n(); } out + typeof n"); + assert_eq!(kept, Ok(JsValue::String("6undefined".into()))); + assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); @@ -286,6 +308,38 @@ fn a_global_var_that_cannot_be_declared_declares_nothing() { assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0))); } +#[test] +fn a_script_stopped_by_the_frame_limit_declares_no_let() { + let mut realm = Realm::with_options(es_options(), Limits { frames: 0, ..Limits::default() }); + let stopped = realm.run("let early = 1; const fixed = 2;"); + assert!(matches!(&stopped, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Frames)), "{stopped:?}"); + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0))); +} + +#[test] +fn a_script_stopped_by_the_heap_limit_declares_no_let() { + // The `let` and `const` names of a script go in before its functions are made; a heap too + // small for both stops the script before any name is declared. + let lets: String = (0..200).map(|i| format!("let a_long_lexical_name_{i} = {i}; ")).collect(); + let decls: String = (0..40).map(|i| format!("function f{i}() {{ return {i}; }} ")).collect(); + let src = format!("let early = 1; const fixed = 2; {lets}{decls}"); + let mut stopped = 0; + for spare in (40_000..200_000).step_by(97) { + let mut realm = es(); + let live = realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match realm.run(&src) { + Ok(_) => continue, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => stopped += 1, + Err(e) => panic!("{spare}: {e:?}"), + } + realm.set_limits(Limits::default()); + assert_eq!(realm.run("let early = 3; const fixed = 4; early + fixed"), Ok(JsValue::Number(7.0)), "{spare}"); + } + assert!(stopped > 0); +} + #[test] fn eval_code_keeps_its_let_and_const_to_itself() { truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index e25bac7323..c59925c1bb 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -623,6 +623,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { + code.functions.len() + code.params.len() + code.vars.len() + + code.annex_vars.len() + 2 * code.fun_decls.len() + code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::() + code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::(); @@ -641,7 +642,7 @@ fn mark_code(code: &Code, strings: &mut StringSizes) { strings.add(pattern); strings.add(flags); } - let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k)); + let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(&code.annex_vars).chain(code.fun_decls.iter().map(|(k, _)| k)); for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) { strings.add_key(k); } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d7a0ef6481..b4fa731b76 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -92,6 +92,9 @@ impl ErrorType { pub(crate) struct Intrinsics { pub(crate) object_proto: ObjId, pub(crate) function_proto: ObjId, + /// The built-in `Function`, which a script can replace as the global or as the prototype's + /// `constructor`. + pub(crate) function_ctor: ObjId, pub(crate) array_proto: ObjId, pub(crate) string_proto: ObjId, pub(crate) number_proto: ObjId, @@ -115,6 +118,7 @@ impl Intrinsics { Self { object_proto: o, function_proto: o, + function_ctor: o, array_proto: o, string_proto: o, number_proto: o, @@ -149,6 +153,7 @@ impl Intrinsics { let mut v = vec![ self.object_proto, self.function_proto, + self.function_ctor, self.array_proto, self.string_proto, self.number_proto, @@ -187,6 +192,9 @@ pub(crate) struct Frame { /// The promise of the async function the frame runs: a return resolves it, an exception /// that leaves the frame rejects it, and the call's value is the promise. async_promise: Option, + /// The block functions of script or eval code ([`Code::annex_vars`]) whose variable was not + /// declared: [`Op::AnnexB`] leaves them alone. + annex_off: Vec, } /// Where the exception being thrown was raised: the code and the instruction. @@ -471,7 +479,13 @@ fn declaration_bytes(code: &Code) -> usize { let closure = code.functions.get(*fi as usize).map_or(0, |f| closure_bytes(f)); total.saturating_add(binding_bytes(name.len()) + closure) }); - code.vars.iter().fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) + code.vars.iter().chain(&code.annex_vars).fold(funs, |total, v| total.saturating_add(binding_bytes(v.len()))) +} + +/// The bytes the `let` and `const` names at the top of a script add to the global scope. +fn global_lexical_bytes(code: &Code) -> usize { + let lets: &[(Key, bool)] = code.top_scope.and_then(|i| code.scopes.get(i as usize)).map_or(&[], |s| &s.lets); + lets.iter().fold(0usize, |total, (name, _)| total.saturating_add(binding_bytes(name.len()))) } /// A call to a function written in JavaScript, ready to enter. @@ -2396,9 +2410,13 @@ impl Interp { Ok(()) } - /// Assigns a function declared in a block to the variable of the same name. + /// Assigns a function declared in a block to the variable of the same name, unless the + /// variable of script or eval code was not declared. fn op_annex_b(&mut self, n: u32) -> JsResult<()> { let name = self.name(n)?; + if self.frame()?.annex_off.contains(&name) { + return self.pop().map(drop); + } let v = self.peek(0)?; let var_env = self.frame()?.var_env; match self.heap.env(var_env) { @@ -2952,6 +2970,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); // An async function's call makes its promise first thing (section 25.5.5.2); the frame // keeps what the function holds reachable while it is made. @@ -3278,14 +3297,16 @@ impl Interp { (caller_env, caller_var_env) }; self.stack.truncate(start); - let env = self.instantiate_pending(&code, env, var_env, true)?; - self.push_code_frame(code, env, var_env, this, false) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, true)?; + self.push_code_frame(code, env, var_env, this, false)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// [`Self::instantiate_global`] with `code` and its environment `env` kept reachable, and the /// code counted against the heap, until its frame holds them: the scopes and functions it /// makes can collect. - fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + fn instantiate_pending(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let mark = self.temp_envs.len(); self.temp_envs.push(env); self.temp_codes.push(code.clone()); @@ -3311,9 +3332,15 @@ impl Interp { r } - /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. + /// Declares `code`'s variables and functions and pushes its boundary frame, ready to run. The + /// frame limit and the heap, with a script's `let` and `const` names, are checked before + /// anything is declared. pub(crate) fn enter_global(&mut self, code: Rc, is_eval: bool) -> JsResult<()> { - self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let lexical = if is_eval { 0 } else { global_lexical_bytes(&code) }; + self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES).saturating_add(lexical))?; let (scope, global) = (self.global_scope(), self.global); let (env, var_env) = if code.strict && is_eval { let e = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); @@ -3321,8 +3348,10 @@ impl Interp { } else { (scope, self.global_env) }; - let env = self.instantiate_pending(&code, env, var_env, is_eval)?; - self.push_code_frame(code, env, var_env, Value::Object(global), true) + let (env, annex_off) = self.instantiate_pending(&code, env, var_env, is_eval)?; + self.push_code_frame(code, env, var_env, Value::Object(global), true)?; + self.frame_mut()?.annex_off = annex_off; + Ok(()) } /// The environment global code runs in: the one that holds the scripts' `let` and `const` @@ -3437,6 +3466,7 @@ impl Interp { completion: Value::Undefined, boundary, async_promise: None, + annex_off: Vec::new(), }); Ok(()) } @@ -3446,8 +3476,9 @@ impl Interp { /// /// Gives the environment the code runs in: `env`, or with [`Options::es2015`] eval code's own /// environment of its `let` and `const` names. A script's `let` and `const` names go in the - /// global scope ([`Self::declare_global_lexical`]). - fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult { + /// global scope ([`Self::declare_global_lexical`]). Also gives the names of + /// [`Code::annex_vars`] that [`Self::annex_var_declarable`] did not declare. + fn instantiate_global(&mut self, code: &Rc, env: EnvId, var_env: EnvId, is_eval: bool) -> JsResult<(EnvId, Vec)> { let configurable = if is_eval { CONFIGURABLE } else { 0 }; if is_eval && !code.strict && self.options.es2015 { self.check_eval_vars(code, env, var_env)?; @@ -3492,7 +3523,47 @@ impl Interp { self.global_vars.insert(v.clone()); } } - Ok(lex) + let mut annex_off = Vec::new(); + for v in &code.annex_vars { + self.use_fuel()?; + if !self.annex_var_declarable(v, env, var_env)? { + annex_off.push(v.clone()); + continue; + } + self.declare(var_env, v, None, configurable)?; + if on_global { + self.global_vars.insert(v.clone()); + } + } + Ok((lex, annex_off)) + } + + /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and + /// B.3.3.3, ): no + /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` + /// parameter does not count, and on the global object the name is its own property or the + /// object is extensible. Each environment passed takes a unit of fuel. + fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { + let mut cur = Some(env).filter(|&e| e != var_env); + while let Some(e) = cur { + self.use_fuel()?; + cur = match self.heap.env(e) { + Some(Env::Decl { bindings, outer }) => { + if bindings.get(name).is_some_and(|b| b.lexical) { + return Ok(false); + } + *outer + } + Some(Env::Obj { outer, .. }) => *outer, + None => return internal("environment out of range"), + } + .filter(|&o| o != var_env); + } + if var_env != self.global_env { + return Ok(true); + } + let global = self.global; + Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) } /// A `var` or function that eval code outside strict mode code declares must not take the name diff --git a/crates/js/src/interp/async_function.rs b/crates/js/src/interp/async_function.rs index 7121215b9d..9bb7c26cb8 100644 --- a/crates/js/src/interp/async_function.rs +++ b/crates/js/src/interp/async_function.rs @@ -147,6 +147,7 @@ impl Interp { completion: a.completion, boundary: true, async_promise: Some(a.promise), + annex_off: Vec::new(), }); Ok(()) } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 4a281a7b2f..346c32983a 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -972,6 +972,7 @@ fn code(ops: Vec) -> Code { params: Vec::new(), vars: Vec::new(), fun_decls: Vec::new(), + annex_vars: Vec::new(), uses_arguments: false, source, span: (0, 0), diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 9478074e73..8a7cef804f 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -1130,6 +1130,8 @@ impl<'s> Parser<'s> { let outer_strict = self.ctx.strict; let inner = Context { strict: outer_strict, in_function: true, in_async: is_async, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); + // An `await` in the body does not count for an async arrow function's head around it. + let awaits = self.awaits; self.push_scope(true, names); let block = self.at(Punct::LBrace); let body = if block { @@ -1138,6 +1140,7 @@ impl<'s> Parser<'s> { self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))]) }; self.pop_scope(); + self.awaits = awaits; let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict); self.ctx = outer; self.leave(); @@ -1553,7 +1556,8 @@ impl<'s> Parser<'s> { if name == "await" { self.awaits = self.awaits.saturating_add(1); } - if self.at_async() { + // With E4X, `async::name` is a qualified name. + if self.at_async() && !(self.e4x && self.peek().is_some_and(|t| t.is_punct(Punct::ColonColon))) { let token = self.bump()?; let id = self.ast.push_expr(Expr::Ident(name), token.span); self.async_ident = Some(id); diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index 8e03f2a136..fc6d927c70 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -78,7 +78,7 @@ fn a_promise_resolved_with_itself_rejects_with_a_type_error() { #[test] fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { - let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + let src = "var bad = 0, seen = 0; function check(e) { seen++; if (!(e instanceof TypeError)) bad++; }\n\ for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; let mut finished = 0; for spare in (40_000..240_000).step_by(641) { @@ -92,6 +92,7 @@ fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { } r.set_limits(Limits::default()); assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + assert_eq!(r.run("seen"), Ok(JsValue::Number(200.0)), "{spare}"); } assert!(finished > 0); } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 0fe3badb67..8cd87a33bb 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,8 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. +//! prints both counts; its failures with the option, and the runs without it that panicked, go to +//! `es2015-failures.txt`. //! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset @@ -42,8 +43,8 @@ //! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: //! those whose feature tags name only `Promise`, `Promise.allSettled` and //! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests -//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its -//! failures go to `promise-failures.txt`. +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line and no +//! line that starts with the failure prefix. Its failures go to `promise-failures.txt`. //! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over @@ -695,13 +696,25 @@ struct Es2015Counts { failures: String, } +impl Es2015Counts { + /// The failures of the run with the option, then each run without it that panicked, marked + /// with `without`. + fn report(after: &Es2015Counts, before: &Es2015Counts, without: &str) -> String { + let mut report = after.failures.clone(); + for line in before.failures.lines().filter(|l| l.ends_with(": PANIC")) { + report.push_str(&format!("{line} ({without})\n")); + } + report + } +} + /// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`] whose feature /// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature /// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a /// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests /// and those that need a missing built-in. Each test is read twice, without and with -/// [`Options::es2015`], and the counts of both are printed; the failures with it go to -/// `es2015-failures.txt`. +/// [`Options::es2015`], and the counts of both are printed; the failures with it, and the runs +/// without it that panicked, go to `es2015-failures.txt`. fn run_es2015(dir: &Path) { let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -779,7 +792,7 @@ fn run_es2015(dir: &Path) { assert!(selected > 0, "no ES2015 tests under {}", language.display()); let [before, after] = counts; let report = dir.join("es2015-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "without Options::es2015")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { @@ -869,11 +882,12 @@ fn promise_builtins_run() { } /// Runs one test that may be asynchronous in a new realm made with `options` and a global `print` -/// that collects its output; an `async` test without a runtime negative passes when it prints -/// `Test262:AsyncTestComplete`, and one with a runtime negative must throw that error. +/// that collects its output; an `async` test without a runtime negative passes when one `print` +/// call gives exactly `Test262:AsyncTestComplete` and none gives a value that starts with +/// `Test262:AsyncTestFailure:`, and one with a runtime negative must throw that error. fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool, options: &Options) -> Result<(), String> { let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); - let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { let line = match args.first() { @@ -881,18 +895,15 @@ fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool Some(other) => format!("{other:?}"), None => String::new(), }; - out.borrow_mut().push_str(&line); - out.borrow_mut().push('\n'); + out.borrow_mut().push(line); Ok(JsValue::Undefined) }); let result = realm.run(script); if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); - return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { - Ok(()) - } else { - Err(format!("printed {:?}", printed.trim())) - }; + let complete = printed.iter().any(|l| l == "Test262:AsyncTestComplete"); + let failed = printed.iter().any(|l| l.starts_with("Test262:AsyncTestFailure:")); + return if complete && !failed { Ok(()) } else { Err(format!("printed {:?}", printed.join("\n"))) }; } match (result, negative_type) { (Ok(_), None) => Ok(()), @@ -1014,7 +1025,8 @@ fn async_functions_run() { /// [`ASYNC_FEATURES`], twice: with [`Options::es2015`] alone and with [`Options::es2017`]. Negative /// parse tests must not parse; the others run as [`run_promise`] runs them, `async` tests /// included, skipping module tests and those that need a missing built-in. Prints the counts of -/// both and writes the failures with [`Options::es2017`] to `async-function-failures.txt`. +/// both and writes the failures with [`Options::es2017`], and the runs with [`Options::es2015`] +/// alone that panicked, to `async-function-failures.txt`. fn run_async_functions(dir: &Path) { let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); @@ -1092,7 +1104,7 @@ fn run_async_functions(dir: &Path) { assert!(selected > 0, "no async-function tests under {}", dir.display()); let [before, after] = counts; let report = dir.join("async-function-failures.txt"); - if let Err(e) = std::fs::write(&report, &after.failures) { + if let Err(e) = std::fs::write(&report, Es2015Counts::report(&after, &before, "with Options::es2015 alone")) { println!("could not write {}: {e}", report.display()); } let line = |c: &Es2015Counts| { From 1f1b967a7c3bb04080f6eea9f6fe2dd86515186b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:01:22 -0800 Subject: [PATCH 039/533] JavaScript: Promise.all reads a String object by its characters `Promise.all`, `Promise.allSettled` and `Promise.race` read a `String` object as the string it holds, one input for each character, as they read a string. A character outside the Basic Multilingual Plane was two inputs before. --- crates/js/src/builtins/promise.rs | 9 ++++++++- crates/js/src/promise_tests.rs | 2 ++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs index 03ece744a5..901125f565 100644 --- a/crates/js/src/builtins/promise.rs +++ b/crates/js/src/builtins/promise.rs @@ -1141,7 +1141,7 @@ fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsRe /// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to /// its length at each step, as an array iterator reads it, and another object up to the `length` -/// it had at the start. +/// it had at the start. A string, and a `String` object, gives its characters. enum Inputs { Indexed { object: ObjId, length: f64 }, CodePoints(Rc<[u16]>), @@ -1149,6 +1149,13 @@ enum Inputs { impl Inputs { fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + // A `String` object iterates as the string it holds does (ECMA-262 2015 section 21.1.3.27). + if let Value::Object(o) = input + && let Some(Class::String(s)) = interp.heap.object(*o).map(|obj| &obj.class) + { + let s = s.clone(); + return Ok(Inputs::CodePoints(flat_charged(interp, &s)?)); + } match input { Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs index fc6d927c70..6f3fb5008d 100644 --- a/crates/js/src/promise_tests.rs +++ b/crates/js/src/promise_tests.rs @@ -105,6 +105,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(new String('a\\uD83D\\uDE00')).then(function (v) { log.push('boxed ' + v.length + ' ' + v[1].length); });\n\ Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; @@ -117,6 +118,7 @@ fn catch_finally_and_the_combinators_settle_as_the_specification_says() { "rejected:r fulfilled:4", "race fast", "chars 2", + "boxed 2 2", "not a list true", "no length true", "bad length true", From d199b0d257c9e972d34cdbb14fd2d5c3eb97bb2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:21:26 -0800 Subject: [PATCH 040/533] Recolor Artwork: a swatch picked for a row keeps the art linked to it A spot or global swatch picked for a row's new color in the Color Picker's swatch list now stays that swatch: with Scale Tints or Preserve Tints the row's art becomes tints of the swatch linked to it, also with no Limit to Library, so editing the swatch recolors the art. A process swatch gives its color, as before. Before this change the picker passed only the color, and the art took unlinked tints. recolor.apply rows take swatch: {name, library?}. Of the swatches with that name, the first with the row's new color is used; when it is a global or spot swatch and no Global Adjust applies without Limit to Library, the row's art links to it. A process swatch, or a swatch or library that is not there, links nothing, and the result lists the names that are not there in swatchesNotFound; a malformed swatch is an error. Rows that pick two library swatches of one name each link to their own added swatch. recolor.randomize moves a row's swatch with its color. In the dialog, the Tint slider shows for a row whose picked swatch is a spot color, a row's swatch goes when its new color changes or a process swatch is picked for it, and a row whose swatch no longer links its art shows the full color. Over Recolor Artwork, the picker lists the document's swatches as they were before the preview. The rows of the picker's swatch list are now buttons named for their swatch, so screen readers can read them. --- crates/engine/src/cmd/recolor.rs | 102 ++++++++--- crates/engine/src/tests/recolor.rs | 198 +++++++++++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 44 ++++- crates/ui-egui/src/dialogs/recolor.rs | 179 ++++++++++++++++++- crates/ui-egui/src/tests/recolor.rs | 179 +++++++++++++++++++ docs/mcp.md | 14 +- docs/target-app-parity.md | 1 + 7 files changed, 681 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index b4ad26400b..381912c3ac 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; a `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Randomize Colors", [], None, - "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys}", + "{map: rows as recolor.apply (an excluded row, or a row whose from is empty, keeps its new color), order?: true (shuffle the new colours among the rows that aren't excluded and hold current colors), saturationBrightness?: false (random saturation and brightness, hue kept), seed?: 0} → {map: the rows with their new colours as keys; a row's tint and swatch move with its new color and are dropped when the color changes}", always, randomize ), @@ -1457,6 +1457,9 @@ struct Row { /// `added`: with no current colors, the new color is a color added to the group, which it /// joins after the colors of the rows with current colors. added: bool, + /// `swatch`: the library key ("document" for the document's swatches) and the name of the + /// swatch the new color was picked from. + swatch: Option<(String, String)>, } /// The color model a row's colors take (`model`): each color's own, the new color's, or the @@ -1512,7 +1515,9 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { match p.get("map") { Some(Value::Object(m)) => m .iter() - .map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false })) + .map(|(k, v)| { + Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false, swatch: None }) + }) .collect(), Some(Value::Array(rows)) => rows .iter() @@ -1525,7 +1530,21 @@ fn parse_rows(p: &Value, cmd: &str) -> Result> { let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32; let model = ModelRule::param(r, cmd)?; let added = switch_or(r, "added", false, cmd)?; - Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added }) + let swatch = match r.get("swatch") { + None | Some(Value::Null) => None, + Some(w) => { + let name = w.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()); + let library = match w.get("library") { + None | Some(Value::Null) => Some(super::swatchlib::DOCUMENT_SWATCHES), + Some(l) => l.as_str().filter(|l| !l.is_empty()), + }; + match (name, library) { + (Some(n), Some(l)) => Some((l.to_string(), n.to_string())), + _ => return Err(bad(cmd, format!("a row's `swatch` must be {{name, library?}} with a name and a library id: {w}"))), + } + } + }; + Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added, swatch }) }) .collect(), _ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")), @@ -1714,10 +1733,33 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(k) => super::swatchlib::library_swatches(s, k).unwrap_or_default(), None => vec![], }; + // A row's own `swatch`, the one its new color was picked from: of the swatches with its name, the + // first with the row's new color (as a color key, which rounds), when that one is a global or + // spot swatch and no Global Adjust changes the colors the row maps. A swatch or library that is + // not there (deleted since the pick) links nothing, and the result names it. Limit to Library's + // swatch of that color comes first. + let same = |a: Color, b: Color| ColorKey::of(&a) == ColorKey::of(&b); + let mut not_found: Vec = vec![]; + let picked: Vec> = rows + .iter() + .map(|r| { + let (lib, name) = r.swatch.as_ref()?; + let list = super::swatchlib::library_swatches(s, lib).filter(|l| l.iter().any(|w| w.name == *name)); + if list.is_none() { + not_found.push(name.clone()); + } + let to = r.new_color()?; + let w = list?.into_iter().find(|w| w.name == *name && w.paint.color().is_some_and(|c| same(c, to)))?; + Some(w).filter(|w| (w.global || w.spot) && mapped_adjust.is_identity()) + }) + .collect(); // A row with no current colors recolors nothing, so its swatch does not join the document. let row_swatches: Vec> = rows .iter() - .map(|r| r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned())) + .zip(picked) + .map(|(r, own)| { + r.new_color().filter(|_| !r.from.is_empty()).and_then(|c| lib_swatches.iter().find(|w| w.paint.color() == Some(c)).cloned().or(own)) + }) .collect(); // While an object of a dynamic symbol instance's art is selected, the selection is refused, as // `selected_roots` refuses it. @@ -1794,19 +1836,28 @@ fn apply(s: &mut Session, p: &Value) -> Result { // The rows' library swatches join the document (one it has with that name and colour is // used as it is). let mut added = vec![]; + // Each library swatch added under a free name, with its library name: rows that took two + // library swatches of one name both find theirs again. + let mut renamed: Vec<(String, Swatch)> = vec![]; let links: Vec> = row_swatches .iter() .zip(&rows) .map(|(w, row)| { let w = w.as_ref()?; + // A swatch is the same one when its paint, Global and spot are. + let alike = |x: &Swatch| x.paint == w.paint && x.global == w.global && x.spot == w.spot; let name = match d.swatch(&w.name) { - Some(x) if x.paint == w.paint => w.name.clone(), - _ => { - let name = d.free_swatch_name(&w.name); - d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); - added.push(name.clone()); - name - } + Some(x) if alike(x) => w.name.clone(), + _ => match renamed.iter().find(|(_, x)| x.name == w.name && alike(x)) { + Some((name, _)) => name.clone(), + None => { + let name = d.free_swatch_name(&w.name); + d.swatches.push(Swatch { name: name.clone(), ..w.clone() }); + added.push(name.clone()); + renamed.push((name.clone(), w.clone())); + name + } + }, }; let color = d.global_color(&name).filter(|_| w.global).or(w.paint.color())?; Some(Link { name, global: w.global, color, tint: row.tint }) @@ -1854,6 +1905,9 @@ fn apply(s: &mut Session, p: &Value) -> Result { })?; let mut out = json!({ "changed": changed, "swatches": added }); not_changed.report(&mut out); + if !not_found.is_empty() { + out["swatchesNotFound"] = json!(not_found); + } if let Some(e) = edit { e.defaults(s)?; out["relinked"] = json!(e.relinked()); @@ -1872,21 +1926,21 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let rows = parse_rows(p, C)?; let mut rng = Rng::new(super::menucmds::whole_or(p, "seed", 0, C)?); let (order, saturation_brightness) = (switch_or(p, "order", true, C)?, switch_or(p, "saturationBrightness", false, C)?); - // Each new color with its row's tint and model: a tint moves with its color, and goes when - // the color changes; a model moves with its color. A row with no current colors recolors - // nothing, so it keeps its new color and takes no other row's. + // Each new color with its row's tint, model and swatch: a tint and a swatch move with their + // color, and go when the color changes; a model moves with its color. A row with no current + // colors recolors nothing, so it keeps its new color and takes no other row's. let takes = |r: &Row| !r.from.is_empty() && r.new_color().is_some(); - let mut news: Vec<(Color, f32, Option)> = - rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model))).collect(); + type New = (Color, f32, Option, Option<(String, String)>); + let mut news: Vec = rows.iter().filter(|r| takes(r)).filter_map(|r| r.new_color().map(|c| (c, r.tint, r.model, r.swatch.clone()))).collect(); if order { rng.shuffle(&mut news); } if saturation_brightness { news = news .into_iter() - .map(|(c, tint, model)| { + .map(|(c, tint, model, swatch)| { let n = rng.saturation_brightness(c); - (n, if ColorKey::of(&n) == ColorKey::of(&c) { tint } else { 1.0 }, model) + if ColorKey::of(&n) == ColorKey::of(&c) { (n, tint, model, swatch) } else { (n, 1.0, model, None) } }) .collect(); } @@ -1894,8 +1948,11 @@ fn randomize(_: &mut Session, p: &Value) -> Result { let map: Vec = rows .iter() .map(|r| { - let (to, tint, model) = - if takes(r) { news.next().map_or((None, 1.0, None), |(c, t, m)| (Some(c), t, m)) } else { (r.to, r.tint, r.model) }; + let (to, tint, model, swatch) = if takes(r) { + news.next().map_or((None, 1.0, None, None), |(c, t, m, w)| (Some(c), t, m, w)) + } else { + (r.to, r.tint, r.model, r.swatch.clone()) + }; let mut row = json!({"from": r.from.iter().map(Match::to_json).collect::>(), "to": to.as_ref().map(key_str)}); if r.exclude { row["exclude"] = json!(true); @@ -1906,6 +1963,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result { if let Some(m) = model { row["model"] = json!(m.id()); } + if let Some((library, name)) = swatch { + row["swatch"] = json!({"name": name, "library": library}); + } if r.added { row["added"] = json!(true); } diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index fe87c1f7a0..2d11b9b1af 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -855,6 +855,204 @@ fn a_rows_tint_tints_the_spot_color_the_art_links_to() { assert!(e.to_string().contains("`tint` must be a number"), "{e}"); } +/// A row's `swatch` (the swatch its new color was picked from) links its art to that swatch without +/// Limit to Library: a spot or global swatch gives linked tints, and a process swatch, a swatch +/// whose color is not the row's new color and a swatch that is not there link nothing. A `swatch` +/// that is not `{name, library?}` is refused. Randomize moves the swatch with its color. +#[test] +fn a_rows_swatch_links_its_art_without_limit_to_library() { + for (options, linked) in [(json!({"spot": true}), true), (json!({"global": true}), true), (json!({}), false)] { + let mut s = session(); + let mut w = json!({"name": "Ink", "color": "cmyk 0 100 0 0"}); + w.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let dark = rect(&mut s, json!("gray 80")); + let light = rect(&mut s, json!("gray 40")); + select_all(&mut s); + let row = |swatch: Value| json!([{"from": ["gray 80", "gray 40"], "to": "cmyk 0 100 0 0", "swatch": swatch}]); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints"})); + let d = &s.doc().unwrap().doc; + let paint = |id: NodeId| match d.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, tint } => (color, swatch, tint), + p => panic!("{p:?}"), + }; + let ((c1, l1, t1), (c2, l2, t2)) = (paint(dark), paint(light)); + assert_eq!(l1.is_some() && l2.is_some(), linked, "{options}: {l1:?} {l2:?}"); + // A process swatch's row keeps the art's gray model (see the next test). + if linked { + assert!(t1 > t2 && t2 > 0.0, "{options}: the lighter gray is a lighter tint: {t1} {t2}"); + assert!(close(c1, Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: {c1:?}"); + } + assert!(!close(c2, c1), "{options}: {c1:?} {c2:?}"); + // Without the swatch the same row gives tints with no link. + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + run(&mut s, "recolor.apply", json!({"map": row(Value::Null), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: no swatch, no link"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch of another color than the row's new color links nothing. + let other = json!([{"from": ["gray 80", "gray 40"], "to": "#00ff00", "swatch": {"name": "Ink", "library": "document"}}]); + run(&mut s, "recolor.apply", json!({"map": other, "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: another color"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // With a Global Adjust the art takes the adjusted colors, not the swatch. + let adjust = json!({"saturation": -40}); + run(&mut s, "recolor.apply", json!({"map": row(json!({"name": "Ink"})), "method": "scaleTints", "globalAdjust": adjust})); + assert_eq!(paint_link(&s, dark), None, "{options}: adjusted"); + assert!(!close(fill(&s, dark), Color::cmyk(0.0, 1.0, 0.0, 0.0)), "{options}: the adjustment applies"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // A swatch or library that is not there (deleted since the pick) links nothing, and the result + // names it. + for gone in [json!({"name": "Missing"}), json!({"name": "Ink", "library": "nowhere"})] { + let r = run(&mut s, "recolor.apply", json!({"map": row(gone.clone()), "method": "scaleTints"})); + assert_eq!(paint_link(&s, dark), None, "{options}: {gone}"); + assert_eq!(r["swatchesNotFound"], json!([gone["name"]]), "{options}: {r}"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + } + for bad in [json!("Ink"), json!({"name": ""}), json!({"name": "Ink", "library": 3})] { + let e = s.execute("recolor.apply", &json!({"map": row(bad.clone())})).unwrap_err(); + assert!(e.to_string().contains("`swatch` must be"), "{bad}: {e}"); + } + let two = json!([ + {"from": ["gray 80"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink"}}, + {"from": ["gray 40"], "to": "#00ff00"}, + ]); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "seed": 3})); + let rows = r["map"].as_array().unwrap(); + let ink = rows.iter().find(|r| r["to"] == "cmyk 0 100 0 0").unwrap(); + let green = rows.iter().find(|r| r["to"] == "rgb 0 255 0").unwrap(); + assert_eq!(ink["swatch"], json!({"name": "Ink", "library": "document"}), "{r}"); + assert!(green.get("swatch").is_none(), "{r}"); + let r = run(&mut s, "recolor.randomize", json!({"map": two, "order": false, "saturationBrightness": true, "seed": 3})); + assert!(r["map"].as_array().unwrap().iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}"); + } +} + +/// A swatch whose components are finer than a color key's hundredths still links the art of the row +/// whose new color is its key. +#[test] +fn a_rows_swatch_with_a_finer_color_than_its_key_still_links() { + let mut s = session(); + let ink = Color::cmyk(0.123_456, 0.876_543, 0.0, 0.0); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0.123_456, "m": 0.876_543, "y": 0.0, "k": 0.0}, "spot": true})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let to = vectorcraft_color::recolor::ColorKey::of(&ink).to_string(); + run(&mut s, "recolor.apply", json!({"map": [{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink"}}], "method": "scaleTints"})); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), ink), "the swatch's own color: {:?}", fill(&s, id)); +} + +/// A row's `swatch` from a loaded library links the art to it and adds it to the document's +/// swatches; of two library swatches with the same name, the one with the row's new color is used, +/// and rows that pick the same one link to one added swatch; of a process and a spot swatch with +/// one name and color, the first is used; and a process swatch recolors as the row's new color +/// alone does, in the color model `model` gives. +#[test] +fn a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Twin", "color": "cmyk 100 0 0 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink", "Twin"], "name": "Inks"}))["data"].as_str().unwrap().to_string(); + // Both of the library's swatches are named Ink. + let data = data.replace("\"Twin\"", "\"Ink\""); + let lib = run(&mut s, "swatch.library.load", json!({"data": data, "name": "inks.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Ink", "Twin"]})); + let id = rect(&mut s, json!("gray 50")); + select_all(&mut s); + let row = |to: &str| json!([{"from": ["gray 50"], "to": to, "swatch": {"name": "Ink", "library": lib}}]); + let r = run(&mut s, "recolor.apply", json!({"map": row("cmyk 100 0 0 0"), "method": "scaleTints"})); + assert_eq!(r["swatches"], json!(["Ink"]), "{r}"); + let d = &s.doc().unwrap().doc; + let w = d.swatch("Ink").unwrap(); + assert!(w.spot && close(w.paint.color().unwrap(), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "the swatch of the row's color joined: {w:?}"); + assert_eq!(paint_link(&s, id).as_deref(), Some("Ink")); + assert!(close(fill(&s, id), Color::cmyk(1.0, 0.0, 0.0, 0.0)), "{:?}", fill(&s, id)); + run(&mut s, "edit.undo", json!({})); + + // Three rows that pick the magenta, the cyan and again the cyan Ink: the two cyan rows link to + // one swatch added to the document. + let more = [rect(&mut s, json!("gray 20")), rect(&mut s, json!("gray 80"))]; + select_all(&mut s); + let three = json!([ + {"from": ["gray 50"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 20"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + {"from": ["gray 80"], "to": "cmyk 100 0 0 0", "swatch": {"name": "Ink", "library": lib}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": three, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (a, b, c) = (paint_link(&s, id), paint_link(&s, more[0]), paint_link(&s, more[1])); + assert!(a.is_some() && b.is_some() && a != b && b == c, "{a:?} {b:?} {c:?}"); + run(&mut s, "edit.undo", json!({})); + + // Of a process and a spot swatch with one name and color, the first, the process one, is used. + run(&mut s, "swatch.new", json!({"name": "Pair", "color": "cmyk 0 0 100 0"})); + run(&mut s, "swatch.new", json!({"name": "Pear", "color": "cmyk 0 0 100 0", "spot": true})); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Pair", "Pear"], "name": "Pairs"}))["data"] + .as_str() + .unwrap() + .replace("\"Pear\"", "\"Pair\""); + let pairs = run(&mut s, "swatch.library.load", json!({"data": data, "name": "pairs.vcswatches"}))["library"].as_str().unwrap().to_string(); + run(&mut s, "swatch.delete", json!({"names": ["Pair", "Pear"]})); + select_all(&mut s); + let map = json!([{"from": ["gray 50"], "to": "cmyk 0 0 100 0", "swatch": {"name": "Pair", "library": pairs}}]); + run(&mut s, "recolor.apply", json!({"map": map, "method": "scaleTints"})); + assert_eq!(paint_link(&s, id), None, "the process swatch"); + run(&mut s, "edit.undo", json!({})); + + // A global process Ink and a spot Ink of one color, from two libraries, while the document's Ink + // is another color: each row links to its own added swatch. + let mut libraries = vec![]; + for (file, kind) in [("global.vcswatches", json!({"global": true})), ("spot.vcswatches", json!({"spot": true}))] { + let mut w = json!({"name": "Ink", "color": "cmyk 0 0 0 100"}); + w.as_object_mut().unwrap().extend(kind.as_object().unwrap().clone()); + run(&mut s, "swatch.new", w); + let data = run(&mut s, "swatch.library.save", json!({"names": ["Ink"], "name": file}))["data"].as_str().unwrap().to_string(); + libraries.push(run(&mut s, "swatch.library.load", json!({"data": data, "name": file}))["library"].as_str().unwrap().to_string()); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00"})); + select_all(&mut s); + let two = json!([ + {"from": ["gray 50"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[0]}}, + {"from": ["gray 20"], "to": "cmyk 0 0 0 100", "swatch": {"name": "Ink", "library": libraries[1]}}, + ]); + let r = run(&mut s, "recolor.apply", json!({"map": two, "method": "scaleTints"})); + assert_eq!(r["swatches"].as_array().map(Vec::len), Some(2), "{r}"); + let (global, spot) = (paint_link(&s, id).unwrap(), paint_link(&s, more[0]).unwrap()); + let d = &s.doc().unwrap().doc; + assert!(global != spot && !d.swatch(&global).unwrap().spot && d.swatch(&spot).unwrap().spot, "{global} {spot}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + select_all(&mut s); + + run(&mut s, "swatch.new", json!({"name": "Leaf", "color": "cmyk 60 0 100 10"})); + select_all(&mut s); + let fills = |s: &mut Session, swatch: Value, model: &str| { + let map = json!([{"from": ["gray 50"], "to": "cmyk 60 0 100 10", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "method": "scaleTints", "model": model})); + let paint = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + run(s, "edit.undo", json!({})); + select_all(s); + (paint, r.get("note").cloned()) + }; + for model in ["keep", "new", "document"] { + let alone = fills(&mut s, Value::Null, model); + assert_eq!(fills(&mut s, json!({"name": "Leaf"}), model), alone, "{model}: a process swatch is its color"); + } +} + +fn paint_link(s: &Session, id: NodeId) -> Option { + match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, .. } => swatch, + p => panic!("{p:?}"), + } +} + /// Randomize order moves a row's tint with its new color; changing saturation and brightness /// drops the tint of every color it changes. #[test] diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 52a6086816..32d1b1a565 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -707,7 +707,23 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O (edit, chosen) } +/// The field holding the swatch last clicked in the list: `{name, library, color, keep}` (see +/// [`picked_swatch`]). +const PICKED_SWATCH: &str = "__pickedSwatch"; + +/// The swatch the dialog's color was picked from, while the color is still that swatch's: for a +/// global or spot swatch `{name, library}` for a `recolor.apply` row's `swatch` and its color, and +/// for a process swatch or a swatch linked to another swatch (a tint swatch) `None` and its color. +fn picked_swatch(d: &Dialog) -> Option<(Option, Color)> { + let w = d.fields.get(PICKED_SWATCH)?; + let c = w.get("color").and_then(color_value)?; + let swatch = w["keep"].as_bool().unwrap_or(false).then(|| json!({"name": w["name"], "library": w["library"]})); + (picked(d).color == c).then_some((swatch, c)) +} + /// The document's colour swatches or a swatch library as a list; returns the clicked swatch's colour. +/// A click also records the swatch in [`PICKED_SWATCH`], with `keep` for a global or spot swatch +/// that is not linked to another one. fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Color, side: f32) -> Option { let t = Tokens::get(ui.ctx()); let mut chosen = None; @@ -740,10 +756,16 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo widgets::dim_label(ui, tl!("Open a document to see its swatches.")); return; }; - let doc = &st.doc; + // Over Recolor Artwork, the swatches as they were before its preview, which + // `recolor.apply` reads: a library swatch the preview added is not listed. + let doc = match &st.interaction { + Some(it) if d.fields.contains_key(RECOLOR_ROW) => &it.doc, + _ => &st.doc, + }; for s in doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())) { let Some(color) = s.paint.color() else { continue }; let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, color == *current, &s.name)); if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } @@ -757,13 +779,14 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo t.text, ); if resp.clicked() { - chosen = Some(color); + chosen = Some((color, s.name.clone(), (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. }))); } } } else if let Some((_, lib)) = swatchlib::library(&app.session, &cur) { for s in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| g.swatches.iter())) { let Some(color) = s.paint.color() else { continue }; let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, color == *current, &s.name)); if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } @@ -777,14 +800,17 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo t.text, ); if resp.clicked() { - chosen = Some(color); + chosen = Some((color, s.name.clone(), (s.global || s.spot) && matches!(s.paint, Paint::Solid { swatch: None, .. }))); } } } }); }); }); - chosen + let (color, name, keep) = chosen?; + let library = Some(d.str("library")).filter(|l| !l.is_empty()).unwrap_or_else(|| swatchlib::DOCUMENT_SWATCHES.to_string()); + d.fields.insert(PICKED_SWATCH.into(), json!({"name": name, "library": library, "color": color_json(&color), "keep": keep})); + Some(color) } /// OK: apply the colour to the proxy, keeping the live preview as one undo step. For an artboard, @@ -818,8 +844,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } if let Some(row) = d.fields.get(RECOLOR_ROW).and_then(Value::as_u64) { let parent = super::parent(d).ok_or("Recolor Artwork is no longer open")?; - let c = in_document_model(app, picked(d).color); - app.ui.dialog = Some(super::recolor::with_new_color(app, parent, usize::try_from(row).unwrap_or(usize::MAX), c)); + let row = usize::try_from(row).unwrap_or(usize::MAX); + // A color picked from a global or spot swatch is that swatch, in its own color model; one + // picked from another swatch takes the row's swatch away. + app.ui.dialog = Some(match picked_swatch(d) { + Some((Some(swatch), c)) => super::recolor::with_new_swatch(app, parent, row, c, Some(swatch)), + Some((None, _)) => super::recolor::with_new_swatch(app, parent, row, in_document_model(app, picked(d).color), None), + None => super::recolor::with_new_color(app, parent, row, in_document_model(app, picked(d).color)), + }); return Ok(Value::Null); } if d.bool("keep") && !app.session.in_interaction() && d.fields.get("original").and_then(color_value) == Some(picked(d).color) { diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1b80ce5e35..1c32bb5ec1 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -84,7 +84,9 @@ //! or redo. //! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot -//! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true` +//! color, added?, swatch?: {name, library} of the global or spot swatch the Color Picker's +//! swatches gave the new color, which links the row's art to it}]; a row with no current colors, +//! `from: []`, recolors no art, and with `added: true` //! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color; //! `base: true`, the base color, else the first color the Edit tab shows; `tie: n` on a marker and //! `follows: n` on a color added on its line, which moves with it; the dialog sends `recolor.apply` @@ -1082,21 +1084,26 @@ fn set_to(row: &mut Value, c: &Color) { if let Some(r) = row.as_object_mut() { r.remove("tint"); r.remove("model"); + r.remove(SWATCH); } } +/// A row's `swatch`: the swatch its new color was picked from (`recolor.apply`'s row `swatch`). +const SWATCH: &str = "swatch"; + /// Set for the frame in which Randomly change color order shuffled the rows' new colors. const SHUFFLED: &str = "__shuffled"; /// Give each row of `rows` whose current colors and new color are those of the same row of -/// `before` that row's tint and model again, when it has none: a change that snaps back to the -/// same new color keeps the tint of it and the model a slider edit gave it. +/// `before` that row's tint, model and swatch again, when it has none: a change that snaps back to +/// the same new color keeps the tint of it, the model a slider edit gave it and the swatch it was +/// picked from. fn keep_tints(before: &[Value], rows: &mut [Value]) { for (r, b) in rows.iter_mut().zip(before) { if r["from"] != b["from"] || r["to"] != b["to"] { continue; } - for k in ["tint", "model"] { + for k in ["tint", "model", SWATCH] { if r.get(k).is_none() && let Some(v) = b.get(k) { @@ -1481,6 +1488,33 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C d } +/// `d` with row `i`'s new color set to color `c` of a swatch picked from the Color Picker's +/// swatches: for a global or spot swatch, `swatch` (`{name, library}`), which the row keeps, so +/// `recolor.apply` links its art to it, unless Limit to Library snaps the color to another one +/// (colors compare as [`ColorKey`]s, as the row holds them); for another swatch, `None`, which +/// takes away a swatch picked for the row before, and without Limit to Library the tint it gave. +pub(super) fn with_new_swatch(app: &VectorcraftApp, d: Dialog, i: usize, c: Color, swatch: Option) -> Dialog { + let mut d = with_new_color(app, d, i, c); + let keeps_tint = !d.str("limitTo").is_empty(); + let mut rs = rows(&d); + let Some(r) = rs.get_mut(i) else { return d }; + match swatch { + Some(w) if to_color(r).is_some_and(|t| ColorKey::of(&t) == ColorKey::of(&c)) => r[SWATCH] = w, + Some(_) => return d, + None => { + let Some(o) = r.as_object_mut() else { return d }; + if o.remove(SWATCH).is_none() { + return d; + } + if !keeps_tint { + o.remove("tint"); + } + } + } + d.fields.insert("rows".into(), Value::Array(rs)); + d +} + /// The fields a step of Undo Changes and Redo Changes restores: what the art is recolored with. const STEP_FIELDS: [&str; 11] = ["rows", "colors", "method", "preserveWhite", "preserveBlack", "preserveGrays", "limitTo", "rule", "globalAdjust", THEME_PICKS, WEIGHTS]; @@ -2030,10 +2064,13 @@ fn spot_tinted(app: &VectorcraftApp, c: Color, t: f32) -> Color { fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color { let to = to_color(row).unwrap_or_default(); // Only a Lab spot color can show another color; the library lookup is skipped for the rest. - if matches!(to, Color::Lab { .. }) && d.bool("__art") && spot_of(app, d, &to).is_some() { + if matches!(to, Color::Lab { .. }) && d.bool("__art") && (spot_of(app, d, &to).is_some() || own_spot(app, d, row, &to).is_some()) { spot_tinted(app, to, row_tint(row)) - } else { + } else if row_tint(row) < 1.0 && tint_applies(app, d, row, &to) { to.tinted(row_tint(row)) + } else { + // The swatch the tint was for no longer links the art, which takes the full color. + to } } @@ -2053,6 +2090,59 @@ fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { swatchlib::library_swatches(&app.session, &lib)?.into_iter().find(|w| w.paint.color() == Some(near)).filter(|w| w.spot).map(|w| w.name) } +/// The name of the spot swatch `row`'s new color `c` was picked from (its `swatch`), while that +/// swatch has color `c` and no Global Adjust applies without Limit to Library, as `recolor.apply` +/// reads it. +fn own_spot(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> Option { + if d.str("limitTo").is_empty() && !global_adjust(adjust_values(d)).is_identity() { + return None; + } + let (name, _) = swatch_ref(row)?; + row_swatch(app, row, c).filter(|spot| *spot).map(|_| name.to_string()) +} + +/// The name and library key of `row`'s `swatch` when it is `{name, library?}` with a name, as +/// `recolor.apply` reads it. +fn swatch_ref(row: &Value) -> Option<(&str, &str)> { + let w = row.get(SWATCH)?; + let name = w.get("name")?.as_str().filter(|n| !n.is_empty())?; + let library = match w.get("library") { + None | Some(Value::Null) => swatchlib::DOCUMENT_SWATCHES, + Some(l) => l.as_str().filter(|l| !l.is_empty())?, + }; + Some((name, library)) +} + +/// Whether the swatch `row`'s `swatch` names, with color `c` (as a color key), is a spot color, +/// when it is a global or spot swatch; `None` when it is a process swatch or not there (deleted +/// since the pick). Of several swatches with that name, the first with that color counts, as +/// `recolor.apply` finds it. The document's swatches are read as they were before the preview, +/// which `recolor.apply` runs on. +fn row_swatch(app: &VectorcraftApp, row: &Value, c: &Color) -> Option { + let (name, lib) = swatch_ref(row)?; + let fits = |s: &&vectorcraft_color::swatch::Swatch| { + s.name == name + && matches!(s.paint, vectorcraft_color::Paint::Solid { swatch: None, .. }) + && s.paint.color().is_some_and(|w| ColorKey::of(&w) == ColorKey::of(c)) + }; + let found = if lib == swatchlib::DOCUMENT_SWATCHES { + let st = app.session.active()?; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatches_iter().find(fits).map(|s| (s.global || s.spot, s.spot)) + } else { + let (_, l) = swatchlib::library(&app.session, lib)?; + l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).find(fits).map(|s| (s.global || s.spot, s.spot)) + }; + found.filter(|(links, _)| *links).map(|(_, spot)| spot) +} + +/// Whether the new color chip shows `row`'s tint: with Limit to Library, when the row has no +/// `swatch`, or when its `swatch` links the art ([`row_swatch`], with no Global Adjust). A row whose +/// `swatch` links nothing recolors its art with the full color. +fn tint_applies(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> bool { + !d.str("limitTo").is_empty() || swatch_ref(row).is_none() || (global_adjust(adjust_values(d)).is_identity() && row_swatch(app, row, c).is_some()) +} + /// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else /// `c`'s own model (HSB for a gray), or Tint for a spot color (`spot`). fn slider_mode(d: &Dialog, c: &Color, spot: bool) -> Option { @@ -2098,7 +2188,7 @@ impl SliderTarget { let row = row.filter(|i| *i < rows.len()); let color = row.and_then(|i| to_color(&rows[i])); // A row tint acts only on art, so without art a spot color shows the process modes. - let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c)); + let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c).or_else(|| own_spot(app, d, &rows[row?], &c))); Self { row, color, spot } } @@ -2431,6 +2521,7 @@ fn remove_color(rows: &mut Vec, i: usize, base: Option, keep: bool if let Some(r) = rows[i].as_object_mut() { r.remove("tint"); r.remove("model"); + r.remove(SWATCH); } return Some(base.unwrap_or(0)); } @@ -3511,6 +3602,80 @@ mod tests { assert!(super::rows(&other)[0].get("tint").is_none(), "{:?}", super::rows(&other)); } + /// A spot swatch picked for a row with no Limit to Library gives the row the swatch and the + /// sliders its Tint; another new color drops the swatch, and a Global Adjust, under which + /// `recolor.apply` does not use the swatch, shows the color modes instead of Tint. + #[test] + fn a_picked_spot_swatch_gives_its_row_the_tint_slider() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": "#808080"})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": 1})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("rows".into(), json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}])); + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0); + let picked = with_new_swatch(&app, d.clone(), 0, ink, Some(json!({"name": "Ink", "library": "document"}))); + let rs = super::rows(&picked); + assert_eq!(rs[0][SWATCH], json!({"name": "Ink", "library": "document"})); + assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot.as_deref(), Some("Ink"), "the Tint slider"); + let other = with_new_color(&app, picked.clone(), 0, Color::rgb(0.0, 1.0, 0.0)); + assert!(super::rows(&other)[0].get(SWATCH).is_none(), "{:?}", super::rows(&other)); + let mut adjusted = picked; + adjusted.fields.insert("globalAdjust".into(), json!({"saturation": 20.0, "brightness": 0.0, "temperature": 0.0, "luminosity": 0.0})); + assert_eq!(SliderTarget::at(&app, &adjusted, &rs, Some(0)).spot, None, "no Tint under a Global Adjust"); + } + + /// A row's chip shows its tint while its picked swatch links the art, also while a preview + /// changes that swatch; once the swatch is deleted the chip shows the full color the art takes + /// and OK recolors with it. A process swatch picked in its place takes the row's swatch and tint + /// away. + #[test] + fn a_picked_swatch_that_is_gone_links_nothing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": "#808080"})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": 1})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("rows".into(), json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}])); + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0); + let mut picked = with_new_swatch(&app, d, 0, ink, Some(json!({"name": "Ink", "library": "document"}))); + let mut rs = super::rows(&picked); + rs[0]["tint"] = json!(40.0); + picked.fields.insert("rows".into(), Value::Array(rs)); + let rs = super::rows(&picked); + let tinted = new_shown(&app, &picked, &rs[0]); + assert!(tinted != ink && tinted.to_rgb()[1] > ink.to_rgb()[1], "the chip at 40%: {tinted:?}"); + // A process swatch of the same color picked for the row. + let process = with_new_swatch(&app, picked.clone(), 0, ink, None); + let r = &super::rows(&process)[0]; + assert!(r.get(SWATCH).is_none() && r.get("tint").is_none(), "{r}"); + // A preview that gives the swatch another color: the row still links to it. + let _ = app.session.cancel_interaction(); + app.session.begin_interaction("Swatch Options").unwrap(); + app.session.preview("swatch.edit", &json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap(); + assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot.as_deref(), Some("Ink"), "the swatch as it was before the preview"); + assert_eq!(new_shown(&app, &picked, &rs[0]), tinted); + let _ = app.session.cancel_interaction(); + app.run("swatch.delete", json!({"names": ["Ink"]})).unwrap(); + assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot, None, "no Tint slider"); + assert_eq!(new_shown(&app, &picked, &rs[0]), ink, "the full color the art takes"); + let r = app.session.execute(CMD, &apply_params(&picked)).unwrap(); + assert_eq!(r["swatchesNotFound"], json!(["Ink"]), "{r}"); + let doc = &app.session.doc().unwrap().doc; + match doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().appearance.fill_paint() { + vectorcraft_color::Paint::Solid { color, swatch, .. } => { + assert_eq!(swatch, None, "no link"); + let [r, g, b] = color.to_rgb(); + assert!(r > 0.9 && g < 0.1 && b > 0.4, "the full ink, not a 40% tint or the gray: {color:?}"); + } + p => panic!("{p:?}"), + } + } + /// With the Spot Colors options on CMYK values, a row whose new color is a Lab spot color of the /// library shows the art's color at its tint: the working-CMYK equivalent with its inks scaled. #[test] diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 986dbb6290..8823e1a0fa 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1749,6 +1749,185 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { } } +/// Each paint under `v`: where it is (`stop` for a gradient stop, `stroke`, `type` for the +/// characters of a text object, else `fill`), its color, the swatch it is linked to and its tint. +fn picked_paints(v: &Value, at: &str, out: &mut Vec<(String, Color, Option, f64)>) { + match v { + Value::Object(m) => { + if let Some(c) = m.get("color").and_then(|c| serde_json::from_value::(c.clone()).ok()) { + let (swatch, tint) = + (m.get("swatch").and_then(Value::as_str).map(String::from), m.get("tint").and_then(Value::as_f64).unwrap_or(1.0)); + out.push((at.to_string(), c, swatch, tint)); + } + // An appearance item is tagged with its `kind`; a text object's characters are its runs. + let at = if m.get("kind").and_then(Value::as_str) == Some("stroke") { "stroke" } else { at }; + for (k, x) in m { + let here = match k.as_str() { + "stops" if at != "type" => "stop", + "runs" => "type", + _ => at, + }; + picked_paints(x, here, out); + } + } + Value::Array(a) => a.iter().for_each(|x| picked_paints(x, at, out)), + _ => {} + } +} + +fn paints_now(app: &VectorcraftApp) -> Vec<(String, Color, Option, f64)> { + let d = &app.session.doc().unwrap().doc; + let mut out = vec![]; + for c in d.layers.iter().filter_map(|l| l.children()) { + picked_paints(&serde_json::to_value(c).unwrap(), "fill", &mut out); + } + out +} + +/// Every number under an `opacity` key under `v`. +fn opacities_under(v: &Value, out: &mut Vec) { + match v { + Value::Object(m) => { + out.extend(m.get("opacity").and_then(Value::as_f64)); + m.values().for_each(|x| opacities_under(x, out)); + } + Value::Array(a) => a.iter().for_each(|x| opacities_under(x, out)), + _ => {} + } +} + +fn opacities_now(app: &VectorcraftApp) -> Vec { + let mut out = vec![]; + for c in app.session.doc().unwrap().doc.layers.iter().filter_map(|l| l.children()) { + opacities_under(&serde_json::to_value(c).unwrap(), &mut out); + } + out +} + +/// The lightness of a gray other than black and white. +fn mid_gray(c: &Color) -> Option { + let [r, g, b] = c.to_rgb(); + ((r - g).abs() < 1e-3 && (g - b).abs() < 1e-3 && r > 0.01 && r < 0.99).then_some(r) +} + +/// Gray art placed from an SVG file (fills, a stroke, a group at 50% opacity, `fill-opacity`, an +/// even-odd compound path, a gradient's stops and type), recolored with one color, Scale Tints or +/// Preserve Tints and no Limit to Library, takes the swatch picked for its row in the Color Picker's +/// swatch list: a spot or global swatch gives tints of it linked to it, darker grays at higher +/// tints, with the opacities kept, and editing the swatch recolors every one of them at the same +/// tints; a process swatch gives tints of its color with no link, as a color picked any other way. With Preserve Black on, black stays black; with it +/// off, black takes the full ink. +#[test] +fn a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library() { + use egui::accesskit::Role; + + let svg = r##"Gray"##; + let path = std::env::temp_dir().join(format!("vectorcraft-recolor-picked-swatch-{}.svg", std::process::id())); + std::fs::write(&path, svg).unwrap(); + let cases = [ + ("spot", json!({"spot": true}), true, true, "scaleTints"), + ("spot, Preserve Black off", json!({"spot": true}), true, false, "scaleTints"), + ("spot, Preserve Tints", json!({"spot": true}), true, true, "preserveTints"), + ("global", json!({"global": true}), true, true, "scaleTints"), + ("process", json!({}), false, true, "scaleTints"), + ]; + for (kind, options, linked, preserve_black, method) in cases { + let mut app = app(); + // The swatch list then shows Ink without scrolling. + let doc = &app.session.doc().unwrap().doc; + let names: Vec<_> = doc + .swatches + .iter() + .filter(|s| !s.is_reserved()) + .map(|s| s.name.clone()) + .chain(doc.swatch_groups.iter().map(|g| g.name.clone())) + .collect(); + app.run("swatch.delete", json!({"names": names})).unwrap(); + let mut swatch = json!({"name": "Ink", "color": "cmyk 0 100 0 0"}); + swatch.as_object_mut().unwrap().extend(options.as_object().unwrap().clone()); + app.run("swatch.new", swatch).unwrap(); + app.run("file.place", json!({"path": path.to_string_lossy(), "at": [120, 50]})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let before = paints_now(&app); + let opacities = opacities_now(&app); + assert!(opacities.iter().any(|o| (o - 0.5).abs() < 1e-6) && opacities.iter().any(|o| (o - 0.7).abs() < 1e-6), "{opacities:?}"); + let black = |c: &Color| c.to_rgb().iter().all(|v| *v < 0.01); + // The paints the ink takes: every mid gray, and black too without Preserve Black. + let inked: Vec = (0..before.len()).filter(|&i| mid_gray(&before[i].1).is_some() || !preserve_black && black(&before[i].1)).collect(); + for at in ["fill", "stroke", "stop", "type"] { + assert!(inked.iter().any(|&i| before[i].0 == at), "{kind}: gray {at} paints came in: {before:?}"); + } + + let mut h = assign_harness(app, json!({"colors": 1})); + set(h.state_mut(), "method", json!(method)); + set(h.state_mut(), "preserveBlack", json!(preserve_black)); + h.run_steps(3); + let rows = field(h.state(), "rows"); + let rows = rows.as_array().unwrap(); + let row = rows.iter().position(|r| !r["exclude"].as_bool().unwrap_or(false)).unwrap(); + assert_eq!(rows.iter().filter(|r| !r["exclude"].as_bool().unwrap_or(false)).count(), 1, "{kind}: one row: {rows:?}"); + assert_eq!(field(h.state(), "limitTo"), json!(""), "no library"); + row_context_menu(&mut h, row); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Ink").click(); + h.run_steps(2); + let picker = h.state().ui.dialog.as_ref().unwrap(); + assert_eq!( + picker.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), + Some(Color::cmyk(0.0, 1.0, 0.0, 0.0)), + "{:?}", + picker.fields + ); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); + // A process swatch gives the row its color alone. + let swatch = linked.then(|| json!({"name": "Ink", "library": "document"})); + assert_eq!(field(h.state(), "rows")[row].get("swatch").cloned(), swatch, "{kind}: the row keeps a global or spot swatch"); + let app = h.state_mut(); + dialogs::confirm(app).unwrap(); + assert!(app.ui.dialog.is_none()); + + let after = paints_now(app); + assert_eq!(after.len(), before.len(), "{kind}: the art has the same paints"); + assert_eq!(opacities_now(app), opacities, "{kind}: the opacities are kept"); + for (i, (b, a)) in before.iter().zip(&after).enumerate() { + if !inked.contains(&i) { + assert_eq!(a.1, b.1, "{kind}: paint {i} keeps its color"); + } + } + for &i in &inked { + assert!(mid_gray(&after[i].1).is_none() && !black(&after[i].1), "{kind}: paint {i} took the ink: {:?}", after[i]); + assert_eq!(after[i].2.as_deref(), linked.then_some("Ink"), "{kind}: paint {i} linked"); + } + if linked { + // Darker grays take higher tints. + for &i in &inked { + for &j in &inked { + let (li, lj) = (mid_gray(&before[i].1).unwrap_or(0.0), mid_gray(&before[j].1).unwrap_or(0.0)); + if li < lj - 0.02 { + assert!(after[i].3 >= after[j].3, "{kind}: paint {i} is darker than {j} and at a higher tint"); + } + } + } + let r = app.run("swatch.edit", json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap(); + let edited = paints_now(app); + for &i in &inked { + let (at, c, link, tint) = &edited[i]; + assert_eq!((link.as_deref(), *tint), (Some("Ink"), after[i].3), "{kind}: paint {i} ({at}) keeps its link and tint"); + assert!(c.to_rgb()[0] < after[i].1.to_rgb()[0] && c != &after[i].1, "{kind}: paint {i} ({at}) shows the edited ink: {c:?}"); + } + // swatch.edit counts every paint that follows it, a gradient as one paint however many + // of its stops follow (the art holds one gradient). + let stops = inked.iter().filter(|&&i| before[i].0 == "stop").count(); + let paints = inked.len() - stops + usize::from(stops > 0); + assert_eq!(r["relinked"].as_u64(), u64::try_from(paints).ok(), "{kind}: every inked paint follows the swatch: {r}"); + } + } + let _ = std::fs::remove_file(&path); +} + /// Whether the dialog's button `name` is disabled. fn disabled(h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str) -> bool { h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled() diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..9bba7e67c1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5566,8 +5566,18 @@ empty row does not count toward Colors. While it is empty and not `added`, the d the base color when the empty row is selected), the harmony rules, linked moves and the Color Theme Picker leave its new color as it is, and Save All Colors and a new color group saved from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art -linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize` -moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo +linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. A row's +`swatch: {name, library?}` names the swatch its new color was picked from (`library` is a swatch library id or name, +default `"document"`): of the swatches with that name, the first with the row's new color (compared as color keys, +which round) is used. While it is a global or spot swatch and there is no Global Adjust (or `limitTo` is given), the +row's art takes the swatch as it would with `limitTo`, linked to it at its tints (and its `tint` applies), and a library +swatch joins the document's swatches. A process swatch, or a swatch or library that is not there (such as a swatch +deleted after it was picked), links nothing, and the row recolors as its new color alone does; the result's +`swatchesNotFound` lists the names of the swatches that are not there. A row whose new color is +picked from a global or spot swatch in the Color Picker's swatch list in Recolor Artwork carries it, so with no Limit to +Library the art still takes the swatch picked; the dialog drops a row's `swatch` when the row's new color changes. A +`swatch` that is not `{name, library?}` is an error. `recolor.randomize` +moves a row's `tint` and `swatch` with its new color and removes them from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that names a swatch's color, rounded to the key's steps, counts as that color, and the swatch keeps its color unrounded. And `recolor.apply` with `group` recolours the art and rewrites the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..cb88bca758 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2033,6 +2033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list stays that swatch, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider` and `a_picked_swatch_that_is_gone_links_nothing` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From f19e114c40227c04e6b8e8a959d852f38ef45d08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:32:54 -0800 Subject: [PATCH 041/533] Scripts: a waiting palette event a handler made its control refuse is dropped A click or change that waits for a palette's run is checked against the palette's controls again before its run starts. When an earlier handler disabled or hid the control, the event is dropped. A list's change whose list a run changed since still ends its run with the error that says so, unless the list can no longer take a change. --- crates/engine/src/script/palettes.rs | 20 ++++++++- crates/engine/src/tests/script_palettes.rs | 48 ++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 5da1b6e888..6fdd49b45b 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -184,7 +184,8 @@ impl Palettes { /// The oldest waiting event whose palette is still shown, given to the control at its place in /// the palette as the runs since left it, and that palette. An event whose control the palette - /// no longer has is dropped. + /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for + /// example because a handler disabled or hid it, is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { while let Some(mut q) = self.waiting.pop_front() { let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; @@ -192,6 +193,23 @@ impl Palettes { let Some(at) = p.dialog.control_at(&q.place) else { continue }; *c = at; } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { + continue; + } + } else { + let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; + q.event = event; + } return Some((p.clone(), q)); } None diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 9c4b7be294..7078442ac2 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,32 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { let mut s = one_doc(); @@ -174,6 +200,28 @@ fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button( assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); } +#[test] +fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/docs/mcp.md b/docs/mcp.md index eee919e83c..2bc012fe73 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2989,7 +2989,8 @@ the same controls, handlers and limits: goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, with the newer value. A waiting click or change, and a text typed in a field, stay with their control when a - run adds controls before it; a waiting event whose control is gone is dropped. A list's change ends its run + run adds controls before it. A waiting event whose control is gone, or that its control can no longer take + because a handler disabled or hid it, is dropped. A list's change ends its run with an error when a script added or removed the list's items after the person chose, even if the list again holds the same texts. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and From 9cbbb23e01e240dbec9b7801f671a529f3b95150 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:58:52 -0800 Subject: [PATCH 042/533] Scripts: a palette event waiting for an open undo group asks for no frames While an undo group is open, a palette event's run cannot start. The app asked for a new frame every frame while the event waited, so it never went idle. It now asks for the next frame at once only when the run can start, and otherwise looks again four times a second. --- crates/engine/src/script/palettes.rs | 10 +++++++ crates/ui-egui/src/app.rs | 7 +++-- crates/ui-egui/src/tests/script_palettes.rs | 31 +++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 6fdd49b45b..1336a6a7f3 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -329,6 +329,16 @@ impl Session { self.script_palettes.waiting.len() } + /// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event + /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in + /// progress is not counted, since starting the run settles it. + pub fn script_palette_can_start(&self) -> bool { + !self.script_palettes.waiting.is_empty() + && !self.script_running() + && self.explicit_undo_group.is_none() + && self.docs.iter().all(|d| d.undo_group.is_none()) + } + /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going /// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it /// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bd2bba2159..b52abc1a7a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -369,9 +369,12 @@ impl VectorcraftApp { crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::poll(self, ctx); // A palette event whose run starts on the next frame. While a run goes on, the block below - // asks for its frames, and a run that waits for the person goes on at their next input. - if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + // asks for its frames, and a run that waits for the person goes on at their next input. An + // event that waits for an open undo group to end looks again four times a second. + if self.session.script_palette_can_start() { ctx.request_repaint(); + } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 56cd162316..877548d602 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,37 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[test] +fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + app.run("edit.undoGroup.begin", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames while the undo group is open"); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + app.begin_host_iteration(); + frame(&ctx, |ui| app.tick(ui.ctx())); + assert_eq!(app.session.script_palette_events_waiting(), 0, "with the group ended the next frame starts the click's run"); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); From 61b7c8dbe1dbbf3bf1e7bc902287a2e1b085af94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:13:29 -0800 Subject: [PATCH 043/533] Scripts: new DocumentPreset and imageCapture keep their limits for every link - new DocumentPreset() counts its default settings toward the 4 MB the presets of a run hold together, and throws a RangeError instead of passing it, as a setter does. - imageCapture refuses a file at the relative path of every linked image, also when two images share a path and content but keep different relative paths; before, only the first one's was protected. --- crates/engine/src/cmd/links.rs | 35 +++++++++++++------ crates/engine/src/script/dom.rs | 7 +++- crates/engine/src/tests/script_dom.rs | 17 +++++++++ .../engine/src/tests/script_raster_capture.rs | 20 +++++++++++ 4 files changed, 68 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 4d6c2c8b39..ff420c436e 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -165,6 +165,9 @@ struct Group { document: Option, /// An image placed from a DCS file: the plate files of their own its plates were read from. plate_files: Vec, + /// The stored relative paths of the group's objects other than `link`'s, each once: objects + /// with the same path and content can each keep a relative path of its own. + other_relatives: Vec, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -198,17 +201,22 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { /// from, wherever it is stored, brush art included, whether or not a file is there: each place /// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, /// as its plate-change check finds them. A link's absolute stored and relative paths are listed -/// as they are too. +/// as they are too, for the relative path of every object in a group. pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { - let link = &g.link; - let mut mains: Vec = - std::iter::once(link.path.as_str()).chain(link.relative.as_deref()).filter(|p| Path::new(p).is_absolute()).map(str::to_string).collect(); - mains.extend(places(link, base)); - for main in mains { - out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); - out.push(main); + let others = g.other_relatives.iter().map(|r| LinkInfo { relative: Some(r.clone()), ..g.link.clone() }); + for link in std::iter::once(g.link.clone()).chain(others) { + let mut mains: Vec = std::iter::once(link.path.as_str()) + .chain(link.relative.as_deref()) + .filter(|p| Path::new(p).is_absolute()) + .map(str::to_string) + .collect(); + mains.extend(places(&link, base)); + for main in mains { + out.extend(g.plate_files.iter().filter_map(|f| super::place::dcs::plate_file_path(&main, &f.name))); + out.push(main); + } } } out @@ -231,10 +239,17 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files }); + out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files, other_relatives: vec![] }); out.len() - 1 }); - if let (Some(id), Some(g)) = (id, out.get_mut(i)) { + let Some(g) = out.get_mut(i) else { return }; + if let Some(r) = &link.relative + && g.link.relative.as_ref() != Some(r) + && !g.other_relatives.contains(r) + { + g.other_relatives.push(r.clone()); + } + if let Some(id) = id { g.ids.push(id); } }; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d651d82867..871cd94370 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -967,7 +967,12 @@ fn new_preset(h: &Host) -> Answer { item("numArtboards", num(1.0)), item("width", num(612.0)), ]; - h.dom.preset_bytes.set(h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::())); + // The defaults count toward MAX_PRESET_BYTES as the setter counts a value. + let kept = h.dom.preset_bytes.get().saturating_add(fields.iter().map(|(_, v)| data_size(v)).sum::()); + if kept > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("the DocumentPresets of a script can hold at most {} MB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(kept); presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c64aee6ec2..bc8f71199a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -873,6 +873,23 @@ fn document_preset_settings_are_limited_in_bytes() { assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); } +/// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the +/// limit is refused and leaves the count as it was. +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + let mut s = Session::new(); + // The six defaults hold 74 bytes; the two strings leave 10 bytes of the 4 MB free. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.title = new Array(2097153).join('a'); p.units = new Array(2097065).join('b');\ + try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ + p.colorMode = 1; vc.log(p.colorMode); p.title = 'x'; vc.log(new DocumentPreset().width);", + ); + assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); + assert_eq!(out[1], json!(1), "a refused preset adds nothing to the count"); + assert_eq!(out[2], json!(612), "a preset below the limit is still made"); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 610882b419..863b5d1db6 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -653,6 +653,26 @@ fn capture_to_a_templates_relative_link_writes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Two images that share a stale path and a content but keep different relative paths are each +/// looked for at their own relative path, so a capture over either one's file is refused. +#[test] +fn capture_over_either_relative_path_of_one_linked_content_writes_nothing() { + let base = folder("two-relatives"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + let stale = base.join("outside/gone/pic.png").to_string_lossy().into_owned(); + for relative in ["a.png", "b.png"] { + place_linked(&mut s, "pic", vectorcraft_doc::LinkInfo { path: stale.clone(), relative: Some(relative.into()), ..Default::default() }); + } + for name in ["a.png", "b.png"] { + let target = dir.join(name); + let e = file_failure(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{name}: {e}"); + assert!(!target.exists(), "{name}: nothing written"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A DCS image whose stored path is stale reads its plate files beside the main file its relative /// path finds, so a capture over one of those is refused. #[test] From 50dcc11e4dd7da5fd6410c91e7a228a4f4ca9b8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:19:15 -0800 Subject: [PATCH 044/533] Plug-ins: keep waiting events to the changes each plug-in was given - A waiting event names each recipient by its installation serial too, so a module that another session removed and installed again is not given an event from before. - A merged layer.changed keeps the reasons per plug-in: one installed between two changes is given only the later change's reasons. - Delivery waits while an interaction is open; the events go out at the first delivery after it ends. - A failed top-level request still delivers what finished before the failure, such as a save in a command.batch whose later step fails. A document.opened for a document that the rollback closes again (a batch, or a failed command of a script or a plug-in call) is dropped. - An event's handler checks the deadline before vc_alloc and before vc_event. - The shared-budget test uses a small instruction budget and checks for an instruction-budget error, and the UI test removes its plug-in when it ends. --- crates/engine/src/cmd/fileio/batch.rs | 3 + crates/engine/src/plugin_events.rs | 118 ++++++++++++++++------- crates/engine/src/script/mod.rs | 5 + crates/engine/src/session/execute.rs | 3 + crates/engine/src/tests/plugin_events.rs | 90 +++++++++++++++++ crates/plugins/src/runtime.rs | 3 + crates/plugins/tests/abi.rs | 23 +++-- crates/ui-egui/src/tests/script_run.rs | 11 +++ docs/plugins.md | 3 +- 9 files changed, 213 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..316fae8573 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -25,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + let opens = s.plugin_events_mark(); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); // The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback. @@ -39,6 +40,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } Err(e) => { roll_back(s, start, &stash); + // The documents the steps opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); s.active = active; s.sync_front_profiles(); diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 9951904991..552d93bd21 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -7,9 +7,10 @@ //! - A check runs after each top-level command, or when a frontend that sets //! [`Session::plugin_event_frames`] delivers ([`Session::deliver_plugin_events`]), by the frame. //! Changes between two checks are one event: a burst of selection changes is one -//! `selection.changed` with the final selection. No check runs while an interaction is open (a -//! drag being previewed). A document opened or created since the last check is compared with how -//! it was when the command that added it ended ([`Session::plugin_events_see_new_documents`]). +//! `selection.changed` with the final selection. No check or delivery runs while an interaction +//! is open (a drag being previewed); waiting events wait for it to end. A document opened or +//! created since the last check is compared with how it was when the command that added it ended +//! ([`Session::plugin_events_see_new_documents`]). //! - At most [`MAX_PENDING`] events wait; past that the oldest is dropped. An event raised while a //! handler runs waits for the next delivery: handlers never run inside one another. //! - A handler only reads. The host applies nothing it returns, and it may call only the commands @@ -48,22 +49,36 @@ struct Seen { layer: Option, } -/// A plug-in an event is for: its id and the hash of its module. -type Recipient = (String, String); +/// A plug-in an event is for: its id, the hash of its module and its installation +/// ([`Plugin::serial`]), so a module removed and installed again is another recipient. +type Recipient = (String, String, u64); /// The recipient `p` is. fn recipient(p: &Plugin) -> Recipient { - (p.id().to_string(), p.hash().to_string()) + (p.id().to_string(), p.hash().to_string(), p.serial()) } -/// An event waiting for delivery: what changed, in which document, for `layer.changed` why, and -/// the plug-ins it is for: those installed when it happened. +/// An event waiting for delivery: what changed, in which document, and the plug-ins it is for +/// (those installed when it happened), each with the reasons of a `layer.changed` it was given. #[derive(Clone, Debug, PartialEq)] struct Pending { event: Event, document: u64, - reasons: Vec<&'static str>, - to: Vec, + to: Vec<(Recipient, Vec<&'static str>)>, + /// When it was queued ([`PluginEvents::queued`] then). + seq: u64, +} + +impl Pending { + /// Whether this event is for `r`. + fn is_for(&self, r: &Recipient) -> bool { + self.to.iter().any(|(x, _)| x == r) + } + + /// The reasons of a `layer.changed` that `r` is given. + fn reasons_for(&self, r: &Recipient) -> &[&'static str] { + self.to.iter().find(|(x, _)| x == r).map_or(&[], |(_, reasons)| reasons.as_slice()) + } } /// One plug-in's failed handlers in a row, for the module with `hash`. @@ -95,6 +110,8 @@ pub struct PluginEvents { /// The plug-ins that reacted to events when `seen` was taken. seen_by: Vec, pending: VecDeque, + /// How many events have been queued as their own entry. + queued: u64, dispatching: bool, failures: BTreeMap, notices: VecDeque, @@ -119,24 +136,30 @@ impl PluginEvents { subs } - /// Queues `event` for document `uid`, for the plug-ins `to`. A `selection.changed` or - /// `layer.changed` already waiting for that document takes it in (a layer event adds the new - /// reasons to its own, and the new plug-ins to its own); past [`MAX_PENDING`] the oldest event is - /// dropped. + /// Queues `event` for document `uid`, for the plug-ins `to`, with the reasons of a + /// `layer.changed`. A `selection.changed` or `layer.changed` already waiting for that document + /// takes it in: each plug-in in `to` is added, or adds the new reasons to the ones it was given, + /// so a plug-in is given only the reasons of the changes it was given. Past [`MAX_PENDING`] the + /// oldest event is dropped. fn queue(&mut self, event: Event, uid: u64, reasons: Vec<&'static str>, to: Vec) { if matches!(event, Event::SelectionChanged | Event::LayerChanged) && let Some(p) = self.pending.iter_mut().find(|p| p.event == event && p.document == uid) { - for r in reasons { - if !p.reasons.contains(&r) { - p.reasons.push(r); - } - } - p.reasons.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); for r in to { - if !p.to.contains(&r) { - p.to.push(r); + let i = match p.to.iter().position(|(x, _)| *x == r) { + Some(i) => i, + None => { + p.to.push((r, Vec::new())); + p.to.len() - 1 + } + }; + let given = &mut p.to[i].1; + for reason in &reasons { + if !given.contains(reason) { + given.push(*reason); + } } + given.sort_by_key(|r| LAYER_REASONS.iter().position(|x| x == r)); } return; } @@ -145,7 +168,9 @@ impl PluginEvents { { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } - self.pending.push_back(Pending { event, document: uid, reasons, to }); + let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.queued += 1; } fn notice(&mut self, n: Notice) { @@ -247,6 +272,18 @@ impl Session { self.plugin_events.queue(event, uid, Vec::new(), to); } + /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. + pub(crate) fn plugin_events_mark(&self) -> u64 { + self.plugin_events.queued + } + + /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback + /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The + /// saves stay, since the files they wrote stay written. + pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { + self.plugin_events.pending.retain(|p| p.event != Event::DocumentOpened || p.seq < mark); + } + /// Compares each open document with how the last check saw it and queues the events its changes /// give the installed plug-ins: `selection.changed` and `layer.changed`. A document neither the /// last check nor [`Session::plugin_events_see_new_documents`] saw gives none, and a plug-in @@ -264,7 +301,7 @@ impl Session { } let installed: Vec = subs.iter().map(|p| recipient(p)).collect(); self.plugin_events.pending.retain_mut(|p| { - p.to.retain(|r| installed.contains(r)); + p.to.retain(|(r, _)| installed.contains(r)); !p.to.is_empty() }); if self.docs.iter().any(|d| d.interaction.is_some()) { @@ -300,13 +337,14 @@ impl Session { /// Checks the open documents for changes ([`Session::check_plugin_events`]) and calls the /// handlers of the events waiting, oldest first, one handler at a time. While a handler runs, - /// this returns at once: what the handler's calls change waits for the next delivery. + /// this returns at once: what the handler's calls change waits for the next delivery. While an + /// interaction is open, the events wait for the first delivery after it ends. pub fn deliver_plugin_events(&mut self) { if self.plugin_events.dispatching { return; } self.check_plugin_events(); - if self.plugin_events.pending.is_empty() { + if self.plugin_events.pending.is_empty() || self.docs.iter().any(|d| d.interaction.is_some()) { return; } let subs = self.plugin_events.subscribers(); @@ -319,7 +357,7 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } - for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.to.contains(&recipient(s))) { + for plugin in subs.iter().filter(|s| s.manifest().reacts_to(p.event) && p.is_for(&recipient(s))) { if self.plugin_events.failures_of(plugin).disabled { continue; } @@ -348,7 +386,7 @@ impl Session { } Event::LayerChanged => { v["layer"] = json!(st.active_layer.map(|l| l.0)); - v["reasons"] = json!(p.reasons); + v["reasons"] = json!(p.reasons_for(&recipient(plugin))); } Event::DocumentOpened | Event::DocumentSaved => {} } @@ -449,27 +487,33 @@ impl Session { mod tests { use super::*; + /// Waiting selection and layer events of a document merge; each plug-in keeps the reasons of + /// the changes it was given. #[test] fn waiting_selection_and_layer_events_of_a_document_merge() { + let (a, b): (Recipient, Recipient) = (("a".into(), "1".into(), 1), ("b".into(), "2".into(), 2)); let mut e = PluginEvents::default(); - e.queue(Event::SelectionChanged, 1, vec![], vec![]); - e.queue(Event::LayerChanged, 1, vec!["options"], vec![]); - e.queue(Event::SelectionChanged, 1, vec![], vec![]); - e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![]); - e.queue(Event::SelectionChanged, 2, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - e.queue(Event::DocumentSaved, 1, vec![], vec![]); - let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons.clone())).collect(); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["options"], vec![a.clone()]); + e.queue(Event::SelectionChanged, 1, vec![], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["current", "options"], vec![a.clone()]); + e.queue(Event::LayerChanged, 1, vec!["deleted", "current"], vec![a.clone(), b.clone()]); + e.queue(Event::SelectionChanged, 2, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + e.queue(Event::DocumentSaved, 1, vec![], vec![a.clone()]); + let got: Vec<(Event, u64, Vec<&str>)> = e.pending.iter().map(|p| (p.event, p.document, p.reasons_for(&a).to_vec())).collect(); assert_eq!( got, [ (Event::SelectionChanged, 1, vec![]), - (Event::LayerChanged, 1, vec!["current", "options"]), + (Event::LayerChanged, 1, vec!["current", "deleted", "options"]), (Event::SelectionChanged, 2, vec![]), (Event::DocumentSaved, 1, vec![]), (Event::DocumentSaved, 1, vec![]), ] ); + assert_eq!(e.pending[1].reasons_for(&b), ["current", "deleted"], "only the change it was given"); + assert!(!e.pending[0].is_for(&b)); } /// While a handler runs, a delivery returns at once; the change waits for the next one, which diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..2d15652731 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -642,6 +642,8 @@ pub(crate) struct Savepoint { pending_paint: Option, choices: Choices, journal: usize, + /// The plug-in events queued before the command ([`Session::plugin_events_mark`]). + plugin_events: u64, } impl Savepoint { @@ -676,6 +678,7 @@ impl Savepoint { pending_paint: s.pending_paint.clone(), choices: Choices::of(s), journal: s.journal.len(), + plugin_events: s.plugin_events_mark(), } } @@ -728,6 +731,8 @@ impl Savepoint { s.pending_paint = self.pending_paint; self.choices.put(s); s.journal.truncate(self.journal); + // The documents the command opened are closed again: plug-ins are not told of them. + s.forget_plugin_opens_since(self.plugin_events); s.sync_front_profiles(); exact } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 19cd41fdb0..9f4591423f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -206,6 +206,9 @@ impl Session { // A failed or panicked command's documents are put back: type is drawn in their // composite fonts again, not in those the command set. cmd::compositefonts::sync(self); + // Plug-ins still hear of what finished before the failure, such as a save in a batch + // whose later step failed. + self.plugin_events_after_command(); } let r = r?; if self.depth == 0 { diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index df8dd04cb4..6ee0e8342b 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -238,6 +238,96 @@ fn a_module_installed_again_gets_no_event_from_before_its_removal() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A save waiting in one session is not given to the same module that another session removed and +/// installed again before this session's delivery. +#[test] +fn a_module_installed_again_by_another_session_gets_no_earlier_event() { + let id = "test.events.again_elsewhere"; + let mut s = session(); + s.plugin_event_frames = true; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-elsewhere-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("elsewhere.vectorcraft").to_string_lossy()})); + let mut other = session(); + run(&mut other, "plugin.remove", json!({"id": id})); + install(&mut other, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "the save came before this install"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A plug-in installed between two layer changes waiting for the same delivery is given only the +/// reason of the change after its install; the plug-in installed before is given both. +#[test] +fn a_plugin_installed_between_layer_changes_gets_only_the_later_reason() { + let (early, late) = ("test.events.reasons_early", "test.events.reasons_late"); + let mut s = session(); + let first = s.doc().unwrap().active_layer.unwrap(); + let second = NodeId(run(&mut s, "layer.new", json!({"name": "Two"}))["id"].as_u64().unwrap()); + install(&mut s, early, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + run(&mut s, "layer.setProps", json!({"id": second.0, "name": "Notes"})); + install(&mut s, late, r#"["layer.changed"]"#, &[], "", tpl::LOG_EVENT, &[]); + run(&mut s, "layer.setCurrent", json!({"id": first.0})); + s.deliver_plugin_events(); + let notices = s.take_plugin_event_notices(); + let reasons = |id: &str| -> Vec { + notices.iter().filter(|n| n.plugin == id).map(|n| serde_json::from_str::(&n.text).unwrap()["reasons"].clone()).collect() + }; + assert_eq!(reasons(early), [json!(["current", "options"])]); + assert_eq!(reasons(late), [json!(["current"])], "the rename came before this install"); + run(&mut s, "plugin.remove", json!({"id": early})); + run(&mut s, "plugin.remove", json!({"id": late})); +} + +/// A save waiting for delivery is held while an interaction is open, and given at the first +/// delivery after it ends. +#[test] +fn waiting_events_are_held_while_an_interaction_is_open() { + let id = "test.events.interaction"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-interaction-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("interaction.vectorcraft").to_string_lossy()})); + s.begin_interaction("Move").unwrap(); + s.deliver_plugin_events(); + assert!(given(&mut s, id).is_empty(), "not while the interaction is open"); + s.cancel_interaction().unwrap(); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A save in a batch whose later step fails is still given to the plug-in when the request ends; +/// an open in that batch, which the rollback closes again, is not. +#[test] +fn a_save_before_a_failed_batch_step_is_delivered() { + let id = "test.events.failed_batch"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-batch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("failed-batch.vectorcraft").to_string_lossy().into_owned(); + let steps = json!([ + {"command": "document.save", "params": {"path": path}}, + {"command": "document.open", "params": {"path": path}}, + {"command": "no.such.command", "params": {}} + ]); + assert!(s.execute("command.batch", &json!({"commands": steps})).is_err()); + assert!(std::path::Path::new(&path).exists(), "the save was written"); + assert_eq!(s.documents().len(), 1, "the opened document was closed again"); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 699fe15161..54e315b2cf 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -582,6 +582,8 @@ impl Plugin { let out = (|| { let alloc: TypedFunc = live.func("vc_alloc")?; let handler: TypedFunc = live.func("vc_event")?; + // The start function may have used the time: neither call runs past it. + deadline.check()?; let ptr = self.call_budget(&mut live, &alloc, event.len().max(1) as i32, &mut budget, &deadline, None)? as u32 as usize; if ptr == 0 { return Err(Error::Failed("vc_alloc returned 0 (out of memory)".into())); @@ -589,6 +591,7 @@ impl Plugin { let outside = || Error::Abi("vc_alloc returned a block outside memory".into()); let end = ptr.checked_add(event.len()).ok_or_else(outside)?; live.memory.data_mut(&mut live.store).get_mut(ptr..end).ok_or_else(outside)?.copy_from_slice(event); + deadline.check()?; let code = self.call_budget(&mut live, &handler, (ptr as i32, event.len() as i32), &mut budget, &deadline, bridge)?; deadline.check()?; if code != 0 { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index bb28afd450..146118162e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1073,7 +1073,9 @@ fn vc_event_is_given_the_event_and_its_code_is_checked() { } /// The start function, `vc_alloc` and `vc_event` share one event budget: work that fits it in the -/// handler alone fits it no longer when the start function has done as much first. +/// handler alone fits it no longer when the start function has done as much first. The budget is +/// 200,000 instructions, which run in far less than the 200 ms an event is given, so the run that +/// fails is stopped by its instruction budget. #[test] fn a_handler_and_its_start_function_share_the_event_budget() { let manifest = reacting_manifest("test.events.shared", r#"["layer.changed"]"#); @@ -1084,18 +1086,23 @@ fn a_handler_and_its_start_function_share_the_event_budget() { let plugin = |start: u32, handler: u32| { let imports = format!("{} {burn} (func $s (call $burn (i32.const {start}))) (start $s)", tpl::HOST_IMPORTS); let body = format!("(call $burn (i32.const {handler})) (i32.const 0)"); - Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits::default()).unwrap() + Plugin::load(&build(&tpl::reacting(&manifest, &imports, &body)), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap() }; let event = br#"{"type":"layer.changed","document":1}"#; - // The most loop turns, doubling, that fit the budget in the handler alone: twice as many don't. - let mut k = 1u32 << 16; - while plugin(0, k * 2).run_event(event, None).0.is_ok() { - k *= 2; + // The most loop turns, doubling, that fit the budget in the handler alone: twice as many run out + // of instructions. + let mut k = 1u32 << 8; + let e = loop { + match plugin(0, k * 2).run_event(event, None).0 { + Ok(()) => k *= 2, + Err(e) => break e.to_string(), + } assert!(k < 1 << 30, "a handler that never runs out of its budget"); - } + }; + assert!(e.contains("instruction budget"), "{e}"); assert!(plugin(0, k).run_event(event, None).0.is_ok()); let e = plugin(k, k).run_event(event, None).0.unwrap_err().to_string(); - assert!(e.contains("budget"), "{e}"); + assert!(e.contains("instruction budget"), "{e}"); } /// A heavy filter installs once the user agrees, which loading a folder doesn't ask: it is skipped diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index addee8c79a..03917c635f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -249,10 +249,21 @@ fn finished_background_work_waits_for_the_run_to_end() { #[test] fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { use vectorcraft_plugins::wat as tpl; + + /// Removes the plug-in when the test ends, failed or not: the registry serves every session in + /// the process. + struct Remove(&'static str); + impl Drop for Remove { + fn drop(&mut self) { + vectorcraft_plugins::registry::remove(self.0); + } + } + let mut app = app(); app.session.prefs.show_external_script_warning = false; app.session.allow_plugin_grants_from_requests(); let id = "test.UI.script_run_events"; + let _remove = Remove(id); let grant = json!(["progress", "events"]); let manifest = format!(r#"{{"id":"{id}","name":"Run Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); // The handler writes the event it is given as a warning, which the status bar shows. diff --git a/docs/plugins.md b/docs/plugins.md index 8aba315c74..e50e2455e1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -556,7 +556,8 @@ or the document's contents. and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP - deliver after each request. Opens and saves are each their own event, in order, and are delivered even when the + deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its + `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the document closed before the delivery. At most 32 events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active From ab15fbb0d1bd1df64e3b819f4025e711f4b52983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:32:54 -0800 Subject: [PATCH 045/533] Scripts: palette events keep their errors, and palettes keep visible in step - script.palette.event takes a whole float such as 1.0 as a list's item index, as a window answer does. - With nobody to ask, an event given while an undo group is open is refused with the undo-group error and is not kept. An event whose run cannot begin, for example because a recovery copy cannot be saved, ends the call with its error, and the events after it keep waiting. - A handler's error keeps its file, line and column when a palette getter also throws in the refresh after the run. - A palette's controls reach the host once, after the handler's run ends, so a getter is read once for a run that completes. - The refresh roots its copy of the palette list while getters run. - hide() sets a palette's visible to false, and show() sets it to true once the host shows it. - A close() inside a modal dialog's onClose does nothing, as for a palette; a later close runs onClose again. - A palette list change reads the list's revision after its item texts, whose getters may replace the items. - Bounds given as x, y, width and height keep their right and bottom edges finite. - A palette event that waits for an open undo group asks for no frames; the frame that ends the group asks for the next one. - A list choice queued in a ScriptUI dialog carries the list's items and revision, and is not given when a handler changed the list since. The status message has a row in every complete catalog. - docs/mcp.md: with nobody to ask, the undo-group refusal and the event whose run cannot begin; a handler reads the files allowed with Always. --- crates/engine/src/cmd/scripts.rs | 7 +- crates/engine/src/script/mod.rs | 7 +- crates/engine/src/script/palettes.rs | 24 ++++--- crates/engine/src/tests/script_palettes.rs | 75 +++++++++++++++++++++ crates/js/src/realm.rs | 12 ++++ crates/js/src/scriptui.rs | 49 +++++++++----- crates/js/src/scriptui_tests.rs | 72 +++++++++++++++++++- crates/ui-egui/src/app.rs | 9 ++- crates/ui-egui/src/dialogs/script_window.rs | 29 ++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/tests/script_palettes.rs | 16 +++-- crates/ui-egui/src/tests/script_window.rs | 26 +++++++ docs/mcp.md | 7 +- 37 files changed, 316 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 831b56c586..349b46b28f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), @@ -281,6 +281,11 @@ fn palette_event(s: &mut Session, p: &Value) -> Result { let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo + // group, which a run cannot start in. + if !s.script_frames && s.undo_group_open() { + return Err(EngineError::Other(script::OPEN_EDIT.to_string())); + } let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; if s.script_frames { return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index de8f299cec..ef204e4582 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2345,7 +2345,7 @@ impl Session { } } -const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; +pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; @@ -2515,9 +2515,10 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result realm.refresh_script_ui().map(|()| Progress::Done(v)), // A failed run keeps its globals, so its palettes show what it left too; a refresh - // that fails as well (the fuel is spent, a stop) leaves them as they were. + // that fails as well (the fuel is spent, a stop) leaves them as they were, and the + // run's error keeps its place. Err(e) if named && e.kind != RunErrorKind::Internal => { - let _ = realm.refresh_script_ui(); + realm.refresh_script_ui_after_error(); Err(e) } r => r, diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 1336a6a7f3..e7de94a1bf 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -43,7 +43,8 @@ pub struct ScriptPalette { pub dialog: ScriptUiDialog, pub visible: bool, /// The SHA-256 the file grants of the script that first showed it are kept for, which its - /// handlers' runs keep using. + /// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the + /// showing run's alone, as for any later run of the script. pub(crate) grants: String, } @@ -253,8 +254,8 @@ pub(crate) fn parse_event( ("click", None) => UiEvent::Click(id), ("click", Some(_)) => return Err("a click takes no `value`".into()), ("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), - ("change", Some(Value::Number(v))) if list => match v.as_u64() { - Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + ("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), None => return Err("a list's `value` must be an item index or null".into()), }, ("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))), @@ -333,10 +334,12 @@ impl Session { /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in /// progress is not counted, since starting the run settles it. pub fn script_palette_can_start(&self) -> bool { - !self.script_palettes.waiting.is_empty() - && !self.script_running() - && self.explicit_undo_group.is_none() - && self.docs.iter().all(|d| d.undo_group.is_none()) + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.undo_group_open() + } + + /// Whether an undo group is open, the session's or a document's, which a run cannot start in. + pub(crate) fn undo_group_open(&self) -> bool { + self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some()) } /// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going @@ -383,11 +386,14 @@ impl Session { } /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, - /// the one just given last. → that one's report. + /// the one just given last. → that one's report. An event whose run could not begin, for + /// example because the recovery copies could not be saved, ends this with its error, and the + /// events after it keep waiting. pub(crate) fn script_palette_run_waiting(&mut self) -> Result { let mut last = Err(EngineError::Other("no script palette event waits".into())); while let Some(started) = self.script_palette_start() { - last = started.and_then(|_| self.script_run_to_end()); + started?; + last = self.script_run_to_end(); } last } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 7078442ac2..c432700fe6 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -262,6 +262,81 @@ fn double_clicks_while_queued_run_once() { assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); } +#[test] +fn a_list_change_takes_a_whole_float_as_its_item_index() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); + assert_eq!(picked["log"], json!(["b"])); + for value in [json!(0.5), json!(-1)] { + let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); + assert!(given.is_err(), "{value}"); + } +} + +#[test] +fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("undo group is open"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + s.script_copy_first = true; + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("recovery copy"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); + s.script_copy_first = false; + assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { + let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let first = base.join("first.jsx"); + std::fs::write( + &first, + "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", + ) + .unwrap(); + let second = base.join("second.jsx"); + std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); + let mut s = one_doc(); + for file in [&first, &second] { + s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); + } + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("handler"), "{e}"); + let report = s.script_report().unwrap(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn a_palette_from_a_script_without_a_named_engine_is_refused() { let mut s = one_doc(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 117ae759b6..3a65a60f0b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -512,6 +512,18 @@ impl Realm { } } + /// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped, + /// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and + /// its thrown value. + pub fn refresh_script_ui_after_error(&mut self) { + let (tag, mark) = (self.interp.error_tag, self.interp.error_mark); + let thrown = self.interp.last_thrown.clone(); + let _ = self.refresh_script_ui(); + self.interp.error_tag = tag; + self.interp.error_mark = mark; + self.interp.last_thrown = thrown; + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 52f42ee49c..dac3e9d590 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -666,14 +666,15 @@ fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { let (o, palette) = window_of(i, &this, "hide")?; if !palette { @@ -682,6 +683,7 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } @@ -698,10 +700,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); } - set_slot(i, win, IN_CLOSE, Value::Bool(true))?; - let allowed = may_close(i, win); - set_slot(i, win, IN_CLOSE, Value::Undefined)?; - if !allowed? { + if !may_close(i, win)? { return Ok(()); } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { @@ -724,10 +723,16 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { /// Gives the host the controls of every palette it shows, after a handler may have changed them. fn update_palettes(i: &mut Interp) -> JsResult<()> { - for win in classes(i)?.palettes { - update_palette(i, win)?; - } - Ok(()) + // A getter may close a later palette, which removes it from the rooted list, so the copy is + // rooted until the loop ends. + let palettes = classes(i)?.palettes; + let roots: Vec = palettes.iter().map(|&win| Value::Object(win)).collect(); + i.rooted(&roots, |i| { + for win in palettes { + update_palette(i, win)?; + } + Ok(()) + }) } /// Gives the host the controls of every palette the realm keeps, as a run left them @@ -755,15 +760,16 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; Ok(Value::Undefined) } /// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the -/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and -/// gives the host every palette's controls afterward. An event for a palette that has closed does -/// nothing. +/// host's `paletteEvent` and gives it to the palette the way a dialog takes the person's event. The +/// host gets every palette's controls once the run ends ([`crate::Realm::refresh_script_ui`]). An +/// event for a palette that has closed does nothing. fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; @@ -795,7 +801,6 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. +/// Runs `onClose`, during which a `close()` of the same window does nothing. → false when it +/// returned `false`. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let ran = handler(i, win, "onClose"); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + Ok(!matches!(ran?, Some(Value::Bool(false)))) } /// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. @@ -1005,12 +1014,14 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } // A palette's list may have changed while the event waited: the host gives // the items the person saw and the list's revision then. + // The revision is read after the texts, whose getters may change the list. None => { + let same = same_items(i, c, &slot(i, ev, "items")?)?; let revised = match slot(i, ev, "revision")? { Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; - if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } } @@ -1116,7 +1127,9 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { Some(Data::Number(n)) => *n, _ => 0.0, }; - return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + // Two finite numbers can add up to infinity; the sum is kept finite. + let end = |a: f64, b: f64| (a + b).clamp(-f64::MAX, f64::MAX); + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(end(n(0), n(2))), Data::Number(end(n(1), n(3)))])); } numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 76a70d331d..f9be03af3b 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -444,7 +444,10 @@ fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]); r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into())); - assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event gives the host the new controls"); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(); + assert_eq!(updates(&calls), 1, "the handlers give the host nothing"); + r.refresh_script_ui().unwrap(); + assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls"); assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs"); } @@ -489,6 +492,73 @@ fn a_palette_list_change_after_its_items_changed_throws() { assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into())); } +/// A palette list change as the host gives it: the item index, the items the person saw (`a` and +/// `b`) and the revision of a list made with those two items. +fn seen_list_change(index: f64) -> Data { + let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null }; + fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())]))); + fields.push(("revision".into(), Data::Number(2.0))); + Data::Object(fields) +} + +#[test] +fn a_palette_list_change_after_an_item_s_text_changed_throws() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + r.run("var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; l.onChange = function () { got.push(String(l.selection)); }; p.show();") + .unwrap(); + r.run("l.items[1].text = 'z';").unwrap(); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()), "the same items, one with another text"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); +} + +#[test] +fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read replaces the items with ones of the same + // texts. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); + assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); +} + +#[test] +fn a_palette_s_visible_follows_hide_and_show() { + let (mut r, _) = palette_realm(Vec::new()); + let v = r + .run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()") + .unwrap(); + assert_eq!(v, JsValue::String("true,false,true".into())); +} + +#[test] +fn a_close_inside_a_dialog_s_on_close_does_nothing() { + let (mut r, seen, _) = realm(vec![close(), click(13)]); + let source = format!( + "{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel"); + assert_eq!(seen.borrow().ends, vec![(2.0, true)]); +} + +#[test] +fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()") + .unwrap(); + let described = nodes(&seen.borrow().descriptions[0]); + let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]); + assert_eq!(field(&described[1], "bounds"), &want); +} + #[test] fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() { let (mut r, calls) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b52abc1a7a..7cc5524c25 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -370,11 +370,10 @@ impl VectorcraftApp { crate::dialogs::proof_setup::poll(self, ctx); // A palette event whose run starts on the next frame. While a run goes on, the block below // asks for its frames, and a run that waits for the person goes on at their next input. An - // event that waits for an open undo group to end looks again four times a second. + // event that waits for an open undo group asks for no frame; the pass that ends the group + // asks for the next one (`ui_frame`). if self.session.script_palette_can_start() { ctx.request_repaint(); - } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() @@ -672,6 +671,10 @@ impl VectorcraftApp { } scrub::end_frame(self, &ctx); native_menu::sync(self, &ctx); + // A palette event that waited for an undo group this pass ended starts its run next frame. + if self.session.script_palette_can_start() { + ctx.request_repaint(); + } // Observe once, after all of this pass's input, dialogs, floating panels, palette and // commands: the latest completed pass is authoritative for owner, text and cause. crate::ime::end_of_pass(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2c8f35365e..343f6c27d3 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -144,6 +144,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc // The control the event was given to, found again in the dialog as the handlers that ran // since left it. let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); + // A list's choice whose list a handler changed since it was made is not given. + if !same_list(&w, at, fields.remove(LIST_KEY).as_ref()) { + app.status(LIST_CHANGED); + // The events after it are given from the next frame on. + if d.fields.contains_key(QUEUE_KEY) { + ui.ctx().request_repaint(); + } + return DialogAction::None; + } if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,6 +161,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } +/// The field of a queued list change that holds the list's items and revision as the person saw +/// them ([`UiNode::revision`]). +const LIST_KEY: &str = "list"; + +/// The status when a queued list choice is not given because its list changed. +const LIST_CHANGED: &str = "The list's items changed before the choice was taken"; + /// The field of a queued event that holds where its control sits in the dialog /// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; @@ -442,9 +458,22 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { if let Some(i) = control { fields[PLACE_KEY] = json!(w.place_of(i)); } + if let UiEvent::Change(i, UiValue::Index(_)) = event + && let Some(n) = w.nodes.get(*i) + { + fields[LIST_KEY] = json!({"items": n.items, "revision": n.revision}); + } fields } +/// Whether the list control `at` of `w` still holds the items a queued list change was given for +/// (its [`LIST_KEY`] field): the same texts and the same revision. True for any other event. +fn same_list(w: &ScriptUiDialog, at: Option, seen: Option<&Value>) -> bool { + let Some(seen) = seen else { return true }; + let n = at.and_then(|i| w.nodes.get(i)); + n.is_some_and(|n| seen["revision"].as_f64() == Some(n.revision) && seen["items"] == json!(n.items)) +} + /// The event in the dialog's fields, for the dialog `w`. fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { let control = match d.fields.get("control") { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 51a518f798..055cc437f6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6583,6 +6583,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `answers` must be a list of answers `answers` ha de ser una llista de respostes @msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes @msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat +@msg The list's items changed before the choice was taken Els elements de la llista han canviat abans que es prengués l'elecció @msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB @msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value` @msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9457178baf..17f9bd3929 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8987,6 +8987,7 @@ breakText Glyphs Glyfy @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí @msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována +@msg The list's items changed before the choice was taken Položky seznamu se změnily dříve, než byla volba převzata @msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB @msg `answers` must be a list of answers `answers` musí být seznam odpovědí @msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1ef0d2169d..4f64a31c76 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -226,6 +226,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `answers` must be a list of answers `answers` skal være en liste med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt +@msg The list's items changed before the choice was taken Listens elementer blev ændret, før valget blev modtaget @msg `answers` is larger than 1 MiB `answers` er større end 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 935a135c4b..d606cb3196 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8427,6 +8427,7 @@ breakText Glyphs Glyphen @msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten +@msg The list's items changed before the choice was taken Die Einträge der Liste haben sich geändert, bevor die Auswahl übernommen wurde @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index aa30a34709..4ae2b19c0a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2780,6 +2780,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων @msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις @msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε +@msg The list's items changed before the choice was taken Τα στοιχεία της λίστας άλλαξαν πριν ληφθεί η επιλογή @msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB @msg `answers[{i}]` {e} το `answers[{i}]` {e} @msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5cc8d86fdf..6c79382ae8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5055,6 +5055,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `answers` must be a list of answers `answers` debe ser una lista de respuestas @msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas @msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado +@msg The list's items changed before the choice was taken Los elementos de la lista cambiaron antes de que se tomara la elección @msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB @msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value` @msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1205c1dc9d..3a223923e4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5296,6 +5296,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `answers` must be a list of answers `answers` on oltava vastausten luettelo @msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty +@msg The list's items changed before the choice was taken Luettelon kohteet muuttuivat ennen kuin valinta otettiin vastaan @msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB @msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value` @msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dbdca9ca76..0560264b7c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8854,6 +8854,7 @@ breakText Glyphs Glyphes @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé +@msg The list's items changed before the choice was taken Les éléments de la liste ont changé avant que le choix soit pris en compte @msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio @msg `answers` must be a list of answers `answers` doit être une liste de réponses @msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8c5e1f5602..d600eda164 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7729,6 +7729,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए @msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं @msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई +@msg The list's items changed before the choice was taken चुनाव लिए जाने से पहले सूची के आइटम बदल गए @msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 6f7ce5a4ca..10ec8d74fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8858,6 +8858,7 @@ breakText Glyphs Glifák @msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz @msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva +@msg The list's items changed before the choice was taken A lista elemei megváltoztak, mielőtt a választás érvénybe lépett @msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál @msg `answers` must be a list of answers `answers`: válaszok listája kell @msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25e340bec0..50c3eeec25 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -134,6 +134,7 @@ @msg `answers` must be a list of answers `answers` harus berupa daftar jawaban @msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan +@msg The list's items changed before the choice was taken Item daftar berubah sebelum pilihan diterima @msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB @msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value` @msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ea73cf2b91..788dad1c7a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifi @msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato +@msg The list's items changed before the choice was taken Le voci dell'elenco sono cambiate prima che la scelta fosse acquisita @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0b73565e9a..1ef4e34f52 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7294,6 +7294,7 @@ axis Y Axis Y 軸 @msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています @msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした +@msg The list's items changed before the choice was taken 選択が受け付けられる前にリストの項目が変更されました @msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています @msg `answers` must be a list of answers `answers` には回答のリストを指定してください @msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 541d871302..709bb0deea 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -177,6 +177,7 @@ @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს @msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა +@msg The list's items changed before the choice was taken სიის ელემენტები შეიცვალა არჩევანის მიღებამდე @msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია @msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია @msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 07bde95166..e306c15d66 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8626,6 +8626,7 @@ breakText Glyphs 글리프 @msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다 @msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다 +@msg The list's items changed before the choice was taken 선택이 적용되기 전에 목록의 항목이 변경되었습니다 @msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다 @msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다 @msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9287dd44e3..93a35a622b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6494,6 +6494,7 @@ imageTrace Outline Contour @msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden @msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard +@msg The list's items changed before the choice was taken De items van de lijst zijn gewijzigd voordat de keuze werd overgenomen @msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB @msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn @msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fd7342da72..a89b52d6cd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8671,6 +8671,7 @@ breakText Glyphs Glify @msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi @msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane +@msg The list's items changed before the choice was taken Elementy listy zmieniły się, zanim wybór został przyjęty @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4aa2697468..24838d4c6b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9040,6 +9040,7 @@ swatch Yellow Green Verde-amarelado @msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas @msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido +@msg The list's items changed before the choice was taken Os itens da lista mudaram antes de a escolha ser aplicada @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ac74d5747a..8bdecf2658 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5077,6 +5077,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `answers` must be a list of answers `answers` должен быть списком ответов @msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов @msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено +@msg The list's items changed before the choice was taken Элементы списка изменились до того, как выбор был принят @msg `answers` is larger than 1 MiB `answers` больше 1 МиБ @msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value` @msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index dc74ea16ce..ea059da395 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4952,6 +4952,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `answers` must be a list of answers `answers` måste vara en lista med svar @msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte +@msg The list's items changed before the choice was taken Listans objekt ändrades innan valet togs emot @msg `answers` is larger than 1 MiB `answers` är större än 1 MiB @msg `answers[{i}]` {e} `answers[{i}]` {e} @msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 109ef0345a..07a1987942 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7670,6 +7670,7 @@ axis Y Axis Y ekseni @msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var @msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı +@msg The list's items changed before the choice was taken Seçim alınmadan önce listenin öğeleri değişti @msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük @msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır @msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 20e6a222ab..f7b1ffc2a2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8627,6 +8627,7 @@ breakText Glyphs Гліфи @msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей @msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено +@msg The list's items changed before the choice was taken Елементи списку змінилися до того, як вибір було прийнято @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 173c74895c..4fa7e8ace1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5576,6 +5576,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời @msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời @msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại +@msg The list's items changed before the choice was taken Các mục của danh sách đã thay đổi trước khi lựa chọn được nhận @msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB @msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value` @msg must have exactly `kind` and `value` phải có đúng `kind` và `value` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 129b2fff68..863ae243df 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8677,6 +8677,7 @@ breakText Glyphs 字形 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 @msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在采用选择之前,列表的项目已更改 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b11084d879..2d69c7b869 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8622,6 +8622,7 @@ breakText Glyphs 字符 @msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1} @msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個 @msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留 +@msg The list's items changed before the choice was taken 在採用選擇之前,清單的項目已變更 @msg `answers` is larger than 1 MiB `answers` 大於 1 MiB @msg `answers` must be a list of answers `answers` 必須是答案清單 @msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 877548d602..b02fc382b2 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -28,10 +28,16 @@ fn run_to_end(app: &mut VectorcraftApp) { /// One headless frame in which `f` runs. → whether the frame asked for the next one at once. fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + frame_delay(ctx, f).is_zero() +} + +/// One headless frame in which `f` runs. → how long until the frame asked for the next one; +/// `Duration::MAX` when it asked for none. +fn frame_delay(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> std::time::Duration { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); out.textures_delta.clear(); - out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) } #[test] @@ -98,15 +104,15 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let ctx = egui::Context::default(); frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); - let mut asks = true; + let mut delay = std::time::Duration::ZERO; for _ in 0..5 { app.begin_host_iteration(); - asks = frame(&ctx, |ui| app.tick(ui.ctx())); - if !asks { + delay = frame_delay(&ctx, |ui| app.tick(ui.ctx())); + if delay == std::time::Duration::MAX { break; } } - assert!(!asks, "the waiting click asks for no frames while the undo group is open"); + assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the undo group is open"); assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); app.run("edit.undoGroup.end", json!({})).unwrap(); app.begin_host_iteration(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 21fbd0c785..d3e6069f16 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,32 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); var swap = w.add('button', undefined, 'Swap'); \ + w.add('button', undefined, 'OK'); swap.onClick = function () { l.removeAll(); l.add('item', 'x'); l.add('item', 'y'); }; \ + vc.log([w.show(), String(l.selection)]);", + ); + assert!(until_window(&mut app)); + // A click on Swap, then a choice in the list as it was before Swap's handler ran, both given + // in one frame. + let swap = json!({"event": "click", "control": 2, "value": null}); + let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the click and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].items, ["x", "y"]); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "the choice left the line"); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "null"]]), "the choice for the old items was not given"); +} + #[test] fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 2bc012fe73..fef4f78655 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2983,7 +2983,8 @@ the same controls, handlers and limits: A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. - A handler's run reads and writes the files the person allowed the script that first showed the palette. + A handler's run reads and writes the files the person allowed the script that first showed the palette with + Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's engine, with its own report and, when it changes a document, its own Run Script undo step. While another run goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a @@ -3006,7 +3007,9 @@ waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gi `change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in `ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one, -or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. +or its error; an event whose run cannot begin ends it with that error, and the events after it keep waiting. A +hidden palette, a disabled or hidden control, and a control that cannot take the event are errors, and with nobody +to ask so is an event while an undo group is open. ```sh vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}' From 90400601189f9c204d0c1c2150f1b84f211d2e56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:38:52 -0800 Subject: [PATCH 046/533] Links: a group checks its other relative paths in a set Grouping linked objects compared each object's relative path with every other relative path already in its group, so many objects of one file with paths of their own took quadratic time. The group keeps a set beside the list, which keeps the stored order. --- crates/engine/src/cmd/links.rs | 52 ++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index ff420c436e..fad22b6367 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -168,6 +168,8 @@ struct Group { /// The stored relative paths of the group's objects other than `link`'s, each once: objects /// with the same path and content can each keep a relative path of its own. other_relatives: Vec, + /// `other_relatives` as a set, looked up for every object added to the group. + relatives_seen: std::collections::HashSet, } /// What a placed document shows: whether the art's bounds (not the artboard or page) are shown, @@ -239,14 +241,23 @@ fn groups(d: &Document, ids: Option<&[NodeId]>) -> Vec { None => d.images.get(key).map(ImageBlob::plate_files).unwrap_or_default(), Some(_) => vec![], }; - out.push(Group { link: link.clone(), key: key.to_string(), ids: vec![], document, plate_files, other_relatives: vec![] }); + out.push(Group { + link: link.clone(), + key: key.to_string(), + ids: vec![], + document, + plate_files, + other_relatives: vec![], + relatives_seen: Default::default(), + }); out.len() - 1 }); let Some(g) = out.get_mut(i) else { return }; if let Some(r) = &link.relative && g.link.relative.as_ref() != Some(r) - && !g.other_relatives.contains(r) + && !g.relatives_seen.contains(r) { + g.relatives_seen.insert(r.clone()); g.other_relatives.push(r.clone()); } if let Some(id) = id { @@ -3222,6 +3233,43 @@ mod tests { assert!(!Arc::ptr_eq(&a.blob.bytes, &c.blob.bytes)); } + /// Many objects of one file and content that each keep a relative path of their own make one + /// group, which lists every other relative path once, in the order the objects are stored. + #[test] + fn a_group_lists_each_other_relative_path_once_in_stored_order() { + let mut d = Document::new(612.0, 792.0); + let layer = d.default_layer(); + let relatives: Vec = (0..2_000).map(|i| format!("art/{}/pic.png", i % 1_000)).collect(); + for r in &relatives { + let link = LinkInfo { relative: Some(r.clone()), ..LinkInfo::new("/art/pic.png") }; + let im = ImageObject { + key: "pic".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(link), + placement: Default::default(), + pixels: None, + }; + let id = d.alloc_id(); + d.insert(layer, 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + } + let groups = groups(&d, None); + assert_eq!(groups.len(), 1); + let g = &groups[0]; + assert_eq!(g.ids.len(), 2_000); + // Objects inserted at index 0 are stored last to first. + let first = g.link.relative.clone().unwrap(); + let mut expected: Vec = vec![]; + for r in relatives.iter().rev() { + if *r != first && !expected.contains(r) { + expected.push(r.clone()); + } + } + assert_eq!(expected.len(), 999); + assert_eq!(g.other_relatives, expected); + } + #[test] fn unembed_names_a_file_after_the_image_with_only_characters_a_file_name_holds() { for (name, stem) in [ From 8f9e3007106e71998fa19352f22e14c8a809fb8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 18:07:01 -0800 Subject: [PATCH 047/533] Tests: the host name table lists the PageItem.controlBounds setter PageItem.controlBounds now throws that it is not available yet, through the same getter and setter as the other members that are not available, so the table of names the host adds lists controlBounds= as well. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 52721f7c33..d56fd43e02 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -112,7 +112,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds controlBounds= duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ From f05ec9a0906db1895c6f54609a251c8150bb9b23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:36:00 -0800 Subject: [PATCH 048/533] Scripts: a palette event finds its control by its place, and a run at its dialog idles - script.palette.event's params text lists `control` and `value` with their notes in parentheses, so the description reads as a params object again. - A palette handler's run gets the place of the clicked or changed control from the host and gives the event to the control at that place in the palette as it is then. A getter read while the palette is described can add a control before it; the event no longer goes to the control that took its index. An event whose place holds no control is an error. - While a run waits at its ScriptUI dialog, the app asks for no frames; the pass that gives the dialog's event asks for the next one, and so does a frame that handles a control request while a run goes on, such as `ui.dialog.confirm` answering the dialog. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/palettes.rs | 2 +- crates/engine/src/script/scriptui.rs | 10 ++- crates/js/src/scriptui.rs | 35 +++++++++- crates/js/src/scriptui_tests.rs | 19 +++++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/control.rs | 4 ++ crates/ui-egui/src/dialogs/script_window.rs | 3 + crates/ui-egui/src/tests/script_window.rs | 77 +++++++++++++++++++++ 9 files changed, 146 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 349b46b28f..28a05598ea 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e7de94a1bf..673fcf5714 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -65,7 +65,7 @@ pub(crate) struct Queued { /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), /// by which the event finds its control again when a run adds controls before it; empty for a /// close. - place: Vec, + pub(crate) place: Vec, /// For a list's change, the list's items as the palette showed them when the event was given and /// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list /// still has. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index fd3bda32a4..bb96c2771d 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -773,13 +773,17 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { Ok(Data::Undefined) } -/// The event a palette handler's run is for, once: `{palette, event, id, value, items}`, as `show()` -/// takes a dialog's event with the palette's id added, and for a list's change the items the -/// palette showed; `null` for any other run, and after the first call. +/// The event a palette handler's run is for, once: `{palette, event, id, value, place, items}`, as +/// `show()` takes a dialog's event with the palette's id added, the place of a click's or a +/// change's control ([`ScriptUiDialog::place_of`]), which the run finds the control by, and for a +/// list's change the items the palette showed; `null` for any other run, and after the first call. fn palette_event(host: &Host, _: &[Data]) -> Result { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if !queued.place.is_empty() { + fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); + } if let Some((items, revision)) = queued.list { fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); fields.push(("revision".into(), Data::Number(revision))); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index dac3e9d590..6e997aa2af 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -795,10 +795,23 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + let held = list_values(i, nodes)?; + // The host gives the control's place, which is found again in the palette as it is now: + // a getter read in the description may have added a control before it. + let at = match slot(i, ev, "place")? { + Value::Object(place) => { + let control = control_at_place(i, win, place)?; + control.and_then(|c| held.iter().position(|v| v.as_object() == Some(c))) + } + _ => match slot(i, ev, "id")? { + Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => Some(n as usize), + _ => None, + }, + }; + let Some(at) = at.filter(|&n| n >= 1 && n < held.len()) else { return Err(error(i, "a palette event names a control the palette no longer holds")); - } + }; + set_slot(i, ev, "id", Value::Number(at as f64))?; take_event(i, win, nodes, ev, &event, None)?; } Ok(Value::Undefined) @@ -807,6 +820,22 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult> { + let mut at = win; + for k in list_values(i, place)? { + let Value::Number(k) = k else { return Ok(None) }; + if k < 0.0 || k.fract() != 0.0 { + return Ok(None); + } + let Some(kid) = kids_of(i, at)?.get(k as usize).and_then(Value::as_object) else { return Ok(None) }; + at = kid; + } + Ok((at != win).then_some(at)) +} + fn host_fn(i: &mut Interp, name: &str) -> JsResult { let host = classes(i)?.host; i.get_value(&Value::Object(host), &key(name)) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index f9be03af3b..c6ed56abdb 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -530,6 +530,25 @@ fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); } +#[test] +fn a_palette_event_finds_its_control_by_its_place() { + let placed = |id: usize, place: &[f64]| { + let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null }; + fields.push(("place".into(), Data::Array(place.iter().map(|&k| Data::Number(k)).collect()))); + Data::Object(fields) + }; + // The host's index 1 is the group, where a control a getter added would have moved the button; + // the place is the button's, the second control of the palette. + let (mut r, _) = palette_realm(vec![placed(1, &[1.0]), placed(2, &[2.0])]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();") + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control at its place"); + let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control at the place"); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); +} + #[test] fn a_palette_s_visible_follows_hide_and_show() { let (mut r, _) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7cc5524c25..b24b69f419 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -378,10 +378,12 @@ impl VectorcraftApp { if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() + && self.session.script_window().is_none() && self.session.script_picker().is_none() { // A script in `$.sleep` goes on when its time is up; until then the app can idle. A // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. + // A script at its ScriptUI dialog goes on when the dialog gives it an event. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 5ef64dfa3f..43e1cff7ed 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -120,6 +120,10 @@ impl VectorcraftApp { if handled == control::MAX_CONTROL_REQUESTS_PER_FRAME { // Leave later requests on the channel and schedule another frame to serve them. ctx.request_repaint(); + } else if handled > 0 && self.session.script_running() { + // A request may have answered the dialog a run waits at, which the app idles for: the + // next frame takes the answer and the run's next slice. + ctx.request_repaint(); } self.control_rx = Some(rx); } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 343f6c27d3..78e130bab2 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -158,6 +158,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc } d.fields.extend(fields); } + // The event lets the run go on, which the app idles for while it waits: the next frame takes + // the run's next slice. + ui.ctx().request_repaint(); DialogAction::Confirm } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index d3e6069f16..45bb4db50e 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,83 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn a_run_waiting_at_its_dialog_asks_for_no_frames() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = egui::Context::default(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut delay = std::time::Duration::ZERO; + for _ in 0..5 { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + delay = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + if delay == std::time::Duration::MAX { + break; + } + } + assert_eq!(delay, std::time::Duration::MAX, "the app idles until the person answers"); + assert!(app.session.script_window().is_some(), "the run still waits at its dialog"); +} + +#[test] +fn a_control_request_while_a_run_waits_at_its_dialog_asks_for_the_next_frame() { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = app().with_control(rx); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = egui::Context::default(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let drain = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.drain_control(ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + }; + // A new context asks for a frame or two of its own first. + let mut settled = false; + for _ in 0..10 { + if !drain(&mut app).is_zero() { + settled = true; + break; + } + } + assert!(settled, "nothing asks for a frame while the run waits"); + // What MCP's `answer_dialog` sends, which a later pass gives the run. + let (req, _reply) = crate::control::ControlRequest::new("ui.dialog.confirm", json!({})); + tx.send(req).unwrap(); + let delay = drain(&mut app); + assert!(delay.is_zero(), "the answer is taken in the next frame: {delay:?}"); +} + +#[test] +fn a_pass_that_gives_the_dialog_s_queued_event_asks_for_the_next_frame() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + let ctx = CTX.with(Clone::clone); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pass = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + }; + // The focused field's cursor blink asks for a later frame once the dialog has settled. + let mut settled = false; + for _ in 0..40 { + if !pass(&mut app).is_zero() { + settled = true; + break; + } + } + assert!(settled, "the dialog stops asking for the very next frame while nothing happens in it"); + // A click on Bold that waited in line behind a typed text. + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([{"event": "click", "control": 2, "value": null}])); + assert!(pass(&mut app).is_zero(), "the run the click let go on asks for its next slice"); + assert!(app.session.script_window().is_none(), "the run took the click and has not waited again yet"); +} + #[test] fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { let mut app = app(); From de38412a63eec0312cf90c64a0b143de6485cb4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:19:59 -0800 Subject: [PATCH 049/533] Scripts: new layers stay current, lists start at the top, empty compound paths - layers.add() and activeLayer = layer keep the layer the script made current after the call, instead of putting the earlier current layer back with the selection. - A layer's or artboard's name takes a number or a boolean as String() writes it. Two artboards may now have the same name. - A layer's or group's pageItems, groupItems and compoundPathItems, and a compound path's pathItems, list the topmost object first. - compoundPathItems.add() makes an empty compound path (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). object.newGroup takes compound: true for it, and node.move and PageItem.move put paths into it; the first path gives an empty compound path its paint. Other objects are refused. --- crates/engine/src/cmd/layer.rs | 19 +++- crates/engine/src/cmd/object/arrange.rs | 19 +++- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/script/dom.rs | 24 ++++- crates/engine/src/script/dom/layers.rs | 87 +++++++++++------- crates/engine/src/tests/script_dom.rs | 108 ++++++++++++++++++++++- docs/mcp.md | 31 ++++--- docs/target-app-parity.md | 2 +- 8 files changed, 232 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d2258f4e4a..27d5d58336 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also in a shown, unlocked compound path, and an empty compound path takes the paint of the first path that goes in; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -919,9 +919,19 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if !accepts(d, parent, n) { + let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + if let Some(c) = compound { + if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { + return Err(bad(C, "a compound path holds only paths")); + } + if !d.is_editable(c.id) { + return Err(bad(C, "the compound path is hidden or locked")); + } + } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // An empty compound path takes the paint of the first path that goes into it. + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, n.appearance.clone())); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -931,6 +941,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; + if let Some((c, appearance)) = paint + && let Some(n) = d.node_mut(c) + { + n.appearance = appearance; + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index bd993ec1ec..bd770334e8 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,10 +105,15 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } -/// `object.newGroup`: an empty group in a layer or a group (default: the current layer), on top -/// of its contents or at `index` (0 = bottom). The selection stays as it is. +/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The +/// selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { const C: &str = "object.newGroup"; + let compound = match p.get("compound") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?, + }; let st = s.doc()?; let parent = match p.get("parent") { None | Some(Value::Null) => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?, @@ -126,11 +131,17 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } - let gid = s.edit("Group", |d, _| { + let name = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(name, |d, _| { let gid = d.alloc_id(); let clips = d.node(parent).is_some_and(Node::clips); let index = if clips { index.max(1) } else { index }; - d.insert(Some(parent), index, Node::group(gid, Vec::new()))?; + let node = if compound { + Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero }) + } else { + Node::group(gid, Vec::new()) + }; + d.insert(Some(parent), index, node)?; Ok(gid) })?; Ok(json!({ "id": gid.0 })) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 8d17cc0a72..d197d911f3 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "Group", [], None, - "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 3a3c625754..c8741952d4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -637,6 +637,18 @@ fn on_doc( uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + on_doc_layer(h, uid, keep_selection, true, f) +} + +/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`, +/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current. +fn on_doc_layer( + h: &Host, + uid: u64, + keep_selection: bool, + keep_layer: bool, + f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer) = { let s = h.session.borrow(); @@ -649,6 +661,12 @@ fn on_doc( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let layer = if keep_layer { + layer + } else { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows())) + }; let mut restored = Ok(()); if keep_selection { let doc = { @@ -1754,7 +1772,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } let (parent, beside) = match how { Placement::Top | Placement::Bottom => { - if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + if matches!(t.kind, NodeKind::Compound { .. }) { + if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); } (target, None) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 1251972f64..15171be00d 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -11,20 +11,21 @@ //! one after others are added, moved or removed, and throws once it is gone. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `layers` lists layers top first, as the Layers panel shows them; `groupItems`, -//! `compoundPathItems` and a layer's or group's `pageItems` list art in paint order, bottom first, -//! as `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or -//! compound path at any depth; a layer's or group's hold the ones directly in it. +//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's +//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the +//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at +//! any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. //! - `locked` true means the layer is locked. //! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or //! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it. //! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255. -//! - `CompoundPathItems.add()` throws: a compound path holds at least one path. +//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it +//! gives it its paint, as Make Compound Path takes the paint of a path it joins. //! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a -//! document, the limit `Documents.add` uses. Artboard names are unique: a name another artboard -//! has throws. +//! document, the limit `Documents.add` uses. Two artboards may have the same name. +//! - A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. //! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global //! rulers, setting it moves the document's zero point. //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report @@ -41,7 +42,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_ use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, - method, named, num, number, on_doc, page_items, placement_of, property, text, typename, whole, with_doc, + method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -153,15 +154,26 @@ fn layer_name(h: &Host, a: &[Data]) -> Answer { read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) } +/// A name a script assigns: a string, or a number or boolean as `String()` writes it. +fn name_text(d: &Data) -> Result { + match d { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type("name must be a string".into())), + } +} + fn layer_set_name(h: &Host, a: &[Data]) -> Answer { - let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + let name = name_text(arg(a, 1))?; if name.trim().is_empty() { return Err(HostError::Range("a layer's name cannot be empty".into())); } if name.chars().count() > MAX_LAYER_NAME { return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); } - set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), json!({"name": name})) + let params = json!({"name": &name}); + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), params) } fn layer_visible(h: &Host, a: &[Data]) -> Answer { @@ -522,7 +534,7 @@ fn layers_add(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the layer is hidden or locked".into())); } } - let (_, r) = on_doc(h, doc.uid, true, |h| match parent { + let (_, r) = on_doc_layer(h, doc.uid, true, false, |h| match parent { None => command_value(h, "layer.new", &json!({"top": true})), Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), })?; @@ -574,8 +586,8 @@ pub(super) type ArtList = (u64, Arc, u8, Option, Rc) -> Result>> { @@ -598,7 +610,7 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R Some(c) => { let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); h.charge_call(children.len() as u64)?; - children.iter().filter(|n| kind.holds(n)).map(|n| n.id).collect() + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() } }; let ids = Rc::new(ids); @@ -771,26 +783,36 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer { art_typename(h, a, Kind::Compound) } -/// `groupItems.add()`: an empty group on top of the layer's or group's contents (the document's: -/// the current layer's), with `object.newGroup`. → the group. -fn groups_add(h: &Host, a: &[Data]) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), "GroupItems")?; +/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. +/// → the new object. +fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; if let Some(c) = c { let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); if compound { return Err(HostError::Error("a compound path holds only paths".into())); } } - let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + if kind == Kind::Compound + && let Some(o) = params.as_object_mut() + { + o.insert("compound".into(), json!(true)); + } let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; - let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the object was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; Ok(item_ref(h, st, NodeId(id))) } -fn compounds_add(_: &Host, _: &[Data]) -> Answer { - Err(HostError::Error("CompoundPathItems.add cannot make an empty compound path: a compound path holds at least one path".into())) +fn groups_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Group) +} + +fn compounds_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Compound) } // ---- The art collections of a document, a layer, a group and a compound path ---- @@ -905,7 +927,7 @@ fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { } let now = with_doc(h, doc, |_, st| st.current_layer()); if now != Some(id) { - on_doc(h, doc.uid, true, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + on_doc_layer(h, doc.uid, true, false, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; } Ok(Data::Undefined) } @@ -1026,10 +1048,11 @@ fn board_name(h: &Host, a: &[Data]) -> Answer { read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) } -/// A new artboard name: not empty, at most [`MAX_TEXT_BYTES`] bytes, and no other artboard's -/// (`except`: the artboard being renamed). → the name, trimmed as `artboard.rename` trims it. -fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result { - let Data::String(name) = d else { return Err(HostError::Type("name must be a string".into())) }; +/// A new artboard name: not empty and at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as +/// `String()` writes it. Another artboard may have the same name. → the name, trimmed as +/// `artboard.rename` trims it. +fn board_name_arg(d: &Data) -> Result { + let name = name_text(d)?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } @@ -1037,16 +1060,12 @@ fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result Answer { - let (b, i) = this_board(h, a)?; - let name = with_doc(h, b.doc, |_, st| board_name_arg(st, arg(a, 1), Some(i)))?; - set_board(h, a, |ab| ab.name == name, json!({"name": name})) + let name = board_name_arg(arg(a, 1))?; + set_board(h, a, |ab| ab.name == name, json!({"name": &name})) } fn board_parent(h: &Host, a: &[Data]) -> Answer { @@ -1189,7 +1208,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { let (r, len, name) = with_doc(h, doc, |_, st| { let boards = &st.doc.artboards; h.charge_call(boards.len() as u64)?; - // The first "Artboard N" from one past the count that no artboard has, so names stay unique. + // The first "Artboard N" from one past the count that no artboard has. let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) })?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ccc293c85f..4fe40ddad2 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1391,6 +1391,26 @@ fn layers_list_top_first_and_add_makes_the_new_layer_current() { assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); } +#[test] +fn a_new_or_assigned_layer_stays_the_current_layer() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, base = d.layers[0];\ + var n = d.layers.add(); n.name = 'New'; vc.log(d.activeLayer.name);\ + d.activeLayer = base; vc.log(d.activeLayer.name);\ + d.activeLayer = n; vc.log(d.activeLayer.name);\ + var sub = base.layers.add(); sub.name = 'Sub'; vc.log(d.activeLayer.name);\ + vc.log(d.selection.length); vc.log(d.selection[0].layer.name);", + ); + assert_eq!(out, [json!("New"), json!("Layer 1"), json!("New"), json!("Sub"), json!(1), json!("Layer 1")]); + // The layer the script made current is still current after the run. + let st = s.active().unwrap(); + let current = st.current_layer().and_then(|l| st.doc.node(l)).and_then(|n| n.name.clone()); + assert_eq!(current.as_deref(), Some("Sub")); +} + #[test] fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { let mut s = Session::new(); @@ -1429,7 +1449,8 @@ fn layer_properties_round_trip_and_reject_bad_values() { assert_eq!(undo_steps(&s), steps); let before = format!("{:?}", s.active().unwrap().doc.layers); for (src, msg) in [ - ("app.activeDocument.layers[0].name = 5;", "name must be a string"), + ("app.activeDocument.layers[0].name = null;", "name must be a string"), + ("app.activeDocument.layers[0].name = {};", "name must be a string"), ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), @@ -1535,10 +1556,74 @@ fn group_items_list_every_depth_and_clipped_toggles_the_mask() { assert_eq!(g.children().unwrap()[0].id, b); assert_eq!(undo_steps(&s), steps + 1); assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); - assert!(failure(&mut s, "app.activeDocument.compoundPathItems.add();").contains("empty compound path")); assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); } +#[test] +fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds, bottom to top, the compound path of `a` and the group of `b` (50 pt wide) + // and `c` (70 pt wide). + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], P = L.pageItems, g = L.groupItems[0];\ + vc.log(P[0].typename); vc.log(P[1].typename); vc.log(g.pageItems[0].width); vc.log(g.pageItems[1].width);\ + var e = L.groupItems.add(); e.name = 'E'; vc.log(L.groupItems[0].name); vc.log(L.pageItems[0].name);\ + vc.log(L.compoundPathItems[0].pathItems[0].width);", + ); + assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); +} + +#[test] +fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(); c.name = 'C'; vc.log(c.typename); vc.log(c.pathItems.length);\ + vc.log(d.compoundPathItems.length); vc.log(c.layer.name);", + ); + assert_eq!(out, [json!("CompoundPathItem"), json!(0), json!(1), json!("Layer 1")]); + assert_eq!(undo_steps(&s), steps + 1); + let cid = { + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap().id + }; + // Paths moved into it become its members, and it takes the paint of the first one. The layer + // lists the new compound path first, then `b`, then `a`. + let source = "var d = app.activeDocument, c = d.compoundPathItems.getByName('C'), L = d.layers[0].pageItems, a = L[2], b = L[1];\ + vc.log(L[0].name); a.move(c, ElementPlacement.PLACEATBEGINNING); b.move(c, ElementPlacement.PLACEATEND);\ + vc.log(c.pathItems.length); vc.log(a.parent.typename); vc.log(b.parent.typename);"; + assert_eq!(log(&mut s, source), [json!("C"), json!(2), json!("CompoundPathItem"), json!("CompoundPathItem")]); + let c = s.active().unwrap().doc.node(cid).unwrap(); + let members: Vec = c.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + assert!(members.contains(&a) && members.contains(&b)); + assert_eq!(c.appearance, red); + // A group goes neither into a compound path nor beside a path inside one. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for src in [ + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", + "app.activeDocument.compoundPathItems.add('x').move(app.activeDocument.compoundPathItems.getByName('C'));", + ] { + assert!(failure(&mut s, src).contains("only paths"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1558,7 +1643,7 @@ fn art_collections_follow_edits_between_reads() { let out = log( &mut s, "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ - d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[2].typename); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[0].typename); vc.log(g.length);\ p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", ); assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); @@ -1651,6 +1736,21 @@ fn new_artboards_get_a_name_no_other_artboard_has() { assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); } +#[test] +fn names_take_numbers_and_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, A = d.artboards, L = d.layers[0]; A.add([500, 300, 700, 100]);\ + L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ + A[0].name = 7; vc.log(A[0].name); A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]);\ + vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!(["Same", "Same"]), json!(0)]); + let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Same", "Same"]); +} + #[test] fn artboards_reject_bad_arguments_before_any_change() { let (mut s, _, _) = doc(); @@ -1669,8 +1769,8 @@ fn artboards_reject_bad_arguments_before_any_change() { ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), ("app.activeDocument.artboards.remove(2);", "index must be"), ("app.activeDocument.artboards.remove(-1);", "index must be"), - ("app.activeDocument.artboards[0].name = 'Two';", "another artboard"), ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), + ("app.activeDocument.artboards[0].name = null;", "must be a string"), ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), diff --git a/docs/mcp.md b/docs/mcp.md index 93b4013547..4cec59e36b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2722,11 +2722,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps one artboard. - VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. `groupItems`, - `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's - `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold - only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's + `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in + it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any + depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound + path's `pathItems` have the typename `PathItems`. A layer's or artboard's `name` takes a number or a boolean as + `String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past the next layer beside it and any art between them. @@ -2735,13 +2736,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot with nothing to add or deselect runs no command. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the - layer's or group's contents, or of the current layer's for the document's collection. - `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop + layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` + makes an empty compound path in the same place + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` puts into a compound path + becomes one of its paths, and an empty compound path takes the paint of the first path that goes in; other objects + are refused. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. - Artboard names are trimmed, cannot be empty and are unique: a name - another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one + Artboard names are trimmed and cannot be empty, and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the @@ -2750,10 +2753,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. -- `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: - the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 - puts it directly above the clipping path), as one undo step named Group, and - gives `{id}`. The selection stays as it is. +- `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; + default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, + index 0 puts it directly above the clipping path), as one undo step named Group, and + gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, and an empty + compound path takes the paint of the first path that goes in. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6edddf19b3..023c49c3cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From ff2ceab181b068de57274c28bbf2d2febd054785 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 19:07:47 -0800 Subject: [PATCH 050/533] Scripts: paths keep the paint they are drawn with as they enter or leave a compound path - A path that node.move, move or duplicate puts into a compound path loses its own paint, live shape and pixel alignment, as Make Compound Path leaves its paths; the compound path becomes pixel-aligned when the path was. An empty compound path takes the paint the first path was drawn with: the path's own, or that of the compound path it leaves. - A path that node.move or move takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths. Before, it kept the empty paint Make Compound Path left it and drew nothing. - Artboard.name = '' gives the artboard its default name, Artboard N, as artboard.setProps gives a blank name, instead of throwing. - The undo step of object.newGroup is named through `label`, so the translators' list reads Compound Path as well as Group. - Tests: a compound path's pathItems list the topmost path first, and a path duplicated into a compound path keeps no paint, live shape or pixel alignment of its own. Docs: docs/mcp.md (the order rule names the document's lists; move, duplicate and node.move name a compound path as a place). --- crates/engine/src/cmd/layer.rs | 37 ++++- crates/engine/src/cmd/object/arrange.rs | 4 +- crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/layers.rs | 26 ++-- crates/engine/src/tests/script_dom.rs | 175 +++++++++++++++++++++++- docs/mcp.md | 35 +++-- 6 files changed, 242 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 27d5d58336..5f83152beb 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also in a shown, unlocked compound path, and an empty compound path takes the paint of the first path that goes in; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -930,8 +930,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } - // An empty compound path takes the paint of the first path that goes into it. - let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, n.appearance.clone())); + // An empty compound path takes the paint of the first path that goes into it: the path's own, + // or the paint of the compound path it leaves, which is what painted it. + let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); + let into = compound.map(|c| c.id); + // A path that leaves a compound path for a layer or a group takes the compound path's paint and + // pixel alignment, as Release Compound Path gives them to its paths. + let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -946,6 +953,30 @@ fn move_node(s: &mut Session, p: &Value) -> Result { { n.appearance = appearance; } + // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead. + if let Some(c) = into { + let mut aligned = false; + if let Some(m) = d.node_mut(id) { + m.appearance = vectorcraft_doc::Appearance::default().into(); + aligned = std::mem::take(&mut m.extras_mut().pixel_aligned); + if let NodeKind::Path { live, .. } = &mut m.kind { + *live = None; + } + } + if aligned && let Some(cn) = d.node_mut(c) { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } + } + if let Some((appearance, aligned)) = out_of + && let Some(m) = d.node_mut(id) + { + m.appearance = appearance; + if aligned { + m.extras_mut().pixel_aligned = true; + } + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index bd770334e8..36b3cef6fe 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -131,8 +131,8 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } - let name = if compound { "Compound Path" } else { "Group" }; - let gid = s.edit(name, |d, _| { + let label = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(label, |d, _| { let gid = d.alloc_id(); let clips = d.node(parent).is_some_and(Node::clips); let index = if clips { index.max(1) } else { index }; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c8741952d4..1aeb8d333a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -14,9 +14,11 @@ //! not the active one makes it active for the command and makes the other one active again after. //! //! VectorCraft's own rules, which the help pages do not state: -//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0. -//! `pageItems` lists every object, with the objects inside groups and compound paths after the -//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! - Collections list documents in tab order and the document's art in paint order (bottom first), +//! counted from 0; the `layers` module gives the order of a layer's, a group's and a compound +//! path's lists. The document's `pageItems` lists every object, with the objects inside groups +//! and compound paths after the group or compound path, and leaves out layers and ruler guides. +//! An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 15171be00d..3fafaf684b 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -13,8 +13,8 @@ //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's //! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at -//! any depth, in the order of the document's `pageItems`. +//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. //! - `locked` true means the layer is locked. @@ -587,9 +587,9 @@ pub(super) type ArtList = (u64, Arc, u8, Option, Rc) -> Result>> { { let mut lists = h.dom.art.borrow_mut(); @@ -1048,23 +1048,21 @@ fn board_name(h: &Host, a: &[Data]) -> Answer { read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) } -/// A new artboard name: not empty and at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as -/// `String()` writes it. Another artboard may have the same name. → the name, trimmed as -/// `artboard.rename` trims it. -fn board_name_arg(d: &Data) -> Result { +/// A new artboard name: at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as `String()` writes +/// it. Another artboard may have the same name. → the name, trimmed as `artboard.setProps` trims +/// it; an empty one gives the artboard its default name, `Artboard N` for the Nth artboard. +fn board_name_arg(d: &Data, index: usize) -> Result { let name = name_text(d)?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } let name = name.trim(); - if name.is_empty() { - return Err(HostError::Range("an artboard's name cannot be empty".into())); - } - Ok(name.to_string()) + Ok(if name.is_empty() { format!("Artboard {}", index + 1) } else { name.to_string() }) } fn board_set_name(h: &Host, a: &[Data]) -> Answer { - let name = board_name_arg(arg(a, 1))?; + let (_, i) = this_board(h, a)?; + let name = board_name_arg(arg(a, 1), i)?; set_board(h, a, |ab| ab.name == name, json!({"name": &name})) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4fe40ddad2..e3d0a46807 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1616,7 +1616,7 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { for src in [ "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", - "app.activeDocument.compoundPathItems.add('x').move(app.activeDocument.compoundPathItems.getByName('C'));", + "app.activeDocument.compoundPathItems.add().move(app.activeDocument.compoundPathItems.getByName('C'));", ] { assert!(failure(&mut s, src).contains("only paths"), "{src}"); } @@ -1624,6 +1624,146 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); } +/// The paint of a compound path's only path is the compound path's: moved into an empty compound +/// path, the path gives it that paint, not its own default one. +#[test] +fn a_path_moved_out_of_a_compound_path_gives_an_empty_one_the_paint_it_was_drawn_with() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, old = d.compoundPathItems[0], c = d.compoundPathItems.add(); c.name = 'C';\ + old.pathItems[0].move(c); vc.log(d.compoundPathItems.getByName('C').pathItems.length);", + ); + assert_eq!(out, [json!(1)]); + let d = &s.active().unwrap().doc; + let c = d.parent_of(a).and_then(|p| d.node(p)).unwrap(); + assert_eq!(c.name.as_deref(), Some("C")); + assert_eq!(c.appearance, red); + assert_ne!(d.node(a).unwrap().appearance, red); +} + +/// `node.move` into a compound path leaves the path without paint or pixel alignment of its own, +/// as Make Compound Path leaves its paths, and the compound path takes the alignment. +#[test] +fn node_move_into_a_compound_path_clears_the_paths_own_paint() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let painted = s.active().unwrap().doc.node(b).unwrap().appearance.clone(); + let member = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(b), Some(cid)); + let n = d.node(b).unwrap(); + assert_ne!(n.appearance, painted); + assert_eq!(n.appearance, member); + assert!(!n.extras().pixel_aligned); + assert!(d.node(cid).unwrap().extras().pixel_aligned); +} + +#[test] +fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { + let (mut s, a, b) = doc(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(matches!(s.active().unwrap().doc.node(cid).unwrap().kind, NodeKind::Compound { .. })); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("only paths"), "{err}"); + for hide in ["object.lock", "object.hide"] { + s.execute("select.set", &json!({"ids": [cid.0]})).unwrap(); + s.execute(hide, &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("hidden or locked"), "{hide}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +/// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint. +#[test] +fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let blue = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(), p = d.layers[0].pageItems[2]; var q = p.duplicate(c);\ + vc.log(c.pathItems.length); vc.log(q.parent.typename); vc.log(p.parent.typename);", + ); + assert_eq!(out, [json!(1), json!("CompoundPathItem"), json!("Layer")]); + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + let c = d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(c.appearance, blue); + assert_eq!(d.node(a).unwrap().appearance, blue); + // The copy keeps no paint, live shape or pixel alignment of its own. + let q = &c.children().unwrap()[0]; + assert_ne!(q.appearance, blue); + assert!(matches!(q.kind, NodeKind::Path { live: None, .. })); + assert!(!q.extras().pixel_aligned); +} + +/// A compound path's `pathItems` list its topmost path first. +#[test] +fn a_compound_paths_path_items_list_the_topmost_path_first() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let source = "var P = app.activeDocument.compoundPathItems[0].pathItems; vc.log(P[0].width); vc.log(P[1].width);"; + // `b` (50 pt wide) on top, then `a` (30 pt wide) on top. + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(50), json!(30)]); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(30), json!(50)]); +} + +/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound +/// path's paint and pixel alignment, as Release Compound Path gives them. +#[test] +fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let (cid, red, lid) = { + let d = &s.active().unwrap().doc; + let cid = d.parent_of(a).unwrap(); + (cid, d.node(cid).unwrap().appearance.clone(), d.layer_containing(a).unwrap()) + }; + assert_ne!(s.active().unwrap().doc.node(a).unwrap().appearance, red); + s.execute("node.move", &json!({"id": a.0, "parent": lid.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(lid)); + let n = d.node(a).unwrap(); + assert_eq!(n.appearance, red); + assert!(n.extras().pixel_aligned); + // The path left behind keeps none of its own. + assert_eq!(d.parent_of(b), Some(cid)); + assert_ne!(d.node(b).unwrap().appearance, red); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1737,16 +1877,38 @@ fn new_artboards_get_a_name_no_other_artboard_has() { } #[test] -fn names_take_numbers_and_artboards_may_share_a_name() { +fn names_take_numbers_and_booleans() { let (mut s, _, _) = doc(); let out = log( &mut s, - "var d = app.activeDocument, A = d.artboards, L = d.layers[0]; A.add([500, 300, 700, 100]);\ + "var d = app.activeDocument, L = d.layers[0];\ L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ - A[0].name = 7; vc.log(A[0].name); A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]);\ - vc.log(A.getByName('Same').artboardRect[0]);", + d.artboards[0].name = 7; vc.log(d.artboards[0].name); vc.log(typeof d.artboards[0].name);", ); - assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!(["Same", "Same"]), json!(0)]); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!("string")]); +} + +#[test] +fn an_empty_artboard_name_gives_the_default_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[0].name = 'Front'; A[1].name = 'Back'; A[0].name = ''; A[1].name = ' ';\ + vc.log([A[0].name, A[1].name]);", + ); + assert_eq!(out, [json!(["Artboard 1", "Artboard 2"])]); +} + +#[test] +fn two_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]); vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!(["Same", "Same"]), json!(0)]); let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); assert_eq!(names, ["Same", "Same"]); } @@ -1769,7 +1931,6 @@ fn artboards_reject_bad_arguments_before_any_change() { ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), ("app.activeDocument.artboards.remove(2);", "index must be"), ("app.activeDocument.artboards.remove(-1);", "index must be"), - ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), ("app.activeDocument.artboards[0].name = null;", "must be a string"), ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), diff --git a/docs/mcp.md b/docs/mcp.md index 4cec59e36b..5bbf805842 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2657,9 +2657,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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 - 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 + document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a + group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` + directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an @@ -2671,8 +2671,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. - VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the - objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates + VectorCraft's own rules: documents are listed in tab order, and the document's page items in paint order from the + bottom, with the objects inside groups and compound paths after their group and without layers and ruler guides + (the layers paragraph below gives the order of a layer's, a group's and a compound path's lists). Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` @@ -2738,14 +2739,17 @@ app through the global object `vc`, and writes to the Script Console and runs ot path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` makes an empty compound path in the same place - (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` puts into a compound path - becomes one of its paths, and an empty compound path takes the paint of the first path that goes in; other objects - are refused. `artboards.add` and `insert` stop - at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a + compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. An empty + compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the + compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or + a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths. + `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. - Artboard names are trimmed and cannot be empty, and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one - past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. + Artboard names are trimmed, an empty name gives the artboard its default name (`Artboard N` for the Nth artboard), + and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's + name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because @@ -2757,8 +2761,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. - The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, and an empty - compound path takes the paint of the first path that goes in. + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path + gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A + path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel + alignment. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -6463,7 +6469,8 @@ and `layerRows`, the rows highlighted in the panel. bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level - form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. A row that + form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts + a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join, From 8cc34c71a07a4ff759dd3206b410ea59e51e7b66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:17:14 -0800 Subject: [PATCH 051/533] Scripts: a palette event is dropped once a getter or a handler closed the palette A palette event checks again, after the palette's description is read and after each handler is read or run, that the host still shows the palette under the id the event names. A getter or an earlier handler that closed the palette now stops the event, so no click or change reaches a closed palette, and a list change whose palette closed is dropped rather than refused. --- crates/js/src/scriptui.rs | 56 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 62 +++++++++++++++++++++++ crates/ui-egui/src/tests/script_window.rs | 21 +++++++- 3 files changed, 133 insertions(+), 6 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 6e997aa2af..e912e8a387 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -794,6 +794,10 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult) -> JsResult { + if keep.is_some() { + return Ok(true); + } + let id = slot(i, ev, "palette")?; + Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) +} + +/// Calls control `c`'s handler `name` for the event `ev` when it has one and `win` still takes the +/// event once the handler has been read: a getter for `name` may have closed the palette. +/// → `None` when `win` no longer takes the event, otherwise `handler`'s answer. +fn event_handler(i: &mut Interp, win: ObjId, c: ObjId, ev: ObjId, keep: Option<&[Value]>, name: &str) -> JsResult>> { + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + let f = i.get_value(&Value::Object(c), &key(name))?; + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + if !i.is_callable(&f) { + return Ok(Some(None)); + } + i.call(&f, &Value::Object(c), &[]).map(|v| Some(Some(v))) +} + /// The control at `place` in `win` as it is now: the index of each control among its container's /// controls, from the window down, as the host counts places. `None` when the palette has no /// control there. @@ -975,7 +1007,8 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { /// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of /// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks /// to close it with 1 when it is the default element and 2 when it is the cancel element, which -/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. No handler of a palette runs +/// once a getter, a setter or an earlier handler of the event closed the palette. fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { let id = match slot(i, ev, "id")? { Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, @@ -1003,7 +1036,10 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } i.put(c, key("value"), Value::Bool(true), true)?; } - if handler(i, c, "onClick")?.is_none() + let Some(ran) = event_handler(i, win, c, ev, keep, "onClick")? else { + return Ok(()); + }; + if ran.is_none() && kind == "button" && let Some(keep) = keep { @@ -1019,11 +1055,15 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, match kind.as_str() { "edittext" => { i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } "slider" => { i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } _ => { let n = match value { @@ -1050,6 +1090,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; + // An item's text getter may have closed the palette, and its `onClose` + // may have changed the list: the event is then dropped, not refused. + if !still_takes(i, win, ev, keep)? { + return Ok(()); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } @@ -1058,7 +1103,8 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, set_slot(i, c, SELECTION, Value::Number(n))?; } } - handler(i, c, "onChange")?; + // `onChanging` may have closed the palette. + event_handler(i, win, c, ev, keep, "onChange")?; } _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index c6ed56abdb..063d02a2af 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -549,6 +549,68 @@ fn a_palette_event_finds_its_control_by_its_place() { assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); } +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \ + var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \ + Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();", + ) + .unwrap(); + // The event reads the label's text for the palette's description, which closes the palette. + r.run("armed = true; Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The event reads the first item's text twice: for the palette's description, then to compare + // it with the items the person saw. The second read closes the palette. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into())); + assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \ + Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run"); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text closes the palette, and its `onClose` adds an item. + r.run( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ + p.onClose = function () { l.add('item', 'c'); }; \ + Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \ + p.show();", + ) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error"); + assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into())); +} + #[test] fn a_palette_s_visible_follows_hide_and_show() { let (mut r, _) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 45bb4db50e..ed94fdde69 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -551,7 +551,7 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { // A click on Swap, then a choice in the list as it was before Swap's handler ran, both given // in one frame. let swap = json!({"event": "click", "control": 2, "value": null}); - let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); frame(&mut app, Vec::new()); assert!(until_window(&mut app), "the script takes the click and waits again"); @@ -564,6 +564,25 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { assert_eq!(log(&app), json!([[1, "null"]]), "the choice for the old items was not given"); } +#[test] +fn a_queued_list_choice_is_given_while_its_list_is_unchanged() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); w.add('button', undefined, 'OK'); \ + vc.log([w.show(), String(l.selection)]);", + ); + assert!(until_window(&mut app)); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([choice])); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "the choice left the line"); + assert!(until_window(&mut app), "the script takes the choice and waits again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "b"]]), "the choice for the same items was given"); +} + #[test] fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { let mut app = app(); From 01ec822509dfd2adde186cf25f543aed4c29ad9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:41:53 -0800 Subject: [PATCH 052/533] Plug-ins: drop the open events of a script run that fails A script that opens a document and then throws, runs out of budget or is abandoned loses that document with its working copy, so its waiting document.opened event is now dropped when the run ends. The saves it made before failing are still delivered, and so is a document the frontend opened while the run was paused. --- crates/engine/src/plugin_events.rs | 24 ++++++++++++- crates/engine/src/script/mod.rs | 4 +++ crates/engine/src/tests/plugin_events.rs | 43 ++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 552d93bd21..555f2ac308 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -67,6 +67,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, + /// Queued by a command of the running script, whose run has not ended yet + /// ([`Session::plugin_events_script_ended`]). + by_script: bool, } impl Pending { @@ -169,7 +172,7 @@ impl PluginEvents { log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, by_script: false }); self.queued += 1; } @@ -270,6 +273,25 @@ impl Session { return; } self.plugin_events.queue(event, uid, Vec::new(), to); + // An open or a save is queued as its own entry, the newest. + if self.script_in_run + && let Some(p) = self.plugin_events.pending.back_mut() + { + p.by_script = true; + } + } + + /// At the end of a script's run. When the run failed (`kept` false), drops the waiting + /// `document.opened` events its commands queued, since the documents they opened were discarded + /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the + /// events of documents a frontend opened while the run was paused. + pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { + if !kept { + self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + } + for p in &mut self.plugin_events.pending { + p.by_script = false; + } } /// A mark for [`Session::forget_plugin_opens_since`]: the events queued so far. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 2d15652731..83f6b588d3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1910,6 +1910,8 @@ impl Session { lost }); drop(lost); + // The job's working copy went with it, with the documents the run opened. + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2182,6 +2184,7 @@ impl Session { let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); close_run(self, &job.host, &mut report, ending(&e.kind)); self.end_job(job, e.kind == RunErrorKind::Internal); + self.plugin_events_script_ended(false); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2271,6 +2274,7 @@ impl Session { host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); + self.plugin_events_script_ended(true); self.script_report = Some(report.clone()); Ok(report) } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 6ee0e8342b..9f757b020e 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -328,6 +328,49 @@ fn a_save_before_a_failed_batch_step_is_delivered() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A document a script opened before it failed is discarded with the run's working copy, so the +/// plug-in is not told of it. The save the script made before failing is still given, and so is a +/// document the frontend opened while the run was paused. +#[test] +fn a_failed_script_gives_its_save_but_not_its_open() { + let id = "test.events.failed_script"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-failed-script-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("failed-script.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + assert!(s.docs.iter().all(|d| d.uid == doc || d.uid == front), "the script's document was discarded"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc}), json!({"type": "document.opened", "document": front})]); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] From 0ce36a1b79aca3b8dff3d98fda51e634a22492c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:08:26 -0800 Subject: [PATCH 053/533] Scripts: a concatenated coefficient is rounded once, past a product's rounding When a product leaves the range of a number, concatenateMatrix now adds both products, the parts their rounding drops and the translation into an exact sum, and rounds that sum to the nearest number once. A coefficient just past the largest number gives RangeError, and a sum in the range of subnormal numbers rounds as the exact value does. --- crates/engine/src/script/dom/matrix.rs | 102 +++++++++++++++++--- crates/engine/src/tests/script_dom_prefs.rs | 32 +++++- 2 files changed, 121 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 9ee2fda4e6..2e8a4d7df7 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -96,18 +96,95 @@ fn then(m: Matrix, n: Matrix) -> Matrix { } /// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only one that is not 0, the sum is taken as numbers are. Otherwise the +/// normal numbers is the only term that is not 0, the sum is taken as numbers are. Otherwise the /// products are summed past the range of a number and rounded at the end, so a finite value is not /// lost to a product too large or too small for a number. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; - let alone = |a: f64, b: f64| a == 0.0 || b == 0.0; + let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return plain + t; } - products_difference(x, y, 0.0 - z, w).add(Wide::of(t)).value() + // Each product is split into its rounded value and the part that rounding drops, both exact. + // The five parts are added one at a time into a list of values that do not overlap, smallest + // first, whose sum is exact (Shewchuk's expansion). + let product = |a: f64, b: f64| { + let (a, b) = (Wide::of(a), Wide::of(b)); + let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); + [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] + }; + let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); + let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Vec::with_capacity(10), grow); + nearest(&exact) +} + +/// `sums` with `part` added: values that do not overlap, smallest first, whose sum is exactly the +/// sum of `sums` and `part`. The last value is the largest and has the sign of the sum. +fn grow(sums: Vec, part: Wide) -> Vec { + let mut carry = part; + let mut kept = Vec::with_capacity(sums.len() + 1); + for h in sums { + let (sum, rest) = carry.two_sum(h); + if rest.m != 0.0 { + kept.push(rest); + } + carry = sum; + } + if carry.m != 0.0 { + kept.push(carry); + } + kept +} + +/// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. +fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { + let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums.to_vec(), grow); + match rest.last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } +} + +/// The number nearest the exact sum of `sums`, ties to the even one, and infinite when the sum +/// rounds to 2^1024 or past it. The sum of the values from the smallest up comes within a step of +/// it; the halfway points to the neighbors of that number are then compared with the exact sum, so +/// the result is rounded once. +fn nearest(sums: &[Wide]) -> f64 { + let even = |v: f64| v.to_bits() & 1 == 0; + let mut v = sums.iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); + for _ in 0..4 { + // Half the step to the next number up, and to the next number down. Past the largest + // number the step is to 2^1024, which is 2^971 away. + let up = if v == f64::MAX { f64::INFINITY } else { v.next_up() }; + let down = if v == f64::MIN { f64::NEG_INFINITY } else { v.next_down() }; + let half_up = if up.is_finite() { Wide::new(up - v, -1) } else { Wide::new(1.0, 970) }; + let half_down = if down.is_finite() { Wide::new(v - down, -1) } else { Wide::new(1.0, 970) }; + match sign_past(sums, v, Wide { m: 0.0 - half_up.m, e: half_up.e }) { + 1 => { + v = up; + if !v.is_finite() { + return v; + } + continue; + } + 0 => return if even(v) { v } else { up }, + _ => {} + } + match sign_past(sums, v, half_down) { + -1 => { + v = down; + if !v.is_finite() { + return v; + } + } + 0 => return if even(v) { v } else { down }, + _ => return v, + } + } + v } fn translate(dx: f64, dy: f64) -> Matrix { @@ -217,17 +294,20 @@ impl Wide { Self::new(self.m / o.m, self.e.saturating_sub(o.e)) } - /// The sum. A number more than 2^60 times smaller than the other is past its precision. - fn add(self, o: Self) -> Self { + /// The sum and the part of it that rounding drops, so that `self + o` is exactly their sum. A + /// number more than 2^110 times smaller than the other is returned whole as the dropped part. + fn two_sum(self, o: Self) -> (Self, Self) { let (big, small) = if self.m == 0.0 || (o.m != 0.0 && o.e > self.e) { (o, self) } else { (self, o) }; - if small.m == 0.0 { - return big; - } let gap = small.e.saturating_sub(big.e); - if gap < -60 { - return big; + if small.m == 0.0 || gap < -110 { + return (big, small); } - Self::new(big.m + small.m * pow2(gap), big.e) + // Knuth's two-sum: `small` scaled to `big`'s power of 2 is exact, and so is the error. + let s = small.m * pow2(gap); + let sum = big.m + s; + let back = sum - big.m; + let rest = (big.m - (sum - back)) + (s - back); + (Self::new(sum, big.e), Self::new(rest, big.e)) } /// The nearest `f64`: infinite past its range, and 0 or a subnormal number below it. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index dc2bacdff0..fa01766d63 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -384,9 +384,37 @@ fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_numbe vc.log(app.concatenateMatrix(mat([y, y, 0, 1, 0, 0]), mat([z, 0, z, 1, 0, 0])).mValueA === Number.MIN_VALUE);\ var p = 2.0543170765449965e-57, q = 6.201533916984909e-252;\ vc.log(app.concatenateMatrix(mat([p, 0, 0, 1, 0, 0]), mat([q, 0, 0, 1, 0, 0])).mValueA === p * q);\ - vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));", + vc.log(v(app.concatenateMatrix(mat([-2, 0, 0, -3, 0, 0]), mat([0, 1, -1, 0, 0, 0]))));\ + var big = mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), up = 1 + Math.pow(2, -52);\ + try { app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 971), 0])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + vc.log(app.concatenateMatrix(big, mat([up, 0, 0, 1, -Math.pow(2, 972), 0])).mValueTX === Number.MAX_VALUE);\ + var h = Math.pow(2, 500), far = mat([1, 0, 0, 1, Math.pow(2, 600), -Math.pow(2, 600)]);\ + vc.log(app.concatenateMatrix(far, mat([h, 0, h, 1, 1, 0])).mValueTX);\ + var g = Math.pow(2, 100), farther = mat([1, 0, 0, 1, Math.pow(2, 1000), -Math.pow(2, 1000)]);\ + vc.log(app.concatenateMatrix(farther, mat([g, 0, g, 1, Math.pow(2, -100), 0])).mValueTX === Math.pow(2, -100));\ + var tiny = mat([1, 0, 0, 1, y, 0]);\ + vc.log(app.concatenateMatrix(tiny, mat([z, 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);\ + var least = mat([1, 0, 0, 1, Number.MIN_VALUE, 0]);\ + vc.log(app.concatenateMatrix(least, mat([0.5 - Math.pow(2, -54), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === Number.MIN_VALUE);\ + vc.log(app.concatenateMatrix(least, mat([0.5 + Math.pow(2, -53), 0, 0, 1, Number.MIN_VALUE, 0])).mValueTX === 2 * Number.MIN_VALUE);", + ); + assert_eq!( + out, + vec![ + json!([0, true, true, 1, 0, true]), + json!(true), + json!(true), + json!([0, -2, 3, 0, 0, 0]), + json!("RangeError"), + json!(true), + json!(1), + json!(true), + json!(true), + json!(true), + json!(true) + ] ); - assert_eq!(out, vec![json!([0, true, true, 1, 0, true]), json!(true), json!(true), json!([0, -2, 3, 0, 0, 0])]); } #[test] From 73394611d102f04fda4fd3061f7769d831885890 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:20:02 -0800 Subject: [PATCH 054/533] Scripts: ScriptUI windows, groups and panels have update() Window.update() was missing, so a palette handler that moved a progress bar and called update() ended with an error. The window-object reference describes update() as redrawing the window and taking the person's waiting events, so that a Cancel button can stop a long loop (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - update() on a shown palette, or on a group or panel in it, runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a loop that calls update() sees a Cancel button's onClick. Those events do not get runs of their own. - In the app, an update() in the script's own code then pauses the run so the app draws the palette, at most once every 16 ms of the run's time (VectorCraft's own interval). Only an update() that pauses gives the host the palette's controls, so a loop of many update() calls does not use up the run's host-call or bridge limits. An update() in a handler, a callback of a built-in function, a getter or a conversion, and any update() on the web, does not pause the run. - update() on the showing dialog, or a group or panel in it, runs without an error; the dialog shows a handler's changes when the handler returns. On a window that is not showing it throws an Error, and on a control that is not a container a TypeError. Whether a palette is showing comes from show() and hide(), not from its visible property. - docs/mcp.md and the progress-doc line describe update(). --- crates/engine/src/script/mod.rs | 24 ++++ crates/engine/src/script/palettes.rs | 73 +++++++---- crates/engine/src/script/scriptui.rs | 30 ++++- crates/engine/src/tests/script_palettes.rs | 105 +++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/scriptui.rs | 86 +++++++++++++ crates/js/src/scriptui_tests.rs | 117 ++++++++++++++++++ docs/mcp.md | 22 +++- docs/target-app-parity.md | 2 +- 9 files changed, 429 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ef204e4582..2ea2f2aa71 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -108,6 +108,9 @@ pub const MAX_LOG_LINES: usize = 10_000; pub const MAX_LOG_BYTES: usize = 4 << 20; /// The most bytes of `args` given to one run, as JSON. pub const MAX_ARGS_BYTES: usize = 1 << 20; +/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app +/// draws the window (VectorCraft's own value, about one frame). +const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); /// The `vc.run` calls one slice makes before the interface draws again. const SLICE_HOST_CALLS: u32 = 256; /// The bytes that may cross between a script and the host in one run. @@ -799,6 +802,8 @@ struct Host { started: Option, /// The time since [`Host::started`] at which a `$.sleep` ends. wake_at: Cell>, + /// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice. + drawn_at: Cell>, /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). can_wait: Rc>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). @@ -997,6 +1002,24 @@ impl Host { Ok(()) } + /// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is + /// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. → + /// whether it does, and the palette's controls are to be given now. Without a clock (the web + /// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run + /// ends for another reason. + fn update_drawn(&self) -> bool { + if !self.framed { + return false; + } + let Some(now) = self.elapsed() else { return false }; + if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) { + return false; + } + self.drawn_at.set(Some(now)); + self.pause.set(true); + true + } + /// The time left of a `$.sleep`, or none when the run is not asleep. fn asleep(&self) -> Option { let wake = self.wake_at.get()?; @@ -2081,6 +2104,7 @@ impl Session { kept_maps, started: clock(), wake_at: Cell::new(None), + drawn_at: Cell::new(None), can_wait: realm.wait_flag(), eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 673fcf5714..68c84e3f0d 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -8,7 +8,9 @@ //! own in the palette's engine, which takes the mutation lease like any other run: one event at a //! time, oldest first, each starting only once no run is going. While an event waits, another click //! on the same control, another change of it or another close of the same palette takes its place -//! in line, with the newer value, instead of waiting as well. +//! in line, with the newer value, instead of waiting as well. A palette's `update()` in a run of the +//! palette's engine takes the events that wait for that engine's palettes and runs their handlers in +//! that run instead ([`Palettes::take_for`]). //! //! A palette closes when its script calls `close()` or the person closes it, unless `onClose` //! returns `false`; when its engine is dropped or ends with an internal error; and with the session. @@ -188,33 +190,56 @@ impl Palettes { /// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for /// example because a handler disabled or hid it, is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { - while let Some(mut q) = self.waiting.pop_front() { - let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; - if let Some(c) = control_of(&mut q.event) { - let Some(at) = p.dialog.control_at(&q.place) else { continue }; - *c = at; + while let Some(q) = self.waiting.pop_front() { + if let Some(taken) = self.checked(q) { + return Some(taken); } - // A list's change whose list a run changed since goes to its run, which ends with the - // error that says so, when the list can still take a change: the choice is checked - // without its item, which the list may no longer have. - let list_changed = match (&q.event, &q.list) { - (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { - p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) - } - _ => None, - }; - if let Some(c) = list_changed { - if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { - continue; - } - } else { - let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; - q.event = event; - } - return Some((p.clone(), q)); } None } + + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other + /// engines' palettes keep their places in line. + fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { + loop { + let list = &self.list; + let at = self.waiting.iter().position(|q| list.iter().any(|p| p.id == q.palette && p.engine == engine))?; + let q = self.waiting.remove(at)?; + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + } + + /// The taken event `q` given to the control at its place in its palette, and that palette, or + /// `None` when it is dropped ([`Palettes::next`]). + fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; + if let Some(c) = control_of(&mut q.event) { + *c = p.dialog.control_at(&q.place)?; + } + // A list's change whose list a run changed since goes to its run, which ends with the + // error that says so, when the list can still take a change: the choice is checked + // without its item, which the list may no longer have. + let list_changed = match (&q.event, &q.list) { + (UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => { + p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c) + } + _ => None, + }; + if let Some(c) = list_changed { + scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?; + } else { + q.event = scriptui::check_event(&p.dialog, q.event).ok()?; + } + Some((p.clone(), q)) + } + + /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` + /// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]). + pub(crate) fn take_for(&mut self, engine: &str) -> Option { + self.next_of(engine).map(|(_, q)| q) + } } /// `name` in a `#targetengine` line, quoted with a quote it does not hold. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index bb96c2771d..e460408a51 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -38,6 +38,7 @@ use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; use super::Host; +use super::palettes::Queued; /// The largest size or place, in pixels, of a dialog or a control in it. pub const MAX_EXTENT: f32 = 8192.0; @@ -712,6 +713,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("paletteHide".into(), function(link, palette_hide)), ("paletteClose".into(), function(link, palette_close)), ("paletteEvent".into(), function(link, palette_event)), + ("paletteTake".into(), function(link, palette_take)), + ("paletteDraw".into(), function(link, palette_draw)), ]) } @@ -747,7 +750,7 @@ fn palette_show(host: &Host, args: &[Data]) -> Result { shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) } -/// The palette `id`'s controls as a handler or `add()` left them. +/// The palette `id`'s controls as a handler, `add()` or `update()` left them. fn palette_update(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); let dialog = described(host, args)?; @@ -757,6 +760,22 @@ fn palette_update(host: &Host, args: &[Data]) -> Result { Ok(Data::Undefined) } +/// A palette's `update()` in the script's own code asks whether the app draws the palette now +/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's +/// controls through `paletteUpdate`. +fn palette_draw(host: &Host, _: &[Data]) -> Result { + palette_engine(host)?; + Ok(Data::Bool(host.update_drawn())) +} + +/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine, +/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. +fn palette_take(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let taken = host.session.borrow_mut().script_palettes.take_for(&engine); + Ok(taken.map_or(Data::Null, event_data)) +} + fn palette_hide(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { @@ -779,7 +798,12 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { /// list's change the items the palette showed; `null` for any other run, and after the first call. fn palette_event(host: &Host, _: &[Data]) -> Result { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; - let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; + Ok(event_data(queued)) +} + +/// The waiting event `queued` as a script takes it ([`palette_event`]). +fn event_data(queued: Queued) -> Data { + let Data::Object(mut fields) = queued.event.data() else { return Data::Null }; fields.push(("palette".into(), Data::Number(queued.palette as f64))); if !queued.place.is_empty() { fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); @@ -788,7 +812,7 @@ fn palette_event(host: &Host, _: &[Data]) -> Result { fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); fields.push(("revision".into(), Data::Number(revision))); } - Ok(Data::Object(fields)) + Data::Object(fields) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index c432700fe6..eff97479d1 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -2,11 +2,13 @@ //! and run one at a time after it, the events that take a waiting one's place, `close()` and the //! close box, the engine's end, and the limits. +use std::time::Duration; + use serde_json::{Value, json}; use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; use crate::script::scriptui::PALETTE_NEEDS_ENGINE; -use crate::script::{DialogAnswer, UiEvent, Waiting}; +use crate::script::{DialogAnswer, TEST_ELAPSED, UiEvent, Waiting}; use crate::*; /// One open document with one rectangle. @@ -72,6 +74,107 @@ fn show_returns_at_once_and_the_palette_stays_after_the_run() { assert_eq!(changed["log"], json!(["change abc"])); } +#[test] +fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["done"]), "update() in the handler does not throw"); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); +} + +#[test] +fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ + for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); + for _ in 0..100 { + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + if value(&s) > 0.0 { + break; + } + } + let first = value(&s); + assert!(first > 0.0); + TEST_ELAPSED.set(Some(Duration::from_millis(16))); + assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); + let second = value(&s); + assert!(second > first, "the palette shows the second update()"); + assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); + assert!(value(&s) > second); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["canceled"]), "{report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_in_a_handler_does_not_pause_the_run() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); + assert_eq!(report["log"], json!(["done"])); + TEST_ELAPSED.set(None); +} + +#[test] +fn many_update_calls_within_one_interval_give_the_controls_once() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + let report = run_in_app( + &mut s, + "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ + var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ + p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", + ); + let calls = report["hostCalls"].as_u64().unwrap(); + assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); + let bar = s.script_palettes()[0].dialog.nodes[2].value; + assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); + TEST_ELAPSED.set(None); +} + #[test] fn a_later_run_in_the_engine_changes_what_the_palette_shows() { let mut s = one_doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 08badaae56..ba03106e4b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), ("Window.", "__vcPaletteEvent length prototype"), - ("Window.prototype.", "add center close constructor findElement hide show"), + ("Window.prototype.", "add center close constructor findElement hide show update"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index e912e8a387..2d2ccf2e9a 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -33,6 +33,14 @@ //! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a //! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown //! palette does the same for that palette, so the host's list of its controls stays in step. +//! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits +//! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or +//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! handler, a callback of a built-in function, a getter or a conversion), it asks the host's +//! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the +//! palette's description. On the showing dialog, or a group or panel in it, `update()` does +//! nothing more, and on a window that is not showing it throws an `Error`. A dialog takes the +//! person's events once the running handler returns. //! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the @@ -77,6 +85,7 @@ const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; const PALETTE_ID: &str = "__vcPaletteId"; +const SHOWN: &str = "__vcShown"; const IN_CLOSE: &str = "__vcInClose"; /// How many times a list's items were added or removed: a palette's waiting change of the list is /// for the items it had then. @@ -683,11 +692,76 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + set_slot(i, o, SHOWN, Value::Bool(false))?; i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } +/// `update()` on a window: [`update_window`]. +fn update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, palette) = window_of(i, &this, "update")?; + update_window(i, o, palette, own)?; + Ok(Value::Undefined) +} + +/// Whether the native running now was called from the script's own code in a run that can pause, +/// as the host's functions find whether a run can wait. +fn own_code(i: &Interp) -> bool { + i.in_slice && i.reentry == 0 +} + +/// `update()` on a `group` or a `panel`: [`update_window`] for the window that holds it. +fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, kind) = element(i, &this, "update")?; + if !is_container(&kind) { + return Err(i.type_error("update: this is not a ScriptUI window or container")); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a container without its window".into())) }; + let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); + update_window(i, win, palette, own)?; + Ok(Value::Undefined) +} + +/// `update()` on the window `win`. On a shown palette: hands each event that waits for a palette of +/// the run's engine to its palette ([`take_waiting`]), and then, from the script's own code (`own`), +/// gives the host the palette's controls when the host draws it now (`paletteDraw`). The showing +/// dialog's controls go to the host when its handler returns, since a handler runs to its end in +/// one slice. Whether a palette shows is the host's, not its `visible` property. A window that is +/// not showing throws. +fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResult<()> { + let showing = if palette { slot(i, win, SHOWN)?.truthy() } else { classes(i)?.showing == Some(win) }; + if !showing { + return Err(error(i, "update: the window is not showing")); + } + if !palette { + return Ok(()); + } + take_waiting(i)?; + if !own || !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let f = host_fn(i, "paletteDraw")?; + if i.call(&f, &Value::Undefined, &[])?.truthy() { + update_palette(i, win)?; + } + Ok(()) +} + +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +fn take_waiting(i: &mut Interp) -> JsResult<()> { + let f = host_fn(i, "paletteTake")?; + loop { + let answer = i.call(&f, &Value::Undefined, &[])?; + if answer.as_object().is_none() { + return Ok(()); + } + deliver(i, answer)?; + } +} + fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { if let Some(c) = i.script_ui.as_mut() { f(&mut c.palettes); @@ -705,6 +779,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_slot(i, win, SHOWN, Value::Bool(false))?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; @@ -760,6 +835,7 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + set_slot(i, win, SHOWN, Value::Bool(true))?; i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; @@ -773,6 +849,14 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; + deliver(i, answer)?; + Ok(Value::Undefined) +} + +/// Gives the host's event `answer` (`{palette, event, id, value, place}`, or anything else for +/// none) to its palette the way a dialog takes the person's event. An event for a palette that has +/// closed does nothing. +fn deliver(i: &mut Interp, answer: Value) -> JsResult { let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; let mark = i.temp_roots.len(); i.temp_roots.push(answer.clone()); @@ -1422,6 +1506,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; + method(i, window_proto, "update", update, 0)?; pausable_method(i, window_proto, "show", show, 0)?; method(i, control_proto, "add", add, 4)?; method(i, control_proto, "findElement", find_element, 1)?; @@ -1429,6 +1514,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, control_proto, "notify", notify, 1)?; method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; + method(i, control_proto, "update", control_update, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 063d02a2af..355faee1cf 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -380,6 +380,12 @@ type Calls = Rc>>; /// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives /// the events in `events`, in order, then `null`. fn palette_realm(events: Vec) -> (Realm, Calls) { + palette_realm_with(events, Vec::new(), Vec::new()) +} + +/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, +/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); let calls: Calls = Rc::default(); @@ -403,6 +409,18 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let taken = RefCell::new(VecDeque::from(taken)); + let c = calls.clone(); + let take: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteTake".into(), 0.0)); + Ok(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let draws = RefCell::new(VecDeque::from(draws)); + let c = calls.clone(); + let draw: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteDraw".into(), 0.0)); + Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false))) + }); let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into()))); let items = vec![ ("open".into(), HostItem::Function(none.clone())), @@ -414,6 +432,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), ("paletteEvent".into(), HostItem::Function(event)), + ("paletteTake".into(), HostItem::Function(take)), + ("paletteDraw".into(), HostItem::Function(draw)), ]; r.define_script_ui(items).unwrap(); (r, calls) @@ -467,6 +487,103 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } +fn count(calls: &Calls, name: &str) -> usize { + calls.borrow().iter().filter(|(n, _)| n == name).count() +} + +#[test] +fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]); + r.start( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \ + for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }", + ) + .unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn"); + assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws"); +} + +#[test] +fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() { + let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]); + r.run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();", + ) + .unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start("Window.__vcPaletteEvent();").unwrap(); + while r.advance(1_000_000).unwrap() == Progress::Paused {} + assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn"); + assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls"); + r.refresh_script_ui().unwrap(); + assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends"); +} + +#[test] +fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \ + cancel.onClick = function () { stopped = true; }; p.show(); \ + var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); + assert!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); +} + +#[test] +fn update_throws_for_a_window_that_is_not_showing() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \ + ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into())); + let (mut r, _) = palette_realm(Vec::new()); + let hidden = r + .run( + "var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \ + p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()", + ) + .unwrap(); + assert_eq!(hidden, JsValue::String("before show,hidden".into())); +} + +#[test] +fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() { + let (mut r, _, _) = realm(vec![click(12)]); + let source = format!( + "{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \ + [w.show(), done].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into())); +} + +#[test] +fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() { + let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]); + r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap(); + let before = count(&calls, "paletteUpdate"); + r.start( + "var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \ + p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \ + try { b.update(); } catch (e) { log.push(e.name); } log.join()", + ) + .unwrap(); + let log = loop { + if let Progress::Done(v) = r.advance(1_000_000).unwrap() { + break v; + } + }; + assert_eq!(log, JsValue::String("shown,hidden,TypeError".into())); + assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows"); +} + #[test] fn a_palette_list_change_after_its_items_changed_throws() { let seen = |index: f64| { diff --git a/docs/mcp.md b/docs/mcp.md index fef4f78655..941a86437c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2918,8 +2918,15 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s - A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, `window`, `show()` and `hide()`. A container also has `children`, `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` - (15 to start, 0 for a group) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, - `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + (15 to start, 0 for a group), `findElement(name)` and `update()`. The dialog has `defaultElement`, + `cancelElement`, `close([result])`, `hide()` and `update()`. `center()`, `layout.layout()` and + `layout.resize()` do nothing. +- `update()` on the showing dialog, or on a group or panel in it, runs without an error and does nothing more: a handler + runs to its end before the app draws again, so the dialog shows the handler's changes when the handler + returns, and a progress bar that a handler moves shows only its last value. On a window that is not showing + it throws an `Error`, and on a control that is not a container it throws a `TypeError`. It does not take the + person's clicks or changes: the dialog takes them once the running handler returns, so a loop that waits for + a Cancel button's `onClick` to set a flag does not see the click. `show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An @@ -2983,6 +2990,17 @@ the same controls, handlers and limits: A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. + `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and + closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop + a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). + Those events do not wait for runs of their own. In the app, an `update()` in the script's own code then + pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time + (VectorCraft's own interval); an `update()` within the same 16 ms does not pause the run, and the app draws + its changes at the next pause or when the run ends. An `update()` in a handler, in a callback of a built-in + function such as `forEach`, in a getter or in a conversion does not pause the run, since the run cannot + pause there, and on the web `update()` does not pause the run; the app draws those changes when the run ends. + On a palette that `hide()` hid, or that is not shown, it throws an `Error`; setting the palette's `visible` + does not change this. A handler's run reads and writes the files the person allowed the script that first showed the palette with Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8f4bb0095..9919c099c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1067,7 +1067,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_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`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going; a newer event for the same control takes a waiting one's place. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes, so a Cancel button can stop a loop, and in the script's own code in the app pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). From 331acb4a909b345594b1c64fd85fe9b00c5812b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:55:24 -0800 Subject: [PATCH 055/533] Scripts: a path moved between compound paths keeps its pixel alignment A path in a pixel-aligned compound path has no pixel alignment of its own. When node.move or move put it into another compound path, the new compound path did not become pixel-aligned, although it takes the paint the path was drawn with. It now becomes pixel-aligned when the path or the compound path it leaves was. The node.move params text and docs/mcp.md say so. --- crates/engine/src/cmd/layer.rs | 10 ++++++---- crates/engine/src/tests/script_dom.rs | 19 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 5f83152beb..9fe8d9e678 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -936,6 +936,7 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); let into = compound.map(|c| c.id); + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned); // A path that leaves a compound path for a layer or a group takes the compound path's paint and // pixel alignment, as Release Compound Path gives them to its paths. let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); @@ -954,12 +955,13 @@ fn move_node(s: &mut Session, p: &Value) -> Result { n.appearance = appearance; } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as - // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead. + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when + // the path was, or when the compound path it leaves was. if let Some(c) = into { - let mut aligned = false; + let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { m.appearance = vectorcraft_doc::Appearance::default().into(); - aligned = std::mem::take(&mut m.extras_mut().pixel_aligned); + aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned); if let NodeKind::Path { live, .. } = &mut m.kind { *live = None; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e3d0a46807..e8522ed334 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1764,6 +1764,25 @@ fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { assert_ne!(d.node(b).unwrap().appearance, red); } +/// A path that leaves a pixel-aligned compound path for another compound path makes that one +/// pixel-aligned, as it gives it the paint it was drawn with. +#[test] +fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(a).unwrap().extras().pixel_aligned); + let to = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(!s.active().unwrap().doc.node(to).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": a.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(to)); + assert!(d.node(to).unwrap().extras().pixel_aligned); + assert!(!d.node(a).unwrap().extras().pixel_aligned); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 5bbf805842..037d1a5433 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2740,7 +2740,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` makes an empty compound path in the same place (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a - compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. An empty + compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. The + compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. An empty compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths. From 2356ffe7475d85f079b6edfcb3f55f64da3386de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:55:12 -0800 Subject: [PATCH 056/533] Scripts: layers and groups give their own text frames Layer.textFrames and GroupItem.textFrames threw "not available yet". They now give a TextFrames collection with the members of the document's: length, [i], index, getByName, add, pointText, areaText, pathText and removeAll. It lists the type directly in the layer or group, topmost first, as the layer's other collections do, and new type goes on top of the layer's or group's contents whatever the current layer. A hidden or locked layer or group throws and changes nothing. text.create takes a parent: a shown, unlocked layer or group that the new type goes on top of, whatever the drawing mode. Area type and type on a path are moved there with node.move in the same step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/create.rs | 41 +++++++- crates/engine/src/script/dom/layers.rs | 29 +++++- crates/engine/src/script/dom/text.rs | 96 ++++++++++++++----- crates/engine/src/tests/script_text.rs | 87 +++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 7 files changed, 229 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..feb2505258 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -885,7 +885,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result { add_look(s, "Pen", path_kind(path, None), look, None) } +/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one. +fn text_parent(s: &Session, p: &Value) -> Result> { + const C: &str = "text.create"; + let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + Ok(Some(parent)) +} + +/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { + let id = s.edit("Type", |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, kind); + NewArt::plain(Appearance::default()).apply(d, &mut n); + super::object::align_new_object(d, &mut n); + n.bbox_angle = bbox_angle; + d.insert(Some(parent), usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + fn text_create(s: &mut Session, p: &Value) -> Result { + let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; super::paint::check_keep_model(p, "text.create")?; @@ -922,8 +953,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; + let made = match parent { + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, + None => { + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? + } + }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..b315aab2e0 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -65,6 +65,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Type (`TextFrame`), whose collection's other members are in `text.rs`. + Text, } impl Kind { @@ -73,6 +75,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Text => "TextFrames", } } @@ -81,6 +84,7 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Text => typename(n) == Some("TextFrame"), } } } @@ -845,6 +849,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +fn held_text(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Text) +} + +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + art_scope(h, d, Kind::Text.class()) +} + +/// The type objects directly in `container`, topmost first. +pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result>> { + art_list(h, st, Kind::Text, Some(container)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +915,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("textFrames", get(l, held_text)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1339,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("textFrames", get(l, held_text)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1348,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order)), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..556b0a113c 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1,4 +1,4 @@ -//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its //! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , @@ -7,6 +7,9 @@ //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`, +//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden +//! or locked layer or group throws. //! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so //! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves //! out to the whole character. One item of `characters` is one code point. @@ -1231,32 +1234,46 @@ fn frame_ids(h: &Host, st: &DocState) -> Rc> { ids } +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + super::layers::text_scope(h, arg(a, 0)) +} + fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "TextFrames") + Ok(frames_scope(h, a)?.0) +} + +/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those +/// directly in a layer or group, topmost first. +fn listed(h: &Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + match container { + None => Ok(frame_ids(h, st)), + Some(c) => super::layers::text_list(h, st, c), + } } fn frames_length(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) + let (doc, c) = frames_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(doc_ref(h, doc.uid)) + let (doc, c) = frames_scope(h, a)?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } fn frames_at(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = listed(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1284,29 +1301,40 @@ fn vertical_of(d: &Data) -> std::result::Result { } } -/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. -fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on +/// top of the contents of `container` when there is one. +fn point_text(h: &Host, (doc, container): (Doc, Option), anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let (_, r) = - on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical}); + if let Some(c) = container { + check_open(h, doc, c)?; + if let Some(o) = params.as_object_mut() { + o.insert("parent".into(), json!(c.0)); + } + } + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", ¶ms))?; new_ref(h, doc, result_id(&r)) } +/// The error for a layer or group that takes no new type. +const SHUT_CONTAINER: &str = "the layer or group is hidden or locked"; + /// `add()`: empty point type at the origin. fn frames_add(h: &Host, a: &[Data]) -> Answer { - point_text(h, frames_doc(h, a)?, None, false) + point_text(h, frames_scope(h, a)?, None, false) } /// `pointText(anchor, orientation?)`. fn frames_point_text(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let scope = frames_scope(h, a)?; let anchor = point(arg(a, 1), "anchor")?; - point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) + point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?) } -/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves +/// it on top of the contents of the collection's layer or group when there is one. fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, container) = frames_scope(h, a)?; if handle_of(arg(a, 1), "PathItem").is_none() { return Err(HostError::Type("textPath must be a PathItem".into())); } @@ -1321,8 +1349,23 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); - let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - new_ref(h, doc, result_id(&r)) + let Some(c) = container else { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + return new_ref(h, doc, result_id(&r)); + }; + check_open(h, doc, c)?; + let id = super::atomically(h, |h| { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + let id = result_id(&r).ok_or_else(|| HostError::Error("the command made no object".into()))?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?; + new_ref(h, doc, Some(id)) +} + +/// Refuses a hidden or locked layer or group as the place for new type. +fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> { + if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) } } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. @@ -1335,15 +1378,16 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or +/// locked one stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..a164ca396b 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -582,6 +582,93 @@ fn type_made_with_a_large_id_is_the_new_type() { assert_eq!(plain(&s, NodeId(big)), ""); } +/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a +/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type +/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current. +const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\ + function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\ + put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\ + var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\ + var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\ + var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\ + function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }"; + +#[test] +fn a_layers_and_a_groups_text_frames_list_only_their_own_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + &format!( + "{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\ + vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\ + vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\ + vc.log(d.textFrames.length);" + ), + ); + assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"])); + assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"])); + assert_eq!(out[2], json!(["front", "back", true])); + assert_eq!(out[3], json!(6)); + // Type inside the layer's group or sublayer is not the layer's own. + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');")); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn text_frames_of_a_layer_or_group_put_new_type_in_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap(); + let before = undo_steps(&s); + // The rectangle is in the first layer, which becomes `base`; `other` is current while the + // collections of `base` and `g` add type. + let out = log( + &mut s, + &format!( + "var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\ + var t = L0.textFrames.add(); t.name = 'added';\ + vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\ + var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\ + var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\ + g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);" + ), + ); + assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"])); + assert_eq!(out[1], json!(["g", "g-added"])); + assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"])); + // removeAll takes the group's own type and leaves the type inside its group. + assert_eq!(out[3], json!(["gg", "added,front,back"])); + assert_eq!(undo_steps(&s), before + 1); + // A locked layer and a hidden group take no new type, and the run changes nothing. + let before = undo_steps(&s); + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();")); + assert!(e.contains("hidden or locked"), "{e}"); + let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);")); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn text_create_puts_type_in_the_layer_or_group_it_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // A new layer is current, and a locked one takes no type. + let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap(); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = undo_steps(&s); + for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] { + assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before); + let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group))); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f08c8eb324..cc23a9d5c3 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -109,7 +109,7 @@ const INSIDE: &[(&str, &str)] = &[ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ - textFrames= typename visible visible= zOrder zOrderPosition", + typename visible visible= zOrder zOrderPosition", ), ("Layers.", "prototype"), ("Layers.prototype.", "add constructor getByName index length parent removeAll typename"), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "GroupItem.prototype.", "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ - rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + rasterItems rasterItems= symbolItems symbolItems= textFrames", ), ("GroupItems.", "prototype"), ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"), diff --git a/docs/mcp.md b/docs/mcp.md index 2de50317ee..63f947b35b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -620,7 +620,7 @@ change nothing; an omitted or null `id` keeps the default. Commands that need an `path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and `text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of -`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when +`node.move` and `text.create` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when `group` is left out or null, and reports a missing group only when both are left out. A command that needs a number (`x` of `shape.rectangle`, `pos` of `guide.add`, `index`, `x` and `y` of the `object.mesh.*` and `object.envelope.setMeshPoint` point commands, and the others like them) refuses a value that is not a number with @@ -2772,7 +2772,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + available yet. A `Layer` and a `GroupItem` have `textFrames` with the same members. VectorCraft's own rules for + them: they list the type objects directly in the layer or group, topmost first, and their `add()`, `pointText`, + `areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer. + Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the + drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or + locked layer or group throws an error and changes nothing. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05bd1ba664..76797eea1f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames`, and the `textFrames` of a layer or group, which list the type directly in it and put new type on top of its contents (VectorCraft's own rule), make point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/, with https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ for the layer's and group's `textFrames`, describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 62ce314f752fddd5de5994e09bfafddb36fa2928 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:03:22 -0800 Subject: [PATCH 057/533] New Document: test that the column count the rows show leaves a preset unchanged --- crates/ui-egui/src/dialogs/new_document.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 1bcfb52473..1f42df5ae1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -885,7 +885,7 @@ mod tests { let rows = DocSettings { artboards: 9, layout: ArtboardLayout::GridByColumn, columns: 2, rows: 4, ..DocSettings::default() }; let mut s = rows.clone(); set_columns(&mut s, 3); - assert_eq!((s.columns, s.rows), (3, 4), "3 is what the rows show"); + assert_eq!(s, rows, "3 is what the rows show"); set_columns(&mut s, 2); assert_eq!((s.layout, s.columns, s.rows), (ArtboardLayout::GridByColumn, 2, 0)); assert_eq!(s.grid_columns(), 2); From 368915aff4f5d55e35dc0b13e9db6ec7dc16b97e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:06:25 -0800 Subject: [PATCH 058/533] Recolor Artwork: a picked swatch the color group rewrites links nothing A row's picked global or spot swatch that OK's rewrite of the color group gives another color no longer links the row's art: the art keeps the row's new color, as other recolored art does. With Limit to Library, the dialog reads the library swatch of a row's new color before the row's own picked swatch, as recolor.apply does, so a process swatch there hides the Tint slider and the chip's tint. With the document's swatches as the library, the dialog reads them as they were before the preview. The library palette and the rewritten swatches are read once for all rows. --- crates/engine/src/cmd/recolor.rs | 6 +- crates/engine/src/tests/recolor.rs | 57 ++++++++ crates/ui-egui/src/dialogs/recolor.rs | 194 +++++++++++++++++++++----- crates/ui-egui/src/tests/recolor.rs | 101 ++++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 6 files changed, 325 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 381912c3ac..73d53945eb 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; a `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; with limitTo the library's swatch of the row's new color comes first; a global swatch of `group` that is rewritten with another color links nothing, and the row's art keeps the row's new color; a `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1622,7 +1622,9 @@ impl ColorMap { }; let i = out.rows.len(); let colors: Vec = r.from.iter().map(Match::color).collect(); - let link = links.get(n).cloned().flatten(); + // A global swatch of the rewritten group that takes another color links nothing, and the + // row recolors as it would with no swatch (its tint of the swatch left out). + let link = links.get(n).cloned().flatten().filter(|l| !(l.global && out.group.iter().any(|g| g.name == l.name && g.shown != l.color))); // Colors that can't link to the swatch take the row's tint of it too. let mapped = link.as_ref().filter(|l| l.global && l.tint < 1.0).map_or(to, |l| to.tinted(l.tint)); out.rows.push(RowMap::new(method, &colors, mapped).with_own_model(r.model.unwrap_or(model) != ModelRule::Keep)); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 2d11b9b1af..3c8da0536a 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -947,6 +947,63 @@ fn a_rows_swatch_with_a_finer_color_than_its_key_still_links() { assert!(close(fill(&s, id), ink), "the swatch's own color: {:?}", fill(&s, id)); } +/// A row's `swatch` that is a global swatch of the group being rewritten with another color links +/// nothing: the row's art takes the row's new color as with no swatch, in its own model and without +/// the row's tint of the swatch. A swatch of the group that keeps its color still links the art. +#[test] +fn a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Red Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Blue Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "G", "swatches": ["Red Ink", "Blue Ink"]})); + let red = rect(&mut s, json!("#ff0000")); + let blue = rect(&mut s, json!("#0000ff")); + select_all(&mut s); + let map = |first: &str| { + json!([ + {"from": ["#ff0000"], "to": first}, + {"from": ["#0000ff"], "to": "#ff0000", "swatch": {"name": "Red Ink"}}, + ]) + }; + run(&mut s, "recolor.apply", json!({"map": map("#00ff00"), "group": "G"})); + let ink = |s: &Session| s.doc().unwrap().doc.swatch("Red Ink").unwrap().paint.color().unwrap().to_hex(); + assert_eq!(ink(&s), "#00ff00", "the group is rewritten"); + assert_eq!(fill(&s, red).to_hex(), "#00ff00"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the blue art keeps its row's new color"); + assert_eq!(paint_link(&s, blue), None); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Also at a row tint of 0, where Red Ink's old and new colors both show white. + let mut zero = map("#00ff00"); + zero[1]["tint"] = json!(0); + run(&mut s, "recolor.apply", json!({"map": zero, "group": "G"})); + assert_eq!(paint_link(&s, blue), None, "at a tint of 0"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000", "the row's new color, as with no swatch"); + run(&mut s, "edit.undo", json!({})); + select_all(&mut s); + // Red Ink is rewritten with its own color, so the blue art links to it. + run(&mut s, "recolor.apply", json!({"map": map("#ff0000"), "group": "G"})); + assert_eq!(ink(&s), "#ff0000"); + assert_eq!(fill(&s, blue).to_hex(), "#ff0000"); + assert_eq!(paint_link(&s, blue).as_deref(), Some("Red Ink")); + run(&mut s, "edit.undo", json!({})); + // A CMYK swatch of a group rewritten with another color: the RGB art takes the row's new color + // as the row without the swatch gives it, in the art's own model. + run(&mut s, "swatch.new", json!({"name": "Cyan Ink", "color": "cmyk 100 0 0 0", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "C", "swatches": ["Cyan Ink"]})); + let result = |s: &mut Session, swatch: Value| { + select_all(s); + let map = json!([{"from": ["#0000ff"], "to": "cmyk 100 0 0 0", "swatch": swatch}]); + let r = run(s, "recolor.apply", json!({"map": map, "group": "C", "groupColors": ["#00ff00"]})); + let out = (fill(s, blue), paint_link(s, blue), r.get("note").cloned()); + run(s, "edit.undo", json!({})); + out + }; + let alone = result(&mut s, Value::Null); + assert!(alone.2.is_some(), "the RGB art keeps its model: {alone:?}"); + assert_eq!(result(&mut s, json!({"name": "Cyan Ink"})), alone); +} + /// A row's `swatch` from a loaded library links the art to it and adds it to the document's /// swatches; of two library swatches with the same name, the one with the row's new color is used, /// and rows that pick the same one link to one added swatch; of a process and a spot swatch with diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 1c32bb5ec1..b5b51a89ab 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1801,7 +1801,8 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut let mut clicked: Option = None; let mut pick: Option<(usize, bool)> = None; let mut limit_to: Option = None; - let shown: Vec = rows.iter().map(|r| new_shown(app, d, r)).collect(); + let links = RowLinks::new(app, d); + let shown: Vec = rows.iter().map(|r| new_shown(app, d, &links, r)).collect(); widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("recolor-rows").max_height(TABLE_H).show(ui, |ui| { ui.set_width(ui.available_width()); @@ -2061,12 +2062,12 @@ fn spot_tinted(app: &VectorcraftApp, c: Color, t: f32) -> Color { /// The color row `row`'s new color chip shows: what the art takes, at the row's tint (a spot color /// of the library as [`spot_tinted`] shows it). -fn new_shown(app: &VectorcraftApp, d: &Dialog, row: &Value) -> Color { +fn new_shown(app: &VectorcraftApp, d: &Dialog, links: &RowLinks, row: &Value) -> Color { let to = to_color(row).unwrap_or_default(); // Only a Lab spot color can show another color; the library lookup is skipped for the rest. - if matches!(to, Color::Lab { .. }) && d.bool("__art") && (spot_of(app, d, &to).is_some() || own_spot(app, d, row, &to).is_some()) { + if matches!(to, Color::Lab { .. }) && d.bool("__art") && linked_spot(app, d, links, row, &to).is_some() { spot_tinted(app, to, row_tint(row)) - } else if row_tint(row) < 1.0 && tint_applies(app, d, row, &to) { + } else if row_tint(row) < 1.0 && tint_applies(app, d, links, row, &to) { to.tinted(row_tint(row)) } else { // The swatch the tint was for no longer links the art, which takes the full color. @@ -2079,26 +2080,108 @@ fn mode_id(m: Mode) -> String { serde_json::to_value(m).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default() } -/// The name of the library swatch (Limit to Library) that `recolor.apply` gives new color `c`, when -/// it is a spot color: the first swatch of the library color nearest `c`. -fn spot_of(app: &VectorcraftApp, d: &Dialog, c: &Color) -> Option { - let lib = d.str("limitTo"); - if lib.is_empty() { - return None; +/// What decides how `recolor.apply` links the art of the rows to swatches, read once for all rows: +/// Limit to Library's palette and color swatches, and the names of the color group's global swatches +/// that OK's rewrite gives another color ([`rewritten_to_another`]). +struct RowLinks { + library: Option<(vectorcraft_color::recolor::Palette, Vec)>, + rewritten: Vec, +} + +impl RowLinks { + fn new(app: &VectorcraftApp, d: &Dialog) -> Self { + let lib = d.str("limitTo"); + let library = if lib.is_empty() { None } else { limit_palette_before_preview(app, &lib).zip(limit_swatches(app, &lib)) }; + let rewritten = rewritten_to_another(app, d, library.as_ref().map(|(palette, _)| palette)); + Self { library, rewritten } + } + + /// The library swatch (Limit to Library) that `recolor.apply` gives new color `c`: the first + /// swatch of the library color nearest `c`. + fn library_swatch(&self, c: &Color) -> Option<&vectorcraft_color::swatch::Swatch> { + let (palette, swatches) = self.library.as_ref()?; + let near = palette.nearest(*c); + swatches.iter().find(|w| w.paint.color() == Some(near)) + } +} + +/// Limit to Library's palette for `lib`, as [`swatchlib::limit_palette`] gives it, with the +/// document's swatches read as they were before the preview, which `recolor.apply` runs on. +fn limit_palette_before_preview(app: &VectorcraftApp, lib: &str) -> Option { + if lib != swatchlib::DOCUMENT_SWATCHES { + return swatchlib::limit_palette(&app.session, lib); + } + let st = app.session.active()?; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + Some(vectorcraft_color::recolor::Palette::new(doc.swatches_iter().filter_map(|w| w.paint.color()))) +} + +/// The color swatches of Limit to Library's `lib`, as [`swatchlib::library_swatches`] gives them, +/// with the document's swatches read as they were before the preview. +fn limit_swatches(app: &VectorcraftApp, lib: &str) -> Option> { + if lib != swatchlib::DOCUMENT_SWATCHES { + return swatchlib::library_swatches(&app.session, lib); + } + let st = app.session.active()?; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + Some(doc.swatches_iter().filter(|w| matches!(w.paint, vectorcraft_color::Paint::Solid { swatch: None, .. })).cloned().collect()) +} + +/// The name of the spot swatch the art of `row`, with new color `c`, links to: Limit to Library's +/// swatch of that color when the library has one (a process swatch there links nothing, and the +/// row's own `swatch` is not used, as in `recolor.apply`), else the row's own spot swatch. +fn linked_spot(app: &VectorcraftApp, d: &Dialog, links: &RowLinks, row: &Value, c: &Color) -> Option { + match links.library_swatch(c) { + Some(w) => (w.spot && !link_rewritten(app, links, w)).then(|| w.name.clone()), + None => own_spot(app, d, links, row, c), } - let near = swatchlib::limit_palette(&app.session, &lib)?.nearest(*c); - swatchlib::library_swatches(&app.session, &lib)?.into_iter().find(|w| w.paint.color() == Some(near)).filter(|w| w.spot).map(|w| w.name) } /// The name of the spot swatch `row`'s new color `c` was picked from (its `swatch`), while that -/// swatch has color `c` and no Global Adjust applies without Limit to Library, as `recolor.apply` -/// reads it. -fn own_spot(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> Option { +/// swatch has color `c`, no Global Adjust applies without Limit to Library and OK's rewrite of the +/// color group gives it no other color ([`link_rewritten`]), as `recolor.apply` reads it. +fn own_spot(app: &VectorcraftApp, d: &Dialog, links: &RowLinks, row: &Value, c: &Color) -> Option { if d.str("limitTo").is_empty() && !global_adjust(adjust_values(d)).is_identity() { return None; } - let (name, _) = swatch_ref(row)?; - row_swatch(app, row, c).filter(|spot| *spot).map(|_| name.to_string()) + row_swatch(app, row, c).filter(|w| w.spot && !link_rewritten(app, links, w)).map(|w| w.name) +} + +/// Whether the art `recolor.apply` links to swatch `w` (a library's or the document's) links nothing +/// because OK's rewrite of the color group gives it another color: `w` joins the document under its +/// own name only when the document's swatch of that name has its paint, Global and spot, and is +/// added under a free name otherwise, which no swatch of the group has. +fn link_rewritten(app: &VectorcraftApp, links: &RowLinks, w: &vectorcraft_color::swatch::Swatch) -> bool { + if !links.rewritten.contains(&w.name) { + return false; + } + let Some(st) = app.session.active() else { return false }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + doc.swatch(&w.name).is_some_and(|x| x.paint == w.paint && x.global == w.global && x.spot == w.spot) +} + +/// The names of the color group's global swatches that OK's rewrite (`groupColors` of +/// [`apply_params`]) gives a color other than their own, as `recolor.apply` reads it: each color +/// takes the Global Adjust and, with Limit to Library, the library's nearest color (`palette`); +/// `"keep"` and a removed color give none. Art whose row picked such a swatch links nothing. +fn rewritten_to_another(app: &VectorcraftApp, d: &Dialog, palette: Option<&vectorcraft_color::recolor::Palette>) -> Vec { + let p = apply_params(d); + let (Some(group), Some(colors)) = (p["group"].as_str(), p["groupColors"].as_array()) else { return Vec::new() }; + let Some(st) = app.session.active() else { return Vec::new() }; + let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); + let adjust = global_adjust(adjust_values(d)); + let Some(g) = doc.swatch_groups.iter().find(|g| g.name == group) else { return Vec::new() }; + g.swatches + .iter() + .filter_map(|w| Some((w, w.paint.color()?))) + .zip(colors) + .filter(|((w, own), v)| { + let new = color_value(v).filter(|_| v.as_str() != Some("keep")).map(|c| adjust.apply(c)); + let new = new.map(|c| palette.map_or(c, |pl| pl.nearest(c))); + w.global && !w.is_reserved() && new.is_some_and(|c| doc.linked_color(c, w.spot) != doc.linked_color(*own, w.spot)) + }) + .map(|((w, _), _)| w.name.clone()) + .collect() } /// The name and library key of `row`'s `swatch` when it is `{name, library?}` with a name, as @@ -2113,12 +2196,11 @@ fn swatch_ref(row: &Value) -> Option<(&str, &str)> { Some((name, library)) } -/// Whether the swatch `row`'s `swatch` names, with color `c` (as a color key), is a spot color, -/// when it is a global or spot swatch; `None` when it is a process swatch or not there (deleted -/// since the pick). Of several swatches with that name, the first with that color counts, as -/// `recolor.apply` finds it. The document's swatches are read as they were before the preview, -/// which `recolor.apply` runs on. -fn row_swatch(app: &VectorcraftApp, row: &Value, c: &Color) -> Option { +/// The swatch `row`'s `swatch` names, with color `c` (as a color key), when it is a global or spot +/// swatch; `None` when it is a process swatch or not there (deleted since the pick). Of several +/// swatches with that name, the first with that color counts, as `recolor.apply` finds it. The +/// document's swatches are read as they were before the preview, which `recolor.apply` runs on. +fn row_swatch(app: &VectorcraftApp, row: &Value, c: &Color) -> Option { let (name, lib) = swatch_ref(row)?; let fits = |s: &&vectorcraft_color::swatch::Swatch| { s.name == name @@ -2128,19 +2210,25 @@ fn row_swatch(app: &VectorcraftApp, row: &Value, c: &Color) -> Option { let found = if lib == swatchlib::DOCUMENT_SWATCHES { let st = app.session.active()?; let doc = st.interaction.as_ref().map_or(&st.doc, |it| &it.doc); - doc.swatches_iter().find(fits).map(|s| (s.global || s.spot, s.spot)) + doc.swatches_iter().find(fits).cloned() } else { let (_, l) = swatchlib::library(&app.session, lib)?; - l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).find(fits).map(|s| (s.global || s.spot, s.spot)) + l.swatches.iter().chain(l.groups.iter().flat_map(|g| g.swatches.iter())).find(fits).cloned() }; - found.filter(|(links, _)| *links).map(|(_, spot)| spot) + found.filter(|s| s.global || s.spot) } -/// Whether the new color chip shows `row`'s tint: with Limit to Library, when the row has no -/// `swatch`, or when its `swatch` links the art ([`row_swatch`], with no Global Adjust). A row whose -/// `swatch` links nothing recolors its art with the full color. -fn tint_applies(app: &VectorcraftApp, d: &Dialog, row: &Value, c: &Color) -> bool { - !d.str("limitTo").is_empty() || swatch_ref(row).is_none() || (global_adjust(adjust_values(d)).is_identity() && row_swatch(app, row, c).is_some()) +/// Whether the new color chip shows `row`'s tint: with Limit to Library unless the library's swatch +/// of `c` is one OK's rewrite of the color group gives another color ([`link_rewritten`]), when the +/// row has no `swatch`, or when its `swatch` links the art ([`row_swatch`], with no Global Adjust, +/// and not [`link_rewritten`]). A row whose `swatch` links nothing recolors its art with the full +/// color. +fn tint_applies(app: &VectorcraftApp, d: &Dialog, links: &RowLinks, row: &Value, c: &Color) -> bool { + if !d.str("limitTo").is_empty() { + return links.library_swatch(c).is_none_or(|w| !link_rewritten(app, links, w)); + } + swatch_ref(row) + .is_none_or(|_| global_adjust(adjust_values(d)).is_identity() && row_swatch(app, row, c).is_some_and(|w| !link_rewritten(app, links, &w))) } /// The mode the sliders show new color `c` in, `None` for Tint: the mode picked in the menu, else @@ -2188,7 +2276,7 @@ impl SliderTarget { let row = row.filter(|i| *i < rows.len()); let color = row.and_then(|i| to_color(&rows[i])); // A row tint acts only on art, so without art a spot color shows the process modes. - let spot = color.filter(|_| d.bool("__art")).and_then(|c| spot_of(app, d, &c).or_else(|| own_spot(app, d, &rows[row?], &c))); + let spot = color.filter(|_| d.bool("__art")).and_then(|c| linked_spot(app, d, &RowLinks::new(app, d), &rows[row?], &c)); Self { row, color, spot } } @@ -3647,7 +3735,7 @@ mod tests { rs[0]["tint"] = json!(40.0); picked.fields.insert("rows".into(), Value::Array(rs)); let rs = super::rows(&picked); - let tinted = new_shown(&app, &picked, &rs[0]); + let tinted = new_shown(&app, &picked, &RowLinks::new(&app, &picked), &rs[0]); assert!(tinted != ink && tinted.to_rgb()[1] > ink.to_rgb()[1], "the chip at 40%: {tinted:?}"); // A process swatch of the same color picked for the row. let process = with_new_swatch(&app, picked.clone(), 0, ink, None); @@ -3658,11 +3746,11 @@ mod tests { app.session.begin_interaction("Swatch Options").unwrap(); app.session.preview("swatch.edit", &json!({"name": "Ink", "color": "cmyk 100 0 0 0"})).unwrap(); assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot.as_deref(), Some("Ink"), "the swatch as it was before the preview"); - assert_eq!(new_shown(&app, &picked, &rs[0]), tinted); + assert_eq!(new_shown(&app, &picked, &RowLinks::new(&app, &picked), &rs[0]), tinted); let _ = app.session.cancel_interaction(); app.run("swatch.delete", json!({"names": ["Ink"]})).unwrap(); assert_eq!(SliderTarget::at(&app, &picked, &rs, Some(0)).spot, None, "no Tint slider"); - assert_eq!(new_shown(&app, &picked, &rs[0]), ink, "the full color the art takes"); + assert_eq!(new_shown(&app, &picked, &RowLinks::new(&app, &picked), &rs[0]), ink, "the full color the art takes"); let r = app.session.execute(CMD, &apply_params(&picked)).unwrap(); assert_eq!(r["swatchesNotFound"], json!(["Ink"]), "{r}"); let doc = &app.session.doc().unwrap().doc; @@ -3676,6 +3764,40 @@ mod tests { } } + /// A row picked from a spot swatch of the color group shows Tint and its tint on the chip while + /// OK leaves the swatch its color, and no Tint and the full color once OK gives the swatch + /// another color, as `recolor.apply` then gives the art. + #[test] + fn a_picked_swatch_the_group_rewrites_shows_the_full_color() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Inks", "swatches": ["Ink"]})).unwrap(); + for c in ["cmyk 0 100 0 0", "#808080"] { + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": c})).unwrap(); + app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Inks"})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let ink = Color::cmyk(0.0, 1.0, 0.0, 0.0); + let rows = |first: &str| { + json!([ + {"from": ["cmyk 0 100 0 0"], "to": first}, + {"from": ["rgb 128 128 128"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": "document"}, "tint": 40.0}, + ]) + }; + d.fields.insert("rows".into(), rows("cmyk 0 100 0 0")); + let rs = super::rows(&d); + assert_eq!(SliderTarget::at(&app, &d, &rs, Some(1)).spot.as_deref(), Some("Ink"), "Ink keeps its color"); + assert_ne!(new_shown(&app, &d, &RowLinks::new(&app, &d), &rs[1]), ink, "the chip at 40%"); + d.fields.insert("rows".into(), rows("rgb 0 255 0")); + let rs = super::rows(&d); + assert_eq!(SliderTarget::at(&app, &d, &rs, Some(1)).spot, None, "no Tint slider once Ink takes green"); + assert_eq!(new_shown(&app, &d, &RowLinks::new(&app, &d), &rs[1]), ink, "the full color the art takes"); + } + /// With the Spot Colors options on CMYK values, a row whose new color is a Lab spot color of the /// library shows the art's color at its tint: the working-CMYK equivalent with its inks scaled. #[test] @@ -3701,7 +3823,7 @@ mod tests { assert!(matches!(c, Color::Lab { .. }), "{c:?}"); let cmyk = app.session.doc().unwrap().doc.linked_color(c, true); assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); - assert_eq!(new_shown(&app, &d, &rs[0]), cmyk.tinted(0.5)); + assert_eq!(new_shown(&app, &d, &RowLinks::new(&app, &d), &rs[0]), cmyk.tinted(0.5)); } /// Runs one frame of the open dialog at `time` and returns row `i`'s new color chip, when the diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 8823e1a0fa..6086f0de26 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -460,6 +460,107 @@ fn a_process_swatch_before_a_spot_one_of_its_color_shows_no_tint() { assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); } +/// A row picked from a spot swatch shows Tint, but not with Limit to Library while the library's +/// swatch of that color is a process color: `recolor.apply` gives the art the library's swatch, +/// which links nothing. +#[test] +fn a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch() { + let mut app = app(); + let lib = library_of(&mut app, &[json!({"name": "Mix Process", "color": {"c": 0, "m": 1, "y": 0, "k": 0}})]); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})).unwrap(); + art(&mut app, &["cmyk 0 100 0 0"]); + let mut h = assign_harness(app, json!({"library": lib})); + let mut rows = field(h.state(), "rows"); + assert_eq!(rows[0]["to"], json!("cmyk 0 100 0 0"), "{rows}"); + rows[0]["swatch"] = json!({"name": "Ink", "library": "document"}); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "no Tint for the library's process swatch"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); +} + +/// A row picked from a spot swatch of the color group being edited shows Tint while OK leaves the +/// swatch its color, and not once another row gives the swatch a new color: `recolor.apply` then +/// links the row's art to nothing. +#[test] +fn a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 100 0 0", "spot": true})).unwrap(); + app.run("swatch.new", json!({"name": "Other", "color": "cmyk 100 0 0 0", "spot": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Inks", "swatches": ["Ink", "Other"]})).unwrap(); + art(&mut app, &["cmyk 0 100 0 0", "cmyk 100 0 0 0"]); + let mut h = assign_harness(app, json!({"group": "Inks"})); + let rows = field(h.state(), "rows"); + let at = |k: &str| rows.as_array().unwrap().iter().position(|r| r["from"].as_array().is_some_and(|f| f.contains(&json!(k)))).unwrap(); + let (magenta, cyan) = (at("cmyk 0 100 0 0"), at("cmyk 100 0 0 0")); + let mut rows = rows.clone(); + rows[cyan]["to"] = json!("cmyk 0 100 0 0"); + rows[cyan]["swatch"] = json!({"name": "Ink", "library": "document"}); + set(h.state_mut(), "rows", rows.clone()); + set(h.state_mut(), "__sel", json!([cyan])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "Ink keeps its color: Tint"); + rows[magenta]["to"] = json!("rgb 0 255 0"); + set(h.state_mut(), "rows", rows); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "Ink takes green: no Tint"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); +} + +/// With Limit to Library on the document's swatches, a row whose new color is a spot swatch of the +/// color group being edited shows Tint while OK leaves the swatch its color, and not once another +/// row gives the swatch a new color: `recolor.apply` then links the row's art to nothing. +#[test] +fn a_library_spot_swatch_rewritten_with_another_color_shows_no_tint() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 70 0 20", "spot": true})).unwrap(); + app.run("swatch.new", json!({"name": "Other", "color": "cmyk 70 0 0 20", "spot": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Inks", "swatches": ["Ink", "Other"]})).unwrap(); + art(&mut app, &["cmyk 0 70 0 20", "cmyk 70 0 0 20"]); + let mut h = assign_harness(app, json!({"group": "Inks"})); + set(h.state_mut(), "limitTo", json!("document")); + // The dialog reduces the art again for the library, which clears the selection. + h.run_steps(2); + let rows = field(h.state(), "rows"); + let at = |k: &str| rows.as_array().unwrap().iter().position(|r| r["from"].as_array().is_some_and(|f| f.contains(&json!(k)))).unwrap(); + let (magenta, cyan) = (at("cmyk 0 70 0 20"), at("cmyk 70 0 0 20")); + let mut rows = rows.clone(); + rows[cyan]["to"] = json!("cmyk 0 70 0 20"); + set(h.state_mut(), "rows", rows.clone()); + set(h.state_mut(), "__sel", json!([cyan])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "Ink keeps its color: Tint"); + rows[magenta]["to"] = json!("cmyk 70 0 0 20"); + set(h.state_mut(), "rows", rows); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "Ink takes cyan: no Tint"); +} + +/// A row picked from a library's spot swatch keeps Tint when the color group being edited gives a +/// different document swatch of the same name another color: `recolor.apply` adds the library's +/// swatch under a free name and links the row's art to it. +#[test] +fn a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint() { + let mut app = app(); + let lib = library_of(&mut app, &[json!({"name": "Ink", "color": {"c": 0, "m": 1, "y": 0, "k": 0}, "spot": true})]); + app.run("swatch.new", json!({"name": "Ink", "color": "cmyk 0 0 100 0", "spot": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "Inks", "swatches": ["Ink"]})).unwrap(); + art(&mut app, &["cmyk 0 0 100 0", "cmyk 0 100 0 0"]); + let mut h = assign_harness(app, json!({"group": "Inks"})); + let rows = field(h.state(), "rows"); + let at = |k: &str| rows.as_array().unwrap().iter().position(|r| r["from"].as_array().is_some_and(|f| f.contains(&json!(k)))).unwrap(); + let (yellow, magenta) = (at("cmyk 0 0 100 0"), at("cmyk 0 100 0 0")); + let mut rows = rows.clone(); + rows[yellow]["to"] = json!("rgb 0 255 0"); + rows[magenta]["to"] = json!("cmyk 0 100 0 0"); + rows[magenta]["swatch"] = json!({"name": "Ink", "library": lib}); + set(h.state_mut(), "rows", rows); + set(h.state_mut(), "__sel", json!([magenta])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "the library's Ink still links: Tint"); +} + /// Opened on a color group without art, a row whose new color is a spot color of the library shows /// the process modes and no Tint: OK saves only the group's colors, so a tint would be lost. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9bba7e67c1..2050ba1d32 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5573,7 +5573,10 @@ which round) is used. While it is a global or spot swatch and there is no Global row's art takes the swatch as it would with `limitTo`, linked to it at its tints (and its `tint` applies), and a library swatch joins the document's swatches. A process swatch, or a swatch or library that is not there (such as a swatch deleted after it was picked), links nothing, and the row recolors as its new color alone does; the result's -`swatchesNotFound` lists the names of the swatches that are not there. A row whose new color is +`swatchesNotFound` lists the names of the swatches that are not there. With `limitTo`, the library's swatch of the +row's new color is used instead when the library has one, so a process swatch there links nothing. A global swatch of +`group` that the group's rewrite gives another color links nothing either: the row's art keeps the row's new color, as +other recolored art does. A row whose new color is picked from a global or spot swatch in the Color Picker's swatch list in Recolor Artwork carries it, so with no Limit to Library the art still takes the swatch picked; the dialog drops a row's `swatch` when the row's new color changes. A `swatch` that is not `{name, library?}` is an error. `recolor.randomize` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cb88bca758..c026dbb243 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2033,7 +2033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list stays that swatch, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider` and `a_picked_swatch_that_is_gone_links_nothing` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list stays that swatch, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From 9b8461feb590e6ebb348379083f0f292c1f9bba4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:26:20 -0800 Subject: [PATCH 059/533] Scripts: exportFile writes DXF with ExportOptionsAutoCAD - Document.exportFile with ExportType.AutoCAD takes an ExportOptionsAutoCAD object and writes a DXF file through document.export, adding .dxf unless the name ends with it. ExportType.AUTOCAD is the same value as ExportType.AutoCAD. - The options map to the DXF writer: version (AutoCADRelease13, 14, 15, 18, 21 and 24 as the R13, R14, 2000, 2004, 2007 and 2010 formats), unit, unitScaleRatio (drawing units for one unit, more than 0 and at most 1000), colors, rasterFormat, exportOption, alterPathsForAppearance, convertTextToOutlines, exportSelectedArtOnly and scaleLineweights. - An option the object leaves out takes the default the help page gives. colors, rasterFormat, unit and unitScaleRatio have none there and default to true colors, PNG, millimeters and 1. - AutoCADExportFileFormat.DWG, the help page's default, throws an error that says DWG is not available, and nothing is written. - New enumerations: AutoCADColors, AutoCADCompatibility, AutoCADExportFileFormat, AutoCADExportOption, AutoCADRasterFormat and AutoCADUnit. https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/save_open.rs | 142 +++++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 83 ++++++++++++ docs/mcp.md | 17 ++- docs/target-app-parity.md | 1 + 5 files changed, 238 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..01f4522700 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1808,7 +1808,9 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { - let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); + items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); realm.define_host_object(name, items)?; } let l = link; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f54c2f3f0b..e3227da608 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -7,7 +7,8 @@ //! , //! , //! , -//! and +//! , +//! and //! describe. //! //! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's @@ -25,6 +26,12 @@ //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. //! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, //! and when one of those files may not be written, none of them is. +//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF +//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not +//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page +//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to +//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one +//! `unit`, more than 0 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -63,6 +70,15 @@ pub(in crate::script) struct State { /// The enumerations these members use, as `dom`'s are made. pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]), + ( + "AutoCADCompatibility", + &["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"], + ), + ("AutoCADExportFileFormat", &["DXF", "DWG"]), + ("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]), + ("AutoCADRasterFormat", &["PNG", "JPEG"]), + ("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]), ( "Compatibility", &[ @@ -88,6 +104,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), ]; +/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the +/// same value as `enumeration.member`. +pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")]; + const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; @@ -482,9 +502,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> { ] } +/// The members of the enumeration `name` in [`ENUMS`]. +fn members_of(name: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m) +} + +fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsAutoCAD.{name}"); + let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what); + match name { + "alterPathsForAppearance" => { + p.insert("alterPaths".into(), json!(boolean(d, &what)?)); + } + "colors" => { + let colors = match pick("AutoCADColors")? { + "Max8Colors" => json!(8), + "Max16Colors" => json!(16), + "Max256Colors" => json!(256), + _ => json!("true"), + }; + p.insert("colors".into(), colors); + } + "convertTextToOutlines" => { + p.insert("outlineText".into(), json!(boolean(d, &what)?)); + } + "exportFileFormat" => { + if pick("AutoCADExportFileFormat")? == "DWG" { + return Err(HostError::Error( + "AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(), + )); + } + } + "exportOption" => { + let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" }; + p.insert("preserve".into(), json!(preserve)); + } + "exportSelectedArtOnly" => { + p.insert("selectedOnly".into(), json!(boolean(d, &what)?)); + } + "rasterFormat" => { + p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" })); + } + "scaleLineweights" => { + p.insert("scaleLineweights".into(), json!(boolean(d, &what)?)); + } + "unit" => { + let unit = match pick("AutoCADUnit")? { + "Points" => "pt", + "Picas" => "pc", + "Inches" => "in", + "Millimeters" => "mm", + "Centimeters" => "cm", + _ => "px", + }; + p.insert("unit".into(), json!(unit)); + } + "unitScaleRatio" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(n > 0.0 && n <= 1000.0) { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + } + p.insert("scale".into(), json!(n)); + } + "version" => { + let version = match pick("AutoCADCompatibility")? { + "AutoCADRelease13" => "R13", + "AutoCADRelease14" => "R14", + "AutoCADRelease15" => "2000", + "AutoCADRelease18" => "2004", + "AutoCADRelease21" => "2007", + _ => "2010", + }; + p.insert("version".into(), json!(version)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn autocad_starts() -> Vec<(&'static str, Data)> { + vec![ + ("alterPathsForAppearance", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("exportFileFormat", text("AutoCADExportFileFormat.DWG")), + ("exportOption", text("AutoCADExportOption.MaximizeEditability")), + ("exportSelectedArtOnly", Data::Bool(false)), + ("scaleLineweights", Data::Bool(false)), + ("version", text("AutoCADCompatibility.AutoCADRelease24")), + ] +} + +/// The options object `d` with the options of a new `class` object it leaves out, or holds as +/// `undefined`, added. +fn with_starts(class: &OptionClass, d: &Data) -> Data { + let Data::Object(items) = d else { return d.clone() }; + let mut items = items.clone(); + for (k, v) in (class.starts)() { + match items.iter_mut().find(|(n, _)| n == k) { + Some((_, held)) if matches!(held, Data::Undefined) => *held = v, + Some(_) => {} + None => items.push((k.to_string(), v)), + } + } + Data::Object(items) +} + const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; +const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts }; /// An `ExportType`: the format `document.export` writes, the extensions a file name may already /// end with (the first is added), and its option class (`None`: no options are taken). @@ -495,9 +624,9 @@ struct ExportKind { } fn export_kind(d: &Data) -> std::result::Result { - let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); let raster = |format, extensions| ExportKind { format, extensions, options: None }; - Ok(match member(d, "ExportType", all, "exportType")? { + Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? { + "AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) }, "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, @@ -631,6 +760,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => Map::new(), }, Some(o) => match kind.options { + // An AutoCAD option left out takes its help page's default, not the DXF writer's. + Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?, Some(class) => options_params(class, o)?, None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, @@ -642,7 +773,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - if kind.format != "svg" { + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } let format = if svgz { "svgz" } else { kind.format }; @@ -740,7 +872,7 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its /// help page gives for the options mapped here. pub(super) fn classes(link: &Link) -> Vec { - let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]); all.map(|c| { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 126c7c3947..9419b65f76 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -153,6 +153,60 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() { let _ = std::fs::remove_dir_all(base); } +/// The value of the DXF header variable `name` (the group after its name). +fn dxf_header(dxf: &str, name: &str) -> Option { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string()) +} + +/// The largest x coordinate (group code 10) in the entities of a DXF. +fn dxf_widest(dxf: &str) -> f64 { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The section's name is a value; the group codes start on the line after it. + let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); + lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) +} + +/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and +/// DWG, the help page's default format, throws without writing a file. +#[test] +fn an_autocad_export_writes_a_dxf_with_its_options() { + let base = folder("autocad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ + try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ + o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ + d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" + ), + ); + assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true])); + assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]); + assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing"); + let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap(); + let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap(); + assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); + assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); + assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); + assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + for name in ["c.dxf", "u.dxf"] { + let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); + assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + } + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -518,6 +572,35 @@ fn bad_arguments_are_refused_with_an_error() { "from 0 to 100", ), (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"), + ( + format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"), + "DWG is not available", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "at most 1000", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADCompatibility", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADColors", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD has no option unitScale", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 5dd133dc00..8aeda63840 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2709,7 +2709,18 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and - `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written + `ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/) + and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version` + (`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`, + `unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`, + `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. + An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and + `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an + AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, + `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` + hold the members the scripting constants page lists. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, @@ -2722,11 +2733,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot files a command reads or writes besides the one named, such as an SVG's linked files, are read and written only where the script's folders allow. `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the - format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws - an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + an error that says it is not available yet, as does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..a407294012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,6 +1027,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 52b43e90f08de968117463a91b376b69c18a9ac4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:57:46 -0800 Subject: [PATCH 060/533] Scripts: an AutoCAD export to a DXF before 2004 does not take true color AutoCADRelease13, 14 and 15 write DXF formats that hold no true color. With them, exportFile takes 256 indexed colors when the options leave colors out, and AutoCADColors.TrueColors throws an error instead of writing indexed colors without telling the script. Docs: docs/mcp.md. --- crates/engine/src/script/dom/save_open.rs | 13 +++++++++++++ crates/engine/src/tests/script_save_open.rs | 6 ++++++ docs/mcp.md | 2 ++ 3 files changed, 21 insertions(+) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index e3227da608..6382fabb54 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -766,6 +766,19 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; + // A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed + // colors, and `AutoCADColors.TrueColors` with it throws. + if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { + match p.get("colors") { + None => { + p.insert("colors".into(), json!(256)); + } + Some(c) if c.as_str() == Some("true") => { + return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into())); + } + Some(_) => {} + } + } let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9419b65f76..fb304236ec 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -601,6 +601,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "ExportOptionsAutoCAD has no option unitScale", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "TrueColors needs AutoCADRelease18", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 8aeda63840..06a97cf28e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2717,6 +2717,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and + `AutoCADColors.TrueColors` throws an error. `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` From e654a3d5b99c695e2343a4523448496d7f35fed6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:42:05 -0800 Subject: [PATCH 061/533] Scripts: an AutoCAD export in picas writes a DXF ExportOptionsAutoCAD.unit = AutoCADUnit.Picas sent a unit name the DXF writer does not read, so exportFile threw instead of writing the file. Each AutoCADUnit member now goes to the writer by its unit's key. The test also checks that an export without artBoardClipping has its origin at the visible art's bounds. --- crates/engine/src/script/dom/save_open.rs | 15 ++++++------ crates/engine/src/tests/script_save_open.rs | 27 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6382fabb54..cfd67ab0bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -48,6 +48,7 @@ use std::cell::Cell; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ @@ -548,14 +549,14 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: } "unit" => { let unit = match pick("AutoCADUnit")? { - "Points" => "pt", - "Picas" => "pc", - "Inches" => "in", - "Millimeters" => "mm", - "Centimeters" => "cm", - _ => "px", + "Points" => Unit::Points, + "Picas" => Unit::Picas, + "Inches" => Unit::Inches, + "Millimeters" => Unit::Millimeters, + "Centimeters" => Unit::Centimeters, + _ => Unit::Pixels, }; - p.insert("unit".into(), json!(unit)); + p.insert("unit".into(), json!(unit.key())); } "unitScaleRatio" => { let n = match d { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index fb304236ec..76b4d66c75 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -161,10 +161,30 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) +} + +/// The smallest x coordinate (group code 10) in the entities of a DXF. +fn dxf_leftmost(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) +} + +/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its +/// elevation point, so hatches are left out. +fn dxf_xs(dxf: &str) -> Vec { let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); // The section's name is a value; the group codes start on the line after it. let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); - lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) + let mut entity = ""; + let mut xs = Vec::new(); + for p in lines[start..].chunks(2).filter(|p| p.len() == 2) { + match p[0] { + "0" => entity = p[1], + "10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::().ok()), + _ => {} + } + } + xs } /// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and @@ -187,6 +207,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" ), @@ -203,7 +224,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. + assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } + let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); + assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); let _ = std::fs::remove_dir_all(base); } From 037a01b5210e2add20ed06eb608510faf31f0a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:49:29 -0800 Subject: [PATCH 062/533] Scripts: update() checks each waiting palette event against the palette as handlers left it update() takes the events that wait for the run's palettes one at a time. Before each one, the host now gets every palette's controls as the script and the earlier handlers left them, as at the end of a run, so a click on a control that an earlier handler disabled, hid or removed runs no handler and is dropped. The new host function palettePending says whether an event still waits. An update() that a getter or a handler calls while events are being taken takes none itself; the update() already taking them goes on with the next one, instead of calling itself until a limit stops the run. Docs: docs/mcp.md palette bullet. --- crates/engine/src/script/palettes.rs | 6 ++++ crates/engine/src/script/scriptui.rs | 8 +++++ crates/engine/src/tests/script_palettes.rs | 26 ++++++++++++++++ crates/js/src/scriptui.rs | 34 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 36 +++++++++++++++++++--- docs/mcp.md | 4 ++- 6 files changed, 107 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 68c84e3f0d..b06dae36fa 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -240,6 +240,12 @@ impl Palettes { pub(crate) fn take_for(&mut self, engine: &str) -> Option { self.next_of(engine).map(|(_, q)| q) } + + /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] + /// would then check and take. + pub(crate) fn waits_for(&self, engine: &str) -> bool { + self.waiting.iter().any(|q| self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + } } /// `name` in a `#targetengine` line, quoted with a quote it does not hold. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index e460408a51..dc4bbf3bc5 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -714,6 +714,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("paletteClose".into(), function(link, palette_close)), ("paletteEvent".into(), function(link, palette_event)), ("paletteTake".into(), function(link, palette_take)), + ("palettePending".into(), function(link, palette_pending)), ("paletteDraw".into(), function(link, palette_draw)), ]) } @@ -776,6 +777,13 @@ fn palette_take(host: &Host, _: &[Data]) -> Result { Ok(taken.map_or(Data::Null, event_data)) } +/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks +/// before it gives the palettes' controls and takes the event with `paletteTake`. +fn palette_pending(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine))) +} + fn palette_hide(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index eff97479d1..54de688f93 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -140,6 +140,32 @@ fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_ TEST_ELAPSED.set(None); } +#[test] +fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ + var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ + stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ + other.onClick = function () { log.push('other'); }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); + TEST_ELAPSED.set(None); +} + #[test] fn update_in_a_handler_does_not_pause_the_run() { TEST_ELAPSED.set(Some(Duration::ZERO)); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 2d2ccf2e9a..4a13c7c835 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -35,7 +35,8 @@ //! palette does the same for that palette, so the host's list of its controls stays in step. //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or -//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving +//! `paletteUpdate` each palette's description before each one. Then, called from the script's own code (not from a //! handler, a callback of a built-in function, a getter or a conversion), it asks the host's //! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the //! palette's description. On the showing dialog, or a group or panel in it, `update()` does @@ -104,6 +105,8 @@ pub(crate) struct Classes { selection_set: ObjId, showing: Option, palettes: Vec, + /// Whether an `update()` is taking the waiting events ([`take_waiting`]). + taking: bool, } impl Classes { @@ -750,10 +753,36 @@ fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResu Ok(()) } -/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits +/// (`palettePending`). Before each one the host gets every palette's controls as the script and the +/// handlers before it left them, as at the end of a run, and drops an event whose control has since +/// been disabled, hidden or removed. An `update()` that a getter or a handler calls meanwhile takes +/// no events: the `update()` already taking them goes on with the next one. fn take_waiting(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_some_and(|c| c.taking) { + return Ok(()); + } + set_taking(i, true); + let r = take_each(i); + set_taking(i, false); + r +} + +fn set_taking(i: &mut Interp, taking: bool) { + if let Some(c) = i.script_ui.as_mut() { + c.taking = taking; + } +} + +/// [`take_waiting`]'s loop. +fn take_each(i: &mut Interp) -> JsResult<()> { + let pending = host_fn(i, "palettePending")?; let f = host_fn(i, "paletteTake")?; loop { + if !i.call(&pending, &Value::Undefined, &[])?.truthy() { + return Ok(()); + } + update_palettes(i)?; let answer = i.call(&f, &Value::Undefined, &[])?; if answer.as_object().is_none() { return Ok(()); @@ -1496,6 +1525,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul selection_set, showing: None, palettes: Vec::new(), + taking: false, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 355faee1cf..4dcf1a3ed5 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -384,7 +384,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { } /// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, -/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the +/// answers in `draws`, in order, then `false`. fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); @@ -409,11 +410,17 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); - let taken = RefCell::new(VecDeque::from(taken)); + let taken = Rc::new(RefCell::new(VecDeque::from(taken))); let c = calls.clone(); + let left = taken.clone(); let take: HostFunction = Rc::new(move |_| { c.borrow_mut().push(("paletteTake".into(), 0.0)); - Ok(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + let c = calls.clone(); + let pending: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("palettePending".into(), 0.0)); + Ok(Data::Bool(!taken.borrow().is_empty())) }); let draws = RefCell::new(VecDeque::from(draws)); let c = calls.clone(); @@ -433,6 +440,7 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), ("paletteEvent".into(), HostItem::Function(event)), ("paletteTake".into(), HostItem::Function(take)), + ("palettePending".into(), HostItem::Function(pending)), ("paletteDraw".into(), HostItem::Function(draw)), ]; r.define_script_ui(items).unwrap(); @@ -533,7 +541,27 @@ fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() ) .unwrap(); assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); - assert!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); + assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits"); + assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event"); + let order = names(&calls); + let take = order.iter().position(|n| n == "paletteTake"); + let last_update = order.iter().rposition(|n| n == "paletteUpdate"); + assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken"); +} + +#[test] +fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() { + let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new()); + let done = r + .run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \ + b.onClick = function () { clicks++; }; \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \ + p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)", + ) + .unwrap(); + assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once"); + assert_eq!(count(&calls, "paletteTake"), 1); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 941a86437c..3623c6e560 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2993,7 +2993,9 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - Those events do not wait for runs of their own. In the app, an `update()` in the script's own code then + Those events do not wait for runs of their own. Each one is checked against the palette as the script and the + handlers before it left it, as an event's own run would be, so a click on a control that an earlier handler + disabled, hid or removed runs no handler. In the app, an `update()` in the script's own code then pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time (VectorCraft's own interval); an `update()` within the same 16 ms does not pause the run, and the app draws its changes at the next pause or when the run ends. An `update()` in a handler, in a callback of a built-in From 38937a1c0f6a835884c3920b493fa7abadf8cbb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:21:19 -0800 Subject: [PATCH 063/533] Scripts: a palette text the full event line refuses stays in its field When 64 palette events already wait, a text change from an edit field is refused. The text had already been taken out of the field's draft, so the next frame showed the script's old text and what the person typed was lost. The refused text now goes back in its field, and the clicks and closes given after a refused change in the same frame are not put in line, so no handler runs without the change before it. --- crates/ui-egui/src/dialogs/script_window.rs | 5 +++ crates/ui-egui/src/script_palettes.rs | 31 +++++++++++++---- crates/ui-egui/src/tests/script_palettes.rs | 37 +++++++++++++++++++-- 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 78e130bab2..69926adf4b 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -233,6 +233,11 @@ pub(crate) fn keep_refused_texts(w: &ScriptUiDialog, d: &mut Dialog, events: &mu refused } +/// Puts `text` back in the edit field `i` of the dialog's drafts `d`, as typed and not given yet. +pub(crate) fn keep_draft(d: &mut Dialog, i: usize, text: &str) { + d.fields.insert(draft_key(i), json!(text)); +} + /// The field that holds an edit field's text while it is typed. fn draft_key(i: usize) -> String { format!("text{i}") diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index ec2e8773dd..8ad4354dac 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -5,10 +5,11 @@ //! is going ([`crate::script_runs::poll`]); the palette stays usable while a run goes on, and its //! events wait for it. A palette does not take the keyboard focus when it opens or changes. An edit //! field's text is given when it loses the focus, at Enter in a one-line field, or before a click -//! or a close; a text the script would refuse stays in its field with the error in the status bar. +//! or a close; a text the script would refuse, or that the full line refuses, stays in its field +//! with the error in the status bar, and the click or close after it is not given. use serde_json::json; -use vectorcraft_engine::script::{ScriptPalette, UiEvent}; +use vectorcraft_engine::script::{ScriptPalette, UiEvent, UiValue}; use crate::VectorcraftApp; use crate::dialogs::script_window; @@ -49,8 +50,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); + give(app, ctx, p.id, &mut drafts, events); keep_drafts(ctx, &p, drafts); - give(app, ctx, p.id, events); } } @@ -83,13 +84,31 @@ pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut } } -/// Puts the events the person gave the palette `id` in line, or shows why one was refused. -pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { +/// Puts the events the person gave the palette `id` in line, or shows why one was refused. A +/// refused text goes back in its field (`drafts`), and once a change is refused, the clicks and +/// closes after it are not given, so no handler runs without the change before it. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, drafts: &mut Dialog, events: Vec) { + let mut change_refused = false; for e in events { + if change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { + continue; + } + let change = match &e { + UiEvent::Change(i, value) => Some((*i, if let UiValue::Text(t) = value { Some(t.clone()) } else { None })), + _ => None, + }; match app.session.script_palette_event(id, e) { // The next frame starts its run. Ok(_) => ctx.request_repaint(), - Err(e) => app.status(e), + Err(error) => { + if let Some((i, text)) = change { + if let Some(text) = text { + script_window::keep_draft(drafts, i, &text); + } + change_refused = true; + } + app.status(error); + } } } } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index b02fc382b2..f467004f6d 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -16,6 +16,11 @@ fn app() -> VectorcraftApp { app } +/// No text typed in a palette's fields. +fn drafts() -> Dialog { + Dialog::new(script_window::KIND, json!({})) +} + fn run_to_end(app: &mut VectorcraftApp) { for _ in 0..10_000 { if !app.session.script_running() { @@ -53,7 +58,10 @@ fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { frame(&ctx, |_| {}); } assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); - assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "the click asks for the next frame"); + assert!( + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])), + "the click asks for the next frame" + ); assert_eq!(app.session.script_palette_events_waiting(), 1); script_runs::poll(&mut app); run_to_end(&mut app); @@ -78,7 +86,7 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { } assert!(app.session.script_dialog().is_some(), "the run waits at its confirm"); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut asks = true; for _ in 0..5 { @@ -102,7 +110,7 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let id = app.session.script_palettes()[0].id; app.run("edit.undoGroup.begin", json!({})).unwrap(); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut delay = std::time::Duration::ZERO; for _ in 0..5 { @@ -146,6 +154,29 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { assert!(!drafts.fields.contains_key("text3")); } +#[test] +fn a_typed_text_the_full_line_refuses_stays_in_its_field() { + use vectorcraft_engine::script::palettes::MAX_WAITING; + let mut app = app(); + let source = format!( + "#targetengine full\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () {{ vc.log(t.text); }}; \ + for (var k = 0; k < {MAX_WAITING}; k++) {{ p.add('button', undefined, 'B' + k); }} p.show();" + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + let fill: Vec = (3..3 + MAX_WAITING).map(UiEvent::Click).collect(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), fill.clone())); + assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "the line is full"); + let mut typed = drafts(); + let events = vec![UiEvent::Change(1, UiValue::Text("typed".into())), UiEvent::Click(2)]; + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut typed, events.clone())); + assert_eq!(typed.fields.get("text1"), Some(&json!("typed")), "the refused text goes back in its field: {:?}", typed.fields); + assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "neither the text nor the click is kept"); +} + #[test] fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { let mut app = app(); From 4ff24a0d6d4cec5cb8affec063b631e18b0a9d2d Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:29:49 +0430 Subject: [PATCH 064/533] PDF: honor embedded-font preferences in synchronous opens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Compose the canonical font choice before Text As, retaining explicit overrides and avoiding an extra parameter clone. - Port the real eight-case synchronous/background font-binding regression to the current Craft runtime. - Build on the contributors’ PDF handling merged in #4569; preserve worker/profile/clipboard and glyph round-trip behavior. Fixes #9286 --- crates/ui-egui/src/dialogs/import_pdf.rs | 8 ++- .../ui-egui/src/dialogs/tests_import_pdf.rs | 2 +- crates/ui-egui/src/io/open.rs | 7 +- crates/ui-egui/src/opening/tests.rs | 69 +++++++++++++++++++ docs/development.md | 4 ++ 5 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..17f1ea744f 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -618,14 +618,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { /// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its /// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the /// file's own text. -pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value { let given = p.get("textAs").is_some_and(|v| !v.is_null()); let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); let options = p.is_object() || p.is_null(); if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { - return p.clone(); + return p; + } + if !p.is_object() { + p = json!({}); } - let mut p = if p.is_object() { p.clone() } else { json!({}) }; p["textAs"] = json!(TextAs::Outlines.id()); p } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..49b5ec44b7 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -430,7 +430,7 @@ fn a_pdf_opened_without_the_dialog_takes_the_pdf_text_preference() { io::open_document(&mut app, "one.pdf", &one, None, &json!({"textAs": "text"})).unwrap(); opened(&mut app); assert_eq!(type_objects(&app), 1, "an open that gives textAs keeps it"); - let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, &serde_json::Value::Null); + let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, serde_json::Value::Null); assert!(p.is_null(), "a .ai file opens as it says: {p}"); // In the dialog too, a .ai file starts from Editable, and its choice is not kept for PDFs. assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(false, None), None, None)); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 639f33ac21..5ab17f9a69 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -143,9 +143,10 @@ pub fn opens_as(name: &str) -> Option { /// Open a document through the engine loader with the `document.open` options in `p` → /// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first /// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent -/// files, once the question is answered. A PDF opens with the `pdfTextAs` preference unless `p` -/// gives `textAs` ([`dialogs::import_pdf::with_preferred_text_as`]). +/// files, once the question is answered. PDF font and Text As preferences supply missing options; +/// explicit `embeddedFonts` and `textAs` choices keep their precedence. pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { + let p = app.session.prefs.with_pdf_font_choice(p); let p = &dialogs::import_pdf::with_preferred_text_as(app, name, bytes, p); let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; @@ -609,7 +610,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } - let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, &Value::Null); + let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, Value::Null); return Ok(crate::opening::start_with(app, path, bytes, params)); } let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 2466381a3d..551cac14e8 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -4,6 +4,75 @@ use super::*; use crate::Services; use crate::tests::picks::{cancel_dialog, close_shown, draw_dialogs, open_dialogs, show_question}; +/// #9286: both real open consumers apply the same preference/explicit-option precedence and bind +/// the carried program to rendered text, rather than merely storing the requested option. +#[test] +fn synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides() { + use std::fmt::Write as _; + use vectorcraft_doc::{FILE_FONT_MIME, NodeKind}; + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let mut glyph = FileGlyph { ch: 'x', outline: Default::default(), advance: 600.0 }; + glyph.outline.move_to((0.0, 0.0)); + glyph.outline.line_to((500.0, 0.0)); + glyph.outline.line_to((500.0, 700.0)); + glyph.outline.line_to((0.0, 700.0)); + glyph.outline.close_path(); + let info = FileFontInfo { family: "VectorCraftUIOpenPreference".into(), style: "Regular".into(), ..Default::default() }; + let font_bytes = build_file_font(&info, &[glyph]).unwrap(); + let mut hex = String::with_capacity(font_bytes.len() * 2); + for b in font_bytes { + write!(hex, "{b:02x}").unwrap(); + } + let n = first_extra(1); + let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(100.0, 100.0, "BT /F1 24 Tf 10 40 Td (x) Tj ET") }; + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+VectorCraftUIOpenPreference /FirstChar 120 /LastChar 120 /Widths [600] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>", + n + 1 + ); + let descriptor = format!( + "<< /Type /FontDescriptor /FontName /ABCDEF+VectorCraftUIOpenPreference /Flags 34 /FontBBox [0 -200 500 900] /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 {} 0 R >>", + n + 2 + ); + let program = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1); + let bytes = pdf_with(&[page], &[&font, &descriptor, &program], None); + for background in [false, true] { + for (preference, explicit, expected) in [(false, None, false), (true, None, true), (false, Some(true), true), (true, Some(false), false)] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + app.session.prefs.pdf_import_embedded_fonts = preference; + let mut params = json!({"textAs": "text"}); + if let Some(value) = explicit { + params["embeddedFonts"] = json!(value); + } + if background { + start_with(&mut app, "embedded-preference.pdf", bytes.clone(), params); + open_ready(&mut app); + } else { + crate::io::open_document(&mut app, "embedded-preference.pdf", &bytes, None, ¶ms).unwrap(); + } + let doc = &app.session.doc().unwrap().doc; + let db = vectorcraft_text::FontDb::global(); + let mut text_count = 0; + let mut carries_font = false; + doc.walk(|node| { + if let NodeKind::Text(text) = &node.kind { + assert_eq!(text.plain_text(), "x", "imported text content"); + text_count += 1; + carries_font |= vectorcraft_text::layout(db, text).glyphs.iter().any(|glyph| db.is_file_font(glyph.font_id)); + } + }); + assert_eq!(text_count, 1, "text survives: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!(carries_font, expected, "rendered font: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!( + doc.images.values().any(|blob| blob.mime == FILE_FONT_MIME), + expected, + "owned font program: background={background}, preference={preference}, explicit={explicit:?}" + ); + } + } +} + #[test] fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/docs/development.md b/docs/development.md index 404dc10f33..8ec8db5fab 100644 --- a/docs/development.md +++ b/docs/development.md @@ -352,6 +352,10 @@ The app decides which cursors exist; whoever draws them works from the list. For doesn't run. `cargo xtask ci` runs the same two as its `test` and `doctests` steps. - The test build leaves out the examples (`--lib --bins --tests`); clippy (`--all-targets`) still checks them. +- PDF open consumers compose the embedded-font preference before Text As without cloning the + composed options again; explicit options win in both synchronous and background opens. + `opening::tests::synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides` + exercises both paths with a generated embedded font and checks rendered font ownership (#9286). - Each crate has one integration-test binary: its test files are modules of `tests/it/main.rs`. Run one file's tests with `cargo nextest run -p vectorcraft-svg --test it roundtrip::` (or `cargo test` with the same arguments). A new test file gets a `mod` line in `main.rs`. From 35e27e2224040c5147f3d7f934d76c4e458c47a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:40:38 -0800 Subject: [PATCH 065/533] Scripts: PageItem translate, rotate, resize and transform move and reshape objects A page item's translate(deltaX, deltaY, ...), rotate(angle, ...), resize(scaleX, scaleY, ...) and transform(matrix, ...) run object.transform on the object inside the run's transaction, so the run keeps one undo step and the selection stays as it was. Offsets, angles and matrices have Y up, rotate, resize and transform act about the center of the geometric bounds or a Transformation point, and positions, patterns, gradients and line widths follow their arguments. Locked art, art on a locked artboard, a scale of 0, a singular matrix and a result past the canvas throw an error and change nothing, and a call that changes nothing runs no command. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 10 +- crates/engine/src/script/dom/matrix.rs | 12 +- crates/engine/src/script/dom/transform.rs | 216 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 8 +- .../engine/src/tests/script_dom_transform.rs | 220 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 7 +- docs/mcp.md | 30 ++- docs/target-app-parity.md | 1 + 9 files changed, 484 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/script/dom/transform.rs create mode 100644 crates/engine/src/tests/script_dom_transform.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 73f00536a2..27a95eb321 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod clipboard; mod matrix; pub mod preferences; +mod transform; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -1834,6 +1835,7 @@ const ENUMS: &[(&str, &[&str])] = &[ ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), ("DocumentColorSpace", &["CMYK", "RGB"]), ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), @@ -1959,6 +1961,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("move", method(l, item_move)), ("remove", method(l, item_remove)), ("zOrder", method(l, item_z_order)), + ("translate", method(l, transform::translate)), + ("rotate", method(l, transform::rotate)), + ("resize", method(l, transform::resize)), + ("transform", method(l, transform::transform)), ]); page_item.extend( [ @@ -1976,10 +1982,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "wrapOffset", "wrapped", "bringInPerspective", - "resize", - "rotate", - "transform", - "translate", ] .into_iter() .map(|m| later(l, "PageItem", m)), diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 2e8a4d7df7..99b0a9aa05 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -24,7 +24,7 @@ use vectorcraft_js::{Data, HostError, HostMember}; use super::{Answer, Host, Link, arg, method, named, num, text}; /// A matrix's six values: `[a, b, c, d, tx, ty]`. -type Matrix = [f64; 6]; +pub(super) type Matrix = [f64; 6]; const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"]; @@ -59,7 +59,7 @@ fn record(m: Matrix) -> Answer { } /// The matrix argument `d`. -fn matrix(d: &Data, what: &str) -> std::result::Result { +pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result { let bad = || HostError::Type(format!("{what} must be a Matrix")); let Data::Object(items) = d else { return Err(bad()) }; let mut m = [0.0; 6]; @@ -187,18 +187,18 @@ fn nearest(sums: &[Wide]) -> f64 { v } -fn translate(dx: f64, dy: f64) -> Matrix { +pub(super) fn translate(dx: f64, dy: f64) -> Matrix { [1.0, 0.0, 0.0, 1.0, dx, dy] } /// A scale by `sx` and `sy` percent. -fn scaled(sx: f64, sy: f64) -> Matrix { +pub(super) fn scaled(sx: f64, sy: f64) -> Matrix { [sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0] } /// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of /// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it. -fn rotate(degrees: f64) -> Matrix { +pub(super) fn rotate(degrees: f64) -> Matrix { let turn = degrees % 360.0; let (sin, cos) = match turn { 0.0 => (0.0, 1.0), @@ -357,7 +357,7 @@ fn determinant(m: Matrix) -> Wide { products_difference(m[0], m[3], m[1], m[2]) } -fn singular(m: Matrix) -> bool { +pub(super) fn singular(m: Matrix) -> bool { determinant(m).m == 0.0 } diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs new file mode 100644 index 0000000000..2a3ff3ec6e --- /dev/null +++ b/crates/engine/src/script/dom/transform.rs @@ -0,0 +1,216 @@ +//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the +//! help page describes them. Each one +//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo +//! step for the document; a call that changes nothing runs no command. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever +//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns +//! it counterclockwise. +//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds, +//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the +//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts +//! about that point. +//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument: +//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles +//! preference. Fill and stroke patterns transform together, and gradients with the object, so a +//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error +//! that says so. +//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own +//! scale in percent, the square root of the area it scales by (stroke weights and effects scale +//! with it, as Scale Strokes & Effects does); any other value throws an error that says so. +//! - A locked object, one inside a locked layer or group, a group that holds one, and an object on +//! a locked artboard are refused with nothing changed, and so are a scale of 0, a matrix whose +//! determinant is 0 and a transformation that would take the object past the canvas. + +use serde_json::json; +use vectorcraft_geom::{Affine, Point, Rect}; +use vectorcraft_js::{Data, HostError}; + +use super::matrix::{self, Matrix}; +use super::{Answer, Coords, Host, Item, arg, coordinate, edit_item, frame, number, this_item, with_doc}; + +/// The error for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; + +/// The error for a locked object. +const LOCKED: &str = "cannot transform locked objects"; + +/// What a transform method changes besides the object's geometry. +struct Options { + /// Positions and orientations (`changePositions`, `transformObjects`). + objects: bool, + /// Pattern fills and strokes. + patterns: bool, + /// Stroke weights and effects (`changeLineWidths`). + strokes: bool, +} + +/// An optional `true` or `false` argument. +fn flag(d: &Data, what: &str) -> std::result::Result, HostError> { + match d { + Data::Undefined => Ok(None), + Data::Bool(b) => Ok(Some(*b)), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after, +/// with the names the method gives them. +fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result { + let tiles = h.session.borrow().prefs.transform_pattern_tiles; + let objects = flag(arg(a, at), names[0])?.unwrap_or(true); + let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles); + let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true); + let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles); + if fill != stroke { + return Err(HostError::Error(format!("{} and {} with different values are not available yet", names[1], names[3]))); + } + if gradients != objects { + return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0]))); + } + Ok(Options { objects, patterns: fill, strokes: false }) +} + +/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix. +fn line_widths(d: &Data, m: Matrix) -> std::result::Result { + let lw = match d { + Data::Undefined => return Ok(false), + d => number(d, "changeLineWidths")?, + }; + let own = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * 100.0; + if (lw - own).abs() <= 1e-9 * own.max(1.0) { + return Ok((own - 100.0).abs() > 1e-9); + } + if (lw - 100.0).abs() <= 1e-9 { + return Ok(false); + } + Err(HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet"))) +} + +/// The point of `r` (document coordinates, Y down) that the `Transformation` value `d` names. +fn anchor(h: &Host, item: Item, r: Rect, d: &Data) -> std::result::Result { + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + let name = match d { + Data::Undefined => return Ok(Point::new(cx, cy)), + Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""), + _ => "", + }; + Ok(match name { + "CENTER" => Point::new(cx, cy), + "TOPLEFT" => Point::new(r.x0, r.y0), + "TOP" => Point::new(cx, r.y0), + "TOPRIGHT" => Point::new(r.x1, r.y0), + "LEFT" => Point::new(r.x0, cy), + "RIGHT" => Point::new(r.x1, cy), + "BOTTOMLEFT" => Point::new(r.x0, r.y1), + "BOTTOM" => Point::new(cx, r.y1), + "BOTTOMRIGHT" => Point::new(r.x1, r.y1), + "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, + _ => return Err(HostError::Type("the point to transform about must be a Transformation value".into())), + }) +} + +/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`. +fn on_page(m: Matrix, o: Point) -> Affine { + let [a, b, c, d, tx, ty] = m; + let page = Affine::new([a, 0.0 - b, 0.0 - c, d, tx, 0.0 - ty]); + Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) +} + +/// Applies `m` (Y up) to the item `this` names, about the point `about` names (`None`: the matrix +/// acts as a move, which needs no point), with `opts`. +fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) -> Answer { + let item = this_item(h, a)?; + if m.iter().any(|v| !v.is_finite()) { + return Err(HostError::Range("the transformation has a value too large for a number".into())); + } + if matrix::singular(m) { + return Err(HostError::Error("the transformation is singular and would flatten the object".into())); + } + let (locked, on_locked, bounds, uses_pattern) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let mut locked = d.ancestry(item.id).is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); + let mut uses = false; + if let Some(n) = d.node(item.id) { + n.walk(&mut |c| { + locked |= c.locked; + uses |= vectorcraft_doc::pattern::uses_pattern(c, None); + }); + } + (locked, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses) + }); + if locked { + return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + let o = match (about, bounds) { + (Some(d), Some(r)) => anchor(h, item, r, d)?, + (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (None, _) => Point::ORIGIN, + }; + let xf = on_page(m, o); + if let Some(r) = bounds.filter(|_| opts.objects) { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; + if corners.iter().map(|p| xf * *p).any(|p| !(p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD)) { + return Err(HostError::Range("the transformation would take the object past the canvas".into())); + } + } + let c = xf.as_coeffs(); + let identity = c.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(v, i)| (v - i).abs() <= 1e-12); + let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; + if changes { + let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); + edit_item(h, item, "object.transform", &p)?; + } + Ok(Data::Undefined) +} + +/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, +/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out). +pub(super) fn translate(h: &Host, a: &[Data]) -> Answer { + let delta = |i: usize, what: &str| match arg(a, i) { + Data::Undefined => Ok(0.0), + d => coordinate(d, what), + }; + let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?); + let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"]; + let opts = options(h, a, 3, names)?; + apply(h, a, matrix::translate(dx, dy), None, &opts) +} + +const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; + +/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, +/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive. +pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer { + let angle = number(arg(a, 1), "angle")?; + let opts = options(h, a, 2, CHANGE_NAMES)?; + apply(h, a, matrix::rotate(angle), Some(arg(a, 6)), &opts) +} + +/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and +/// `scaleY` percent along the page's axes. +pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { + let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?); + if sx == 0.0 || sy == 0.0 { + return Err(HostError::Range("scaleX and scaleY must not be 0".into())); + } + let m = matrix::scaled(sx, sy); + let mut opts = options(h, a, 3, CHANGE_NAMES)?; + opts.strokes = line_widths(arg(a, 7), m)?; + apply(h, a, m, Some(arg(a, 8)), &opts) +} + +/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?, +/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the +/// object. +pub(super) fn transform(h: &Host, a: &[Data]) -> Answer { + let m = matrix::matrix(arg(a, 1), "transformationMatrix")?; + let mut opts = options(h, a, 2, CHANGE_NAMES)?; + opts.strokes = line_widths(arg(a, 6), m)?; + apply(h, a, m, Some(arg(a, 7)), &opts) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c66897c70b..600e82a7be 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -174,6 +174,7 @@ mod script_dialogs; mod script_dollar; mod script_dom; mod script_dom_prefs; +mod script_dom_transform; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a1ea190b57..10de309e4d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -700,9 +700,11 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].bringInPerspective(0, 0);", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs new file mode 100644 index 0000000000..1be3046209 --- /dev/null +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -0,0 +1,220 @@ +//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with a 30 × 40 pt rectangle and a 50 × 50 pt one above it. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The numbers of a logged array, or a logged number as one. +fn numbers(v: &Value) -> Vec { + match v.as_array() { + Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(), + None => vec![v.as_f64().unwrap()], + } +} + +fn close(a: &[f64], b: &[f64]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +#[test] +fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\ + i.translate(10, 0); vc.log([i.left - l, i.top - t]);\ + i.translate(0, 10); vc.log([i.left - l, i.top - t]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\ + i.translate(0, 5); vc.log(i.top - t2);", + ); + assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}"); + // With Y down from the artboard's top, a move up reads as a smaller top. + assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap(); + assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}"); +} + +#[test] +fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\ + vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\ + g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);", + ); + assert_eq!(out[0], json!("GroupItem")); + let (before, after) = (numbers(&out[1]), numbers(&out[2])); + // The width and height trade places, and the center stays. + assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}"); + + // A positive angle about the bottom-left corner swings a rectangle to the left of that corner. + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\ + i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);", + ); + let (b0, b1) = (numbers(&out[0]), numbers(&out[1])); + // [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side + // lies to the left. + assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}"); +} + +#[test] +fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, i = p[0], j = p[1];\ + function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\ + var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\ + var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);", + ); + let first = numbers(&out[0]); + assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}"); + let second = numbers(&out[1]); + assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}"); + assert!(close(&second[1..], &[0.5]), "{second:?}"); + // A line width that is neither 100 nor the scale itself is refused. + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);"); + assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); +} + +#[test] +fn transform_applies_a_matrix_record_about_the_center() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\ + i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\ + vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\ + var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);", + ); + let side = 70.0 / 2f64.sqrt(); + assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}"); + assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}"); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn transforms_that_change_nothing_add_no_undo_step() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\ + i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\ + i.translate(7000000, 0, false, false, false, false);", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn locked_art_and_art_on_a_locked_artboard_are_refused() { + let (mut s, a, b) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] { + let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};")); + assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);"); + assert!(e.contains("cannot transform locked objects"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].rotate(45);"); + assert!(e.contains("cannot transform objects on a locked artboard"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (call, says) in [ + ("rotate('x')", "angle must be a finite number"), + ("rotate()", "angle must be a finite number"), + ("resize(50)", "scaleY must be a finite number"), + ("resize(0, 50)", "must not be 0"), + ("transform({})", "transformationMatrix must be a Matrix"), + ("transform(app.getScaleMatrix(0))", "singular"), + ("translate(1, 0, 'yes')", "transformObjects must be true or false"), + ("translate(7000000, 0)", "past the canvas"), + ("translate('x')", "deltaX must be a finite number"), + ("translate(NaN)", "is not a finite number"), + ("rotate(5, true, false, false)", "changeFillGradients different from changePositions"), + ("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"), + // Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and + // gradients default to true. + ("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"), + ("translate(10, 0, false)", "transformFillGradients different from transformObjects"), + ("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"), + ("rotate(5, true, true, true, true, 3)", "Transformation value"), + ("resize(1e9, 1e9)", "past the canvas"), + ] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains(says), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A deleted object is stale before its arguments are used. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);"); + assert!(e.contains("Stale page item"), "{e}"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index df796262af..9250be140c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -82,7 +82,7 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems Preferences RulerUnits ZOrderMethod", + PageItems Preferences RulerUnits Transformation ZOrderMethod", ), ("Application.", "prototype"), ( @@ -122,8 +122,8 @@ const INSIDE: &[(&str, &str)] = &[ "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ - position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ - transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + position= remove resize rotate selected selected= sliced sliced= tags tags= top top= transform translate \ + typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), @@ -139,6 +139,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; diff --git a/docs/mcp.md b/docs/mcp.md index c480155de3..86737f7fdb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2657,8 +2657,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds together with the anchors and direction points of the paths in the object; a clipping group counts its clipping path only, and a blend, envelope or other live object gives its visible bounds), `editable`, `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 + `move(relativeObject, insertionLocation?)`, `remove()`, `zOrder(method)`, `translate`, `rotate`, `resize` and + `transform` (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 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` @@ -2671,8 +2671,28 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, - `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and - `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. + `Transformation`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` + and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. + `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, + transformStrokePatterns?)` moves the object by the offsets in points, `rotate(angle, changePositions?, + changeFillPatterns?, changeFillGradients?, changeStrokePattern?, rotateAbout?)` turns it by `angle` degrees, + `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, + changeLineWidths?, scaleAbout?)` scales it by the percentages, and `transform(transformationMatrix, changePositions?, + changeFillPatterns?, changeFillGradients?, changeStrokePattern?, changeLineWidths?, transformAbout?)` applies a + `Matrix` record (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each one runs `object.transform` on the + object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is, + so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and + `transform` act about the center of the geometric bounds unless a `Transformation` value names another point of + them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients + default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different + values, and gradients different from positions, counting the defaults of arguments left out, throw an error that + says they are not available yet. + `changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the + square root of the area it scales by (stroke weights and effects scale with it); another value throws the same + error. A locked object, one inside a locked layer or group, a group that holds one, and an object on a locked + artboard throw `cannot transform locked objects` or `cannot transform objects on a locked artboard`. A scale of 0, a + matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error. + In each of these cases the document does not change. A call that changes nothing runs no command. VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with @@ -2693,7 +2713,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. 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. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.bringInPerspective` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 82cbdd078a..30df978ebe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. + - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call runs `object.transform` inside the run's transaction; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From c70eb7fc986a581b49d34ccf046f3434115eb9af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:53:40 -0800 Subject: [PATCH 066/533] Scripts: character attributes set the fill and stroke of text A text range and its characterAttributes now have fillColor, strokeColor and strokeWeight. The colors take and give the same color objects as a path's fill and stroke; a NoColor takes the paint away, and a color out of range or of a kind that cannot be assigned yet throws with nothing changed. strokeWeight is 0 to 1000 points and reads in document points on scaled type. Setting the value a range already has records no undo step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/text.rs | 43 +++++++++-- crates/engine/src/tests/script_text.rs | 72 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 ++-- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 5 files changed, 122 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..6595cfb926 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -3,7 +3,8 @@ //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , //! , -//! and +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: @@ -33,6 +34,8 @@ //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. A text range has the members of //! both its `characterAttributes` and its `paragraphAttributes`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +43,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, - frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, - whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, + float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -789,9 +793,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -803,6 +810,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -905,9 +915,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + /// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); @@ -976,6 +995,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let paint = color.map_or(Paint::None, Paint::solid); + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..7d70741e69 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -225,6 +225,78 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn character_attributes_paint_only_their_own_characters() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\ + var red = new RGBColor(); red.red = 255; b.fillColor = red;\ + var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\ + vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\ + vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);", + ); + let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}"); + assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given"); + assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill"); + assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke"); + let runs = paints(&s, id); + let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own"); + assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(b.3 > 1.0); + assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}"); + assert!(undo_steps(&s) > before); + + let steps = undo_steps(&s); + log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step"); + log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();"); + assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); +} + +#[test] +fn stroke_weight_reads_back_in_document_points_on_scaled_type() { + let (mut s, id) = doc_with("abc"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);"); + assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}"); + let stored = paints(&s, id)[0].3; + assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has"); +} + +#[test] +fn bad_text_paint_is_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let runs = paints(&s, id); + for (src, want) in [ + ("r.fillColor = 'red';", "fillColor must be a color object"), + ("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"), + ("r.fillColor = new GradientColor();", "not available yet"), + ("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"), + ("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a1893c17cf..016b0acd37 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,12 +177,14 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ - spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -195,9 +197,9 @@ const INSIDE: &[(&str, &str)] = &[ ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", - "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ - rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ - underline= verticalScale verticalScale=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 08f1c2fc98..afa5506833 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2719,8 +2719,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and - `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, - set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, + `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and + `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50d76e869f..57c3304e95 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles and tab stops are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From f0c2c946b9277dbf95d1e2c495236d9534f11be4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:58:43 -0800 Subject: [PATCH 067/533] Scripts: keep clipping paths at the bottom and take handles into controlBounds - node.move refuses to move the clipping path of a clip group or clipping layer until the mask is released, and a row moved to index 0 of a clip group goes directly above the clipping path. PageItem.move refuses a place behind a clipping path. - controlBounds takes in the anchors and direction handles of the shown paths in the item; hidden paths, guides and clipped art are left out. - Setting opacity to a value that differs from the current one only past the reported precision now sets it. - Text added after a range that ends inside a character goes after the whole character. - textFrames.removeAll() throws and deletes nothing when a type object is on a locked artboard. - Layer lists are kept while the document is unchanged and are charged by the rows they look at; getByName is charged by the items it scans. - The offset tables of text frame indexes are kept within 64 MiB per run; tables past it are made again when the frame is next read. - The handles of host class objects count toward the script heap limit. - Tests: the file-open test quotes the path as a JS string, the font lookup test clears the message between its two checks, and the collection test pins its host-call count. A new test covers a path node.move puts into a pixel-aligned compound path. - Docs: docs/mcp.md, the M13 roadmap row and the scripts entries in docs/target-app-parity.md describe what scripts have now. --- crates/engine/src/cmd/layer.rs | 11 ++- crates/engine/src/script/dom.rs | 39 ++++++++++- crates/engine/src/script/dom/layers.rs | 65 ++++++++++++------ crates/engine/src/script/dom/text.rs | 93 ++++++++++++++++++++++---- crates/engine/src/tests/layers.rs | 25 +++++++ crates/engine/src/tests/pixelalign.rs | 19 ++++++ crates/engine/src/tests/script_dom.rs | 77 ++++++++++++++++++++- crates/engine/src/tests/script_text.rs | 32 ++++++++- crates/js/src/heap.rs | 4 ++ crates/js/src/host_classes.rs | 4 +- crates/js/src/host_tests.rs | 19 ++++++ docs/mcp.md | 10 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 14 files changed, 354 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9fe8d9e678..a7b4073827 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -930,6 +930,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // The clipping path stays at the bottom of its clip group or clipping layer. + let from = d.parent_of(id); + let clips = |p: Option| p.and_then(|p| d.node(p)).filter(|p| p.clips()); + let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id); + if is_mask && (parent != from || index != 0) { + return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first")); + } + let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index }; // An empty compound path takes the paint of the first path that goes into it: the path's own, // or the paint of the compound path it leaves, which is what painted it. let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); @@ -945,7 +953,6 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; - let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7bafaafca1..bde785060d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1540,7 +1540,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // replaces the one the graph keeps for its series or kind. let item = this_item(h, a)?; let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let v = now.filter(|now| (now * 1e4).round() / 1e4 == v).unwrap_or(v); set_props(h, a, |_| false, json!({"opacity": v})) } @@ -1586,6 +1586,33 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths +/// in the item. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r))); + Ok(f.bounds(h.dom.coords.get(), r)) +} + +/// `r` with the anchors and direction handles of the shown paths in `n`. Hidden objects, the +/// objects in them and guides are left out, as the visible bounds leave them out, and a clip group +/// or clipping layer gives only its clipping path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect) -> Rect { + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return r; + } + for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); + } + let children = n.children().map_or(&[][..], Vec::as_slice); + let children = if n.clips() { &children[..children.len().min(1)] } else { children }; + for c in children { + r = take_in_handles(c, r); + } + r +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1823,7 +1850,13 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul { i -= 1; } - if how == Placement::Above { i + 1 } else { i } + let at = if how == Placement::Above { i + 1 } else { i }; + // A place behind a clipping path is refused; an object put into the clip group + // itself goes directly above the clipping path. + if clips && at == 0 { + return Err(HostError::Error("an object cannot go behind a clipping path".into())); + } + at } (_, None) => count, }; @@ -2078,7 +2111,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index b315aab2e0..684a6c84fb 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -486,7 +486,8 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer { fn layers_length(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; - Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64))) + let n = with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))?; + Ok(num(float(n as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -503,14 +504,14 @@ fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) } fn layers_by_name(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = layer_list(&st.doc, parent); + let ids = layer_ids(h, st, parent)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -583,8 +584,8 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { } } -/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, -/// and the ids it listed then. +/// A document's uid, the document as it was, the [`Kind`] (or [`LAYER_LIST`]) and the container of +/// an art or layer collection, and the ids it listed then. pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); /// How many lists of art [`super::State`] keeps at once. @@ -595,9 +596,44 @@ pub(super) const ART_LISTS: usize = 4; /// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds /// each list once. Each new list is charged by the objects it looks at. fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + kept_list(h, st, kind as u8, container, || { + Ok(match container { + None => { + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } + }) + }) +} + +/// The tag of a list of layers among the kept lists of art. +const LAYER_LIST: u8 = u8::MAX; + +/// The layers of `parent` (`None`: the top level), top first, kept as [`art_list`] keeps its +/// lists. Each new list is charged by the rows it looks at. +fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result>> { + kept_list(h, st, LAYER_LIST, parent, || { + let rows = match parent { + None => Some(&st.doc.layers), + Some(p) => st.doc.children(Some(p)), + }; + h.charge_call(rows.map_or(0, Vec::len) as u64)?; + Ok(layer_list(&st.doc, parent)) + }) +} + +/// The list kept for `tag` and `container` while the document is unchanged, else the one `build` +/// makes, which is kept in place of the least recently used one. +fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option, build: impl FnOnce() -> Result>) -> Result>> { { let mut lists = h.dom.art.borrow_mut(); - let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == tag && *c == container); if let Some(at) = at { let list = lists.remove(at); let ids = list.4.clone(); @@ -605,25 +641,13 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R return Ok(ids); } } - let ids: Vec = match container { - None => { - let all = page_items(h, st); - h.charge_call(all.len() as u64)?; - all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() - } - Some(c) => { - let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); - h.charge_call(children.len() as u64)?; - children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() - } - }; - let ids = Rc::new(ids); + let ids = Rc::new(build()?); let mut lists = h.dom.art.borrow_mut(); lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); if lists.len() >= ART_LISTS { lists.remove(0); } - lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + lists.push((st.uid, st.doc.clone(), tag, container, ids.clone())); Ok(ids) } @@ -663,6 +687,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { let ids = art_list(h, st, kind, c)?; + h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 556b0a113c..df600f6c6b 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -59,6 +59,10 @@ pub const STALE_RANGE: &str = "Stale text range"; /// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit /// is stale. const MAX_EDITS: usize = 100_000; +/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of +/// the other frames are given up; their text, generations and edits stay, and each frame's tables +/// are made again when it is next read. +const INDEX_BUDGET: usize = 64 << 20; /// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. pub(super) struct Index { @@ -102,6 +106,22 @@ impl Index { Self { text, chars, bytes, words, paras } } + /// The text alone, without its offset tables, for a frame whose tables were given up under + /// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read. + fn bare(text: String) -> Self { + Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() } + } + + fn is_bare(&self) -> bool { + self.chars.is_empty() + } + + /// The bytes the offset tables hold. + fn table_bytes(&self) -> usize { + let pairs = self.words.capacity() + self.paras.capacity(); + (self.chars.capacity() + self.bytes.capacity()) * size_of::() + pairs * size_of::<(usize, usize)>() + } + fn len(&self) -> usize { self.chars.last().copied().unwrap_or(0) } @@ -127,6 +147,13 @@ impl Index { fn char_span(&self, i: usize) -> Option<(usize, usize)> { Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) } + + /// UTF-16 offset `u` on a character boundary: inside a surrogate pair, the start of its + /// character, or with `up` the end of it. + fn boundary(&self, u: usize, up: bool) -> usize { + let b = self.byte(u, up); + self.chars.get(self.bytes.partition_point(|&x| x < b)).copied().unwrap_or_else(|| self.len()) + } } /// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty @@ -201,6 +228,28 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]). + table_bytes: Cell, +} + +/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within +/// [`INDEX_BUDGET`], giving up the tables of other frames first. +fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) { + let mut total = state.table_bytes.get() + index.table_bytes(); + if let Some(l) = frames.get_mut(&key) { + total -= l.index.table_bytes(); + l.index = Rc::new(index); + } + for (k, l) in frames.iter_mut() { + if total <= INDEX_BUDGET { + break; + } + if *k != key && !l.index.is_bare() { + total -= l.index.table_bytes(); + l.index = Rc::new(Index::bare(l.index.text.clone())); + } + } + state.table_bytes.set(total); } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -228,29 +277,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc {} + let fresh = match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None, Some(l) => { - if l.reverts != st.reverts || !same_text(t, &l.index.text) { + let changed = l.reverts != st.reverts || !same_text(t, &l.index.text); + if changed { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); - l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + changed.then(|| t.plain_text()) } None => { let l = Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, - index: Rc::new(Index::new(t.plain_text())), + index: Rc::new(Index::bare(String::new())), stamp: 0, floor: 0, edits: VecDeque::new(), }; frames.insert(key, l); + Some(t.plain_text()) } + }; + // Tables given up under the budget are made again from the text the log keeps. + let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone())); + if let Some(text) = fresh { + set_index(&h.dom.text, &mut frames, key, Index::new(text)); } let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok((l.index.clone(), l.stamp)) @@ -320,9 +376,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser l.floor = l.stamp; l.edits.clear(); } - l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now)); Ok(()) }) } @@ -718,16 +774,16 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); @@ -740,13 +796,16 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // An offset inside a character goes to its end for an insertion after, else to its start, for + // the edit, the edit log and the range returned alike. + let at = index.boundary(at, after); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); + let b = index.byte(at, after); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -1379,19 +1438,25 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { } /// `removeAll()`: deletes every type object the collection lists in one command; a hidden or -/// locked one stops it first. +/// locked one, or one on a locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused, on_locked)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f49637c768..858d14396d 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -893,6 +893,31 @@ fn moves_are_validated() { assert_eq!(parent(&s, sub), None); } +/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group +/// or move up in it, and a row moved to index 0 goes directly above it. +#[test] +fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0)); + let layer = parent(&s, a).unwrap(); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + let g = id(&run(&mut s, "object.clippingMask.make", json!({}))); + let before = children(&s, g); + let mask = before[0]; + for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] { + let err = s.execute("node.move", &p).unwrap_err().to_string(); + assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); + assert_eq!(children(&s, g), before, "{p}"); + } + let _ = s.execute("node.move", &json!({"id": mask.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g), before, "the clipping path stays where it is"); + let d = rect(&mut s, 90.0); + run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path"); + run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, before[2]]); +} + /// The Layers panel's commands refuse a switch given as text or as another value that is not true /// or false, and leave the document, the selection, the highlighted rows and the undo history as /// they were; true, false and null still work. diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 00b4cce694..d4b3916f4a 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -478,6 +478,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() { assert!(halves(&pts), "slice: {pts:?}"); } +/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither +/// the path nor where it came from was pixel-aligned. +#[test] +fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); + let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0); + assert!(!aligned(&s, loose)); + s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c))); + let pts = compound_points(&s, c); + assert_eq!(pts.len(), 12); + assert!(halves(&pts), "{pts:?}"); +} + /// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an /// artboard copied with its art, stay on the pixel grid. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e8522ed334..94c92e591f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -133,6 +133,46 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the direction handles of a curve, which reach past its visible bounds. +#[test] +fn control_bounds_take_in_the_direction_handles() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!(top(&out[0]) < 180.0, "{out:?}"); + assert_eq!(top(&out[1]), 200.0, "{out:?}"); + assert_eq!(out[1][2].as_f64().unwrap(), out[0][2].as_f64().unwrap(), "{out:?}"); +} + +/// The `controlBounds` of a group leave out the handles of a hidden curve in it. +#[test] +fn control_bounds_leave_out_hidden_paths() { + let (mut s, a, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, id]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"id": id, "visible": false})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.selection[0].parent; vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[1], out[0], "{out:?}"); +} + +/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping +/// path. +#[test] +fn control_bounds_of_a_clip_group_come_from_its_clipping_path() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + let mask = rect(&mut s, 100.0, 150.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[0], json!(true), "{out:?}"); + assert_eq!(out[2], out[1], "{out:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -257,6 +297,15 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps); } +/// An opacity near the one an item has, but not the one it reports, is set. +#[test] +fn an_opacity_close_to_the_current_one_is_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.opacity = 50.00009; vc.log(i.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -391,6 +440,27 @@ fn move_and_duplicate_place_by_element_placement() { assert!(e.contains("hidden or locked"), "{e}"); } +/// An object cannot go behind a clip group's clipping path; one put at the end of the group goes +/// directly above the clipping path. +#[test] +fn an_object_cannot_go_behind_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = kids(&s); + s.execute("object.setProps", &json!({"id": before[0].0, "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"id": before[1].0, "name": "art"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); + assert!(e.contains("behind a clipping path"), "{e}"); + assert_eq!(kids(&s), before); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), [before[0], c, before[1]]); +} + #[test] fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); @@ -1300,8 +1370,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (same, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({same})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. @@ -1830,6 +1901,8 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap()); assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); + // A list built again for each lookup would add a host call to both. + assert_eq!(a["hostCalls"], json!(50), "{a}"); } #[test] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a164ca396b..6101835982 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -432,7 +432,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -508,6 +508,20 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert_eq!(plain(&s, id), "ab"); } +/// Text added after a range that ends inside a character goes after the whole character, and the +/// range returned holds the added text. +#[test] +fn text_added_after_half_a_character_goes_after_it() { + let (mut s, id) = doc_with("a\u{1F600}b"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\ + var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);", + ); + assert_eq!(out, vec![json!([3, "X"])]); + assert_eq!(plain(&s, id), "a\u{1F600}Xb"); +} + #[test] fn text_fonts_find_a_bundled_face_by_its_postscript_name() { let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { @@ -649,6 +663,22 @@ fn text_frames_of_a_layer_or_group_put_new_type_in_it() { assert_eq!(undo_steps(&s), before); } +/// `textFrames.removeAll()` deletes nothing when a type object it lists is on a locked artboard. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}"); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(undo_steps(&s), before); +} + #[test] fn text_create_puts_type_in_the_layer_or_group_it_names() { let mut s = Session::new(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 9c094a91cc..fd8f201d63 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -422,6 +422,9 @@ pub(crate) const XML_REF_BYTES: usize = 8; pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of the measurement a `UnitValue` object holds. pub(crate) const UNIT_VALUE_BYTES: usize = 32; +/// The bytes of each part of the handle of an object of a host class: the part itself and its +/// copy in the key that finds the object again ([`crate::host_classes`]). +pub(crate) const HOST_PART_BYTES: usize = 16; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -716,6 +719,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, + Class::Host(h) => extra = HOST_PART_BYTES * h.handle.len(), _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..4c5cda0a70 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -155,10 +155,12 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let parts = crate::heap::HOST_PART_BYTES.saturating_mul(handle.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(parts))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); + self.heap.bytes = self.heap.bytes.saturating_add(parts); self.host_objects.insert(made, id); Ok(Value::Object(id)) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..eeac99a3ca 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -661,6 +661,25 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// The handles of the objects of a host class count toward the heap limit. +#[test] +fn host_class_handles_count_toward_the_heap_limit() { + let mut r = Realm::new(); + r.set_limits(Limits { heap_bytes: 64 << 20, ..Limits::default() }); + let n = Rc::new(Cell::new(0.0)); + let big: HostFunction = Rc::new(move |_| { + n.set(n.get() + 1.0); + Ok(host_ref("Thing", &vec![n.get(); 100_000])) + }); + let class = + HostClass { name: "Thing".into(), parent: None, members: vec![("big".to_string(), HostMember::Method(big))], index: None, construct: None }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap(); + match r.run("var a = []; for (var i = 0; i < 100; i++) a.push(thing.big()); a.length") { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => assert_eq!(k, LimitKind::Heap), + other => panic!("{other:?}"), + } +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/docs/mcp.md b/docs/mcp.md index b465eb83a9..e54bc89746 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2682,7 +2682,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + visible bounds with the anchors and direction handles of the shown paths in the item), `editable` (false for an 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 @@ -2795,7 +2795,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel - alignment. + alignment, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the + clipping path of a clip group or clipping layer at its bottom: it refuses to move the clipping path until the mask + is released, and puts a row given index 0 there directly above the clipping path. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both @@ -2807,7 +2809,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer. Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or - locked layer or group throws an error and changes nothing. A `TextFrame` + locked layer or group throws an error and changes nothing. `removeAll()` deletes every type object the collection + lists with `edit.clear` in one step; when one is hidden or locked, in a hidden or locked layer or group, or on a + locked artboard, it throws an error and deletes nothing. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/roadmap.md b/docs/roadmap.md index 26f6a12e3f..a2a446a76a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -198,7 +198,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, and its text frames with their text ranges and the fonts; path properties, views, stories, text styles, the other classes of the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f15c8d15ba..562885ca02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,7 +1033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Paths and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.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`). Path properties and the classes that this bullet and the next two do not name are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `document.textFrames`, and the `textFrames` of a layer or group, which list the type directly in it and put new type on top of its contents (VectorCraft's own rule), make point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/, with https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ for the layer's and group's `textFrames`, describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. From fab69d7f70878d20b58af5b23320a1affc9056d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:10:36 -0800 Subject: [PATCH 068/533] Scripts: a palette's click or change keeps its control when a run changes the palette first The events the person gives a palette are kept with their control's id, and a list's change with the items they chose from, until the app puts them in line. A run that adds or removes controls before then no longer sends a click to the control now at the old index. --- crates/ui-egui/src/dialogs/script_window.rs | 4 ++-- crates/ui-egui/src/script_palettes.rs | 19 ++++++++++++------- crates/ui-egui/src/tests/script_palettes.rs | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 3b7f6098c0..f97cf34bc7 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -259,7 +259,7 @@ pub(crate) fn keep_refused(w: &ScriptUiDialog, drafts: &mut BTreeMap Option { +pub(crate) fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { let id = |i: usize| w.nodes.get(i).map(|n| n.id); Some(match event { UiEvent::Click(i) => Queued::Click(id(*i)?), @@ -274,7 +274,7 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { /// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now. /// `None` when `w` no longer has the control, or for a list's change, when the list's items are no /// longer those the person chose from: other texts, or the same texts added again. -fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { +pub(crate) fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { match q { Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), Queued::Change(id, v, list) => { diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2e4047c09f..05c618c873 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -22,7 +22,7 @@ use vectorcraft_engine::script::{ScriptPalette, ScriptUiDialog, UiEvent, UiValue use crate::VectorcraftApp; use crate::dialogs::script_run::with_host; -use crate::dialogs::script_window; +use crate::dialogs::script_window::{self, Queued}; /// The dialog kind of a ScriptUI palette. pub const KIND: &str = "scriptPalette"; @@ -38,8 +38,10 @@ pub(crate) struct PaletteWindow { palette: ScriptPalette, /// The text typed in each edit field that the script has not had yet, by the field's id. drafts: BTreeMap, - /// The events the person gave since the app last took them. - given: Vec, + /// The events the person gave since the app last took them, each with its control by its id, + /// and a list's change with the items the person saw, so a run that changes the palette before + /// the app takes them leaves each with its own control. + given: Vec, open: bool, } @@ -72,7 +74,7 @@ impl PaletteWindow { /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.given.push(event); + self.given.extend(script_window::queued(&self.palette.dialog, &event)); } } @@ -102,12 +104,12 @@ impl StackDialog for PaletteWindow { let shown = Dialog::new(heading).modeless().initial_focus(Initial::Keep).opened(Bind::bound(open)).show(ui, |ui, _| { events = script_window::controls(ui, &palette.dialog, drafts, true).events; }); - given.extend(events); + given.extend(events.iter().filter_map(|e| script_window::queued(&palette.dialog, e))); // The close box gives the script the close; the palette stays open until the script closes // it. if shown.output.closed.is_some() { self.open = true; - self.given.push(UiEvent::Close); + self.given.push(Queued::Close); } None } @@ -141,8 +143,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { taken }) .unwrap_or_default(); - for (id, mut drafts, mut events) in taken { + for (id, mut drafts, given) in taken { let Some(p) = shown.iter().find(|p| p.id == id) else { continue }; + // Each event goes to its control as the palette is now; one whose control is gone, or whose + // list's items changed since the person chose, is dropped. + let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); drafted(app, &p.dialog, &mut drafts, &mut events); give(app, ctx, p, &mut drafts, events); with_host(app, |host, _| { diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 70462c2b51..b2e89992e0 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -164,6 +164,24 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { assert_eq!(with_palette(&app, id, |w| w.typed(3).map(str::to_string)).unwrap(), None); } +#[test] +fn a_click_given_before_a_run_removes_a_control_before_it_reaches_its_button() { + let mut app = app(); + let source = "#targetengine moves\nvar p = new Window('palette'); var a = p.add('button', undefined, 'A'); \ + var b = p.add('button', undefined, 'B'); a.onClick = function () { vc.log('a'); }; \ + b.onClick = function () { vc.log('b'); }; p.show();"; + let id = shown(&mut app, source); + give(&app, id, UiEvent::Click(2)); + // A run removes A before the app takes the click, so B is now the palette's first control. + start(&mut app, "#targetengine moves\np.remove(a);"); + run_to_end(&mut app); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click waits for its run"); + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["b"]), "the click reaches the button it was given to"); +} + #[test] fn a_typed_text_the_full_line_refuses_stays_in_its_field() { use vectorcraft_engine::script::palettes::MAX_WAITING; From ed0c7432ce0b0fa2806f661a7d703009ebce4c89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:26:11 -0800 Subject: [PATCH 069/533] Scripts: no palette listener runs once an earlier one closed the palette A palette event checks before each listener that the palette still takes it, so a listener that closes the palette stops the listeners after it, on the control and on its containers. --- crates/js/src/scriptui.rs | 21 ++++++++++++--------- crates/js/src/scriptui_tests.rs | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index fe3bd1fadb..970002c96b 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -939,8 +939,10 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, event: ObjId, phase: f64) -> JsResult { +/// in the order they were added. A listener that an earlier one removed does not run, and none +/// runs once the palette of `taker` no longer takes the event. → whether it had any; `None` when +/// the palette stopped taking the event. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, (event, phase): (ObjId, f64), taker: Taker) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() @@ -950,7 +952,7 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve }; let first = wanted(i)?; if first.is_empty() { - return Ok(false); + return Ok(Some(false)); } let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); i.rooted(&functions, |i| { @@ -960,9 +962,12 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve if !wanted(i)?.iter().any(|(g, d)| same(g, f) && d == c) { continue; } + if !takes(i, taker)? { + return Ok(None); + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } - Ok(true) + Ok(Some(true)) }) } @@ -1045,10 +1050,9 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(true), (event, 1.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { return Ok(Some(true)); } @@ -1068,16 +1072,15 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !takes(i, taker)? { return Ok(None); } - let heard = run_listeners(i, target, ty, None, event, 2.0)?; + let Some(heard) = run_listeners(i, target, ty, None, (event, 2.0), taker)? else { return Ok(None) }; if bubbles && !stopped(i)? { for p in above { if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(false), (event, 3.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 428d0aaccc..def7bca945 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -711,6 +711,20 @@ fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() { assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } +#[test] +fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() { + let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \ + b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \ + p.addEventListener('click', function () { later++; }); p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); + assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close"); +} + #[test] fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); From 7737e97068a340fe5597baaa33113b47532722fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:36:05 -0800 Subject: [PATCH 070/533] Scripts: a closed palette's visible is false `close()` and the close box set the palette's `visible` to false once `onClose` lets it close, as `hide()` does, so a script that checks `visible` stops updating a closed palette. --- crates/js/src/scriptui.rs | 6 ++++-- crates/js/src/scriptui_tests.rs | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 970002c96b..9efffaa403 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1428,8 +1428,9 @@ fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { } } -/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its -/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it, its +/// `visible` is false and its handlers no longer run. A `close()` while its `onClose` runs does +/// nothing more. fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); @@ -1440,6 +1441,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; set_slot(i, win, SHOWN, Value::Bool(false))?; + i.put(win, key("visible"), Value::Bool(false), true)?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index def7bca945..ba8421c0f4 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -489,8 +489,10 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { .unwrap(); r.run("Window.__vcPaletteEvent();").unwrap(); assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible"); r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap(); assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again"); + assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible"); assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); } From 199c580ca4331554758e44cb044bcda5f6cb4cb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:27:30 -0800 Subject: [PATCH 071/533] Scripts: pathItems.removeAll() refuses paths on a locked artboard pathItems.removeAll() deleted paths on a locked artboard, while pageItems.removeAll() and remove() throw for them. It now throws the same error and deletes nothing when any path, a path in a group included, is on a locked artboard. --- crates/engine/src/script/dom/paths.rs | 15 +++++++++---- crates/engine/src/tests/script_dom_paths.rs | 25 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 9c4bb604fe..21d8307867 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -67,7 +67,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; @@ -340,18 +340,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `pageItems.removeAll()` is stopped. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index ca995ed913..aac4579cbd 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -97,6 +97,31 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes +/// nothing, as `pageItems.removeAll()` and `remove()` do. +#[test] +fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index af1ddb276f..21fb6ff4c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2804,7 +2804,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, - `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new + `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws + `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, From da2fc57f35bd1b1eadcfb5f74c1e651e94be1ca3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:47:24 -0800 Subject: [PATCH 072/533] Scripts: pathItems reads a path by name as pageItems does pathItems["name"] read as undefined and "name" in pathItems was false even when a path had that name, while pageItems gives the object getByName gives. pathItems now does the same: a read with a name nothing has throws Not found, and the in test is false for it. --- crates/engine/src/script/dom/paths.rs | 13 ++++++++++--- crates/engine/src/tests/script_dom_paths.rs | 16 ++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 21d8307867..823ed46d41 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -67,9 +67,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, - point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, + editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -310,8 +310,15 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), + r => r, + }; + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index aac4579cbd..edd359282e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -97,6 +97,22 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match, +/// as `pageItems` does. +#[test] +fn path_items_read_with_a_name_give_the_named_path() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 21fb6ff4c4..e8d3818991 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2803,7 +2803,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the - order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, + order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as + `pageItems["name"]` is read), `index(key)`, `getByName(name)`, `removeAll()` (when any path is on a locked artboard, it throws `cannot delete objects on a locked artboard` and deletes nothing), `add()` (a path with no points, from `path.create`, painted as new art; when new art has no fill and no stroke, the path has neither), and the shape creators From d84b1cb5650e80cfeef1b05c4ec36117652608fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:10:57 -0800 Subject: [PATCH 073/533] Scripts: a clipping path stays out of compound paths, and near opacities are set node.move refuses to put a clip group's or clipping layer's clipping path into a compound path, so the next object up does not become the clipping path. The art the group clips still moves in. An item's or a layer's opacity assignment is skipped or replaced by the stored value only when it equals the value the getter reports. A value such as 0.00009 on an item at 0% is now set instead of being dropped. --- crates/engine/src/cmd/layer.rs | 7 ++++- crates/engine/src/script/dom.rs | 16 +++++++---- crates/engine/src/script/dom/layers.rs | 6 ++-- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ docs/mcp.md | 2 +- 5 files changed, 61 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 322246f8aa..4ac560fdba 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -924,6 +924,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result { if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { return Err(bad(C, "a compound path holds only paths")); } + // A clip group's or clipping layer's clipping path stays where it is: without it, the + // next object up would become the clipping path. + if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) { + return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first")); + } if !d.is_editable(c.id) { return Err(bad(C, "the compound path is hidden or locked")); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1aeb8d333a..154e9e1cf3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1521,8 +1521,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } +/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four +/// decimals. +fn reported_opacity(opacity: f32) -> f64 { + (f64::from(opacity) * 100.0 * 1e4).round() / 1e4 +} + fn item_opacity(h: &Host, a: &[Data]) -> Answer { - read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -1530,12 +1536,12 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and + // The value the getter reports for the item's opacity sends the opacity it has, and // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // replaces the one the graph keeps for its series or kind. Any other value is sent as given. let item = this_item(h, a)?; - let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| n.opacity)); + let v = now.filter(|now| reported_opacity(*now) == v).map_or(v, |now| f64::from(now) * 100.0); set_props(h, a, |_| false, json!({"opacity": v})) } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..eff3079574 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -42,7 +42,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_ use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, - method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, text, typename, whole, with_doc, + method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -222,7 +222,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { } fn layer_opacity(h: &Host, a: &[Data]) -> Answer { - read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -230,7 +230,7 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e8522ed334..25d3d3f0cf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -257,6 +257,23 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps); } +/// An item's or a layer's opacity that differs from the reported one, however little, is set as +/// given. +#[test] +fn an_opacity_near_the_reported_one_is_still_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; i.opacity = 0.00009; vc.log(i.opacity);\ + var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);", + ); + assert_eq!(out, vec![json!(0.0001), json!(0.0001)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).unwrap().opacity > 0.0); + assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -1695,6 +1712,29 @@ fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); } +/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group +/// clipped as it was; the art the group clips still goes in. +#[test] +fn node_move_refuses_a_clipping_path_for_a_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); + let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s)); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("clipping path"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(cid)); + assert!(d.node(g).unwrap().clips()); + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); +} + /// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint. #[test] fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() { diff --git a/docs/mcp.md b/docs/mcp.md index 49c913442e..b1733075ba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2829,7 +2829,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot index 0 puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path - gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A + gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From c606701aef2a90d41fead42ad84452460e50321c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:04:25 -0800 Subject: [PATCH 074/533] JavaScript: a comma after a rest parameter is a SyntaxError in async arrows - `async (...xs,) => xs` is a SyntaxError, as `(...xs,) => xs` is. `async (x,) => x` still parses. - An arrow function's parameters may end with a comma: `(a, b,) => a + b` parses, and `(a,)` without `=>` is still a SyntaxError. - A `var` that an inherited property of the global object declared, without ECMAScript 2015 scoping, no longer stops a later `let` of its name once the realm turns the option on. - A tagged template's object reserves the heap for its index names and its `raw` property before it is made. - The test262 runner skips a test whose template literal runs a missing built-in as code, as it skips one whose string does. --- crates/js/src/async_tests.rs | 12 ++++++++++ crates/js/src/es2015_tests.rs | 42 +++++++++++++++++++++++++++++++++++ crates/js/src/interp.rs | 17 +++++++++++--- crates/js/src/parser.rs | 37 ++++++++++++++++++++++++------ crates/js/tests/test262.rs | 11 ++++++++- 5 files changed, 108 insertions(+), 11 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 0d78c4fd3c..e16f8e2a35 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -69,6 +69,18 @@ fn arrows_expressions_and_methods_can_be_async() { assert_eq!(log(src), "4,3,function,kv"); } +#[test] +fn a_comma_may_follow_an_arrow_functions_last_parameter_but_not_a_rest_parameter() { + let src = "var f = async (x,) => x; var g = async (x, ...xs) => xs.length; var h = (a, b,) => a + b;\n\ + var async = function () { return arguments.length; }; log.push(async(...[1, 2],));\n\ + Promise.all([f(1), g(1, 2, 3), h(1, 2), h.length]).then(function (r) { log.push(r.join(',')); });"; + assert_eq!(log(src), "2 1,2,3,2"); + let mut r = realm(); + for src in ["async (...xs,) => xs", "async (a, ...xs,) => xs", "(...xs,) => xs", "(a, ...xs,) => xs", "(a,);", "(a, b,);"] { + syntax_error(&mut r, src); + } +} + #[test] fn async_functions_are_not_constructors_and_have_no_prototype() { let src = "async function f() {}\n\ diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f6a337d860..92516cc4b8 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -262,6 +262,17 @@ fn a_global_var_makes_its_own_property_over_an_inherited_one() { assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true))); } +#[test] +fn a_var_an_inherited_property_declared_does_not_stop_a_later_let() { + // Without the option, `var x` uses the inherited `x` and makes no own property, so a later + // run with the option may declare `x` with `let`. + let mut realm = Realm::new(); + assert_eq!(realm.run("Object.prototype.x = 1; 0"), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run("var x; delete this.x"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("let x = 2; x"), Ok(JsValue::Number(2.0))); +} + #[test] fn a_global_function_that_cannot_be_declared_declares_nothing() { let mut realm = es(); @@ -752,6 +763,37 @@ fn spread_stops_at_the_heap_limit_before_the_next_step_runs() { } } +#[test] +fn a_template_object_stays_within_the_heap_limit() { + // The template object's two arrays, the index name of each string and the `raw` property are + // reserved before they are made, so the heap stays within each limit tried. + let setup = "function t(s) { return s.length; } 0"; + let run = format!("t`{}`", (0..10).map(|i| format!("p{i}${{{i}}}")).collect::()); + let mut measure = Realm::with_options(es_options(), Limits::default()); + assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0))); + measure.interp().collect_garbage(); + let base = measure.interp().heap.bytes; + assert_eq!(measure.run(&run), Ok(JsValue::Number(11.0))); + let need = measure.interp().settled_heap_bytes() - base; + let mut stopped = 0; + for heap_bytes in (base..=base + need).step_by(4) { + let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() }); + if realm.run(setup).is_err() { + continue; + } + realm.interp().collect_garbage(); + let r = realm.run(&run); + stopped += usize::from(r.is_err()); + assert!( + matches!(&r, Ok(JsValue::Number(_))) || matches!(&r, Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap)), + "{heap_bytes}: {r:?}" + ); + let bytes = realm.interp().settled_heap_bytes(); + assert!(bytes <= heap_bytes, "{bytes} > {heap_bytes}"); + } + assert!(stopped > 0, "no limit stopped the run"); +} + #[test] fn spreading_other_values_is_a_type_error() { throws("[...1];", "TypeError"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 7224b0c122..f6e21e0224 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2670,8 +2670,16 @@ impl Interp { return self.push(Value::Object(id)); } let Some(t) = code.templates.get(i as usize) else { return internal("template out of range") }; - let strings = t.cooked.len().saturating_add(t.raw.len()); - self.reserve_heap(OBJECT_BYTES.saturating_mul(2).saturating_add(strings.saturating_mul(PROP_BYTES)))?; + // Two arrays, a property and an index name for each string, and the `raw` property. + let names = |n: usize| index_keys_bytes(n).saturating_sub(n.saturating_mul(KEY_ENTRY_BYTES)); + let props = t.cooked.len().saturating_add(t.raw.len()).saturating_add(1); + let bytes = OBJECT_BYTES + .saturating_mul(2) + .saturating_add(props.saturating_mul(PROP_BYTES)) + .saturating_add(names(t.cooked.len())) + .saturating_add(names(t.raw.len())) + .saturating_add(string_bytes(3)); + self.reserve_heap(bytes)?; let raw = self.frozen_array(&t.raw)?; // The raw array stays reachable while the template object is made. self.push(Value::Object(raw))?; @@ -3620,7 +3628,10 @@ impl Interp { for v in &code.vars { self.use_fuel()?; self.declare(var_env, v, None, configurable)?; - if on_global { + // Without ECMA-262 2015's scoping, a property the global object inherits declares the + // variable and no own property is made. Only a name with an own property is kept; + // `delete` removes the name with that property. + if on_global && self.get_own_property(self.global, v)?.is_some() { self.global_vars.insert(v.clone()); } } diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index d4ed2e8c4a..4430636d2d 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -51,6 +51,8 @@ struct Head { line_break: bool, /// The parentheses hold an `await` expression or the identifier `await`. awaits: bool, + /// A comma follows the last item in the parentheses. + trailing_comma: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -1313,6 +1315,13 @@ impl<'s> Parser<'s> { if head.is_some_and(|h| h.line_break) { return Err(self.error_at_offset(start.start, "a line break cannot come after 'async' in an async arrow function")); } + // No comma may follow a rest parameter (ECMA-262 2017 section 14.1). + if let Some(&last) = args.last() + && head.is_some_and(|h| h.trailing_comma) + && matches!(self.ast.expr(last), Some(Expr::Spread(_))) + { + return Err(self.error_at_offset(self.ast.expr_span(last).start, "a rest parameter must be the last parameter")); + } (self.arrow_items(args.clone())?, true) } _ => return Err(self.unexpected()), @@ -1517,14 +1526,14 @@ impl<'s> Parser<'s> { let async_head = news.is_empty() && self.async_ident.is_some_and(|a| a == expr); let line_break = self.tok.newline_before; let awaits = self.awaits; - let args = self.parse_arguments()?; + let (args, trailing_comma) = self.arguments()?; let span = Span::new(self.ast.expr_span(expr).start, self.prev_end); expr = match news.pop() { Some(new) => self.ast.push_expr(Expr::New { callee: expr, args }, Span::new(new.start, self.prev_end)), None => self.ast.push_expr(Expr::Call { callee: expr, args }, span), }; if async_head && self.at(Punct::Arrow) { - self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits }); + self.heads.insert(expr, Head { line_break, awaits: self.awaits != awaits, trailing_comma }); } } TokenKind::Punct(Punct::QuestionDot) => { @@ -1612,19 +1621,29 @@ impl<'s> Parser<'s> { } fn parse_arguments(&mut self) -> Result> { + Ok(self.arguments()?.0) + } + + /// An argument list, and whether a comma follows its last argument. + fn arguments(&mut self) -> Result<(Vec, bool)> { self.expect(Punct::LParen)?; let mut args = Vec::new(); + let mut trailing_comma = false; if !self.at(Punct::RParen) { loop { args.push(self.parse_element()?); // A comma may follow the last argument (ECMAScript 2017, section 12.3). - if !self.eat(Punct::Comma)? || self.at(Punct::RParen) { + if !self.eat(Punct::Comma)? { + break; + } + if self.at(Punct::RParen) { + trailing_comma = true; break; } } } self.expect(Punct::RParen)?; - Ok(args) + Ok((args, trailing_comma)) } fn parse_primary(&mut self) -> Result { @@ -1704,7 +1723,8 @@ impl<'s> Parser<'s> { } /// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow - /// function, which may also be `()` or end with `...name`; those two must come before `=>`. + /// function, which may also be `()`, end with `...name` or end with a comma; those three must + /// come before `=>`. fn parse_paren_or_arrow_head(&mut self) -> Result { let start = self.expect(Punct::LParen)?.span; let awaits = self.awaits; @@ -1723,8 +1743,11 @@ impl<'s> Parser<'s> { if !self.eat(Punct::Comma)? { break; } + // A comma may follow the last parameter (ECMA-262 2017 section 14.2), but not the + // last item of a parenthesized expression. if self.at(Punct::RParen) { - return Err(self.unexpected()); + head_only = true; + break; } } self.expect(Punct::RParen)?; @@ -1740,7 +1763,7 @@ impl<'s> Parser<'s> { }; let paren = self.ast.push_expr(Expr::Paren(inner), self.span_from(start)); if self.at(Punct::Arrow) { - self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits }); + self.heads.insert(paren, Head { line_break: false, awaits: self.awaits != awaits, trailing_comma: false }); } Ok(paren) } diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fcfeb7bf25..fc90beb905 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -436,7 +436,7 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), - TokenKind::String(units) => { + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => { let text = String::from_utf16_lossy(units); missing.contains(text.as_str()) || (strings_are_code && text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')).any(|word| missing.contains(word))) @@ -1155,6 +1155,15 @@ fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() { assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern)); } +#[test] +fn a_missing_name_in_a_template_that_can_run_as_code_skips() { + let missing: HashSet<&str> = ["Map"].into_iter().collect(); + let modern = Options { es2015: true, ..Options::default() }; + assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); + assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); +} + #[test] fn a_missing_name_in_code_skips() { assert!(skips(&["var m = new Map();"])); From a22c730c03e89ec97c037043dec337924ef188f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:21:28 -0800 Subject: [PATCH 075/533] Scripts: text edits refuse hidden or locked type, and lists start with the topmost frame - Text edits (contents, added text, character and paragraph attributes) throw Cannot edit with nothing changed when the frame, or a layer or group it is in, is hidden or locked. - Text added after a range that ends inside a character goes after that character, and styling an empty range changes nothing. - Point changes that wait are written before a call that is put back on failure, and before the points of another path are read, so a failed call does not drop them. - A new path's id is read exactly from the command's result. - A saved or Recent preset's rows above 1,000 read as 1,000, so file.new takes the preset as file.newPresets lists it. - textFrames lists type topmost first, as pageItems does on main; the tests and docs/mcp.md follow. --- crates/engine/src/cmd/newdoc.rs | 11 +++- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/paths.rs | 19 ++++--- crates/engine/src/script/dom/text.rs | 39 +++++++++----- crates/engine/src/tests/newdoc.rs | 19 +++++++ crates/engine/src/tests/script_dom_paths.rs | 22 ++++++++ crates/engine/src/tests/script_text.rs | 59 ++++++++++++++++++--- docs/mcp.md | 2 +- 8 files changed, 140 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4aad006ff1..6aabd654c3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -171,8 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, - /// Rows of a grid by column, in place of `columns` when more than 0. - #[serde(skip_serializing_if = "is_zero")] + /// Rows of a grid by column, in place of `columns` when more than 0 (a saved or Recent preset's + /// value above `MAX_ARTBOARDS` is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). @@ -594,6 +595,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1823b25a34..5537ab5d61 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -158,11 +158,13 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state. Point changes that wait in [`State`] are written +/// first, so a failure in `f` does not put them back. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } + flush(h)?; let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); h.dom.saving.set(true); let r = f(h); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 823ed46d41..ea57a3f49b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -164,13 +164,15 @@ fn same_path(a: Item, b: Item) -> bool { a.doc.uid == b.doc.uid && a.id == b.id } -/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. The +/// waiting point changes of another path are written first. fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { if let Some((waiting, subs)) = &*h.dom.pending.borrow() && same_path(*waiting, item) { return Ok(f(subs)); } + flush(h)?; read_path(h, item, |_, _, pd| f(&pd.subpaths)) } @@ -372,20 +374,17 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the JSON result of a command that made an object, read exactly, as the text creators +/// read it. +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, /// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -544,7 +543,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 6595cfb926..4a25a8300f 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -193,7 +193,7 @@ type Spans = [(usize, usize)]; #[derive(Default)] pub(in crate::script) struct TextState { frames: RefCell>, - /// A document's uid, the document, and the ids of its type objects in paint order. + /// A document's uid, the document, and the ids of its type objects, topmost first. list: RefCell>, /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. @@ -301,6 +301,15 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u }) } +/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing +/// changed, when the frame or a layer or group it is in is hidden or locked. +fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + edit_item(h, item, id, params) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -445,7 +454,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { return Ok(Data::Undefined); } let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; record(h, r.item, &index, s, e - s, &insert)?; Ok(Data::Undefined) } @@ -719,16 +728,17 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + // The place, and whether it is the end of a range, which rounds up to a character boundary. + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); @@ -741,13 +751,15 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // A place inside a character (between the two halves of a surrogate pair) moves to its edge. + let b = index.byte(at, after); + let at = index.text[..b].encode_utf16().count(); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -763,7 +775,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { ), }; let insert = format!("{lead}{contents}{trail}"); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; record(h, r.item, &index, at, 0, &insert)?; let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; let start = at + lead.encode_utf16().count(); @@ -1042,7 +1054,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; // A leading set on characters with auto leading fixes it even where auto gives that value. let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); - let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. + let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1060,7 +1073,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { super::atomically(h, |h| { for (start, end, leading) in &spans { let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); - edit_item(h, r.item, "text.setRangeStyle", &p)?; + edit_text(h, r.item, "text.setRangeStyle", &p)?; } Ok(()) })?; @@ -1072,7 +1085,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?; if let Attr::TextFont = attr { let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; @@ -1234,7 +1247,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - edit_item(h, r.item, id, &p)?; + edit_text(h, r.item, id, &p)?; Ok(Data::Undefined) } @@ -1250,7 +1263,7 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { get(link, doc_text_frames_impl) } -/// The ids of the document's type objects in paint order, kept while the document is unchanged. +/// The ids of the document's type objects, topmost first, kept while the document is unchanged. fn frame_ids(h: &Host, st: &DocState) -> Rc> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 89e050d68f..473077d8e6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -272,6 +272,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that +/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows. +#[test] +fn a_saved_preset_with_too_many_rows_reads_in_range() { + let mut s = Session::new(); + let prefs = json!({ + "newDocPresets": [ + {"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001}, + {"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0}, + ], + }); + s.apply_prefs(serde_json::from_value(prefs).unwrap()); + let saved = presets(&mut s, "Saved"); + assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]); + assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]); + s.execute("file.new", &saved[0]).unwrap(); + assert_eq!(boards(&s).len(), 4); +} + /// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest /// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names /// the limit in points and, when the document's units aren't points, in those units too. diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index edd359282e..06c4670e93 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1207,3 +1207,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// A point change made before a call that fails and is put back, here a new document whose +/// profile cannot be read, is kept. +#[test] +fn a_point_change_before_a_failed_new_document_is_kept() { + let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let (mut s, a, _) = doc(); + s.attach_new_doc_profiles(dir.clone()); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let out = log( + &mut s, + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ + try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", + ); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out, vec![json!("refused")]); + assert_eq!(s.documents().len(), 1); + assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); +} diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 7d70741e69..dcecba422f 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,13 +56,13 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -297,6 +297,49 @@ fn bad_text_paint_is_refused_without_a_change() { assert_eq!(paints(&s, id), runs); } +#[test] +fn hidden_or_locked_type_is_not_edited() { + let (mut s, id) = doc_with("abc"); + let (runs, text) = (paints(&s, id), plain(&s, id)); + for hide in ["t.locked = true;", "t.hidden = true;"] { + for edit in [ + "r.characters[1].fillColor = red;", + "r.size = 30;", + "r.contents = 'xyz';", + "r.characters.add('!');", + "r.justification = Justification.CENTER;", + ] { + let e = failure( + &mut s, + &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), + ); + assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + } + } + assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); +} + +#[test] +fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\ + var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", + ); + assert_eq!(plain(&s, id), "\u{1F600}!X"); + assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // An empty range there sits after the character too, and styling it changes nothing. + let runs = paints(&s, id); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\ + var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);", + ); + assert_eq!(out, vec![json!(0)]); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); @@ -504,7 +547,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -564,16 +607,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -658,7 +701,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/docs/mcp.md b/docs/mcp.md index a72b4cac53..793c599a3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2838,7 +2838,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a placed item's `file`, are not defined yet and read as `undefined`. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type - objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and + objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` From d2ae34dfca3e98304bd4c088535f642e710b6df0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:40:42 -0800 Subject: [PATCH 076/533] Tests: the host name check lists the AutoCAD export names The host adds ExportOptionsAutoCAD, the six AutoCAD enumerations and ExportType.AUTOCAD, and every_name_the_host_adds_has_a_row now finds a row for each. The AutoCAD export test checks that the DXF origin is within 1 mm of the art's left edge on either side of zero. --- crates/engine/src/tests/script_save_open.rs | 2 +- .../engine/tests/it/script_host_vs_scriptcheck.rs | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 81283c528a..5b36ffc5da 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -225,7 +225,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. - assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); + assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 5960d189de..7f6afcf448 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -142,6 +142,13 @@ const INSIDE: &[(&str, &str)] = &[ "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ UserInteractionLevel", ), + ("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"), + ("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"), + ("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"), + ("AutoCADExportFileFormat.", "DWG DXF"), + ("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"), + ("AutoCADRasterFormat.", "JPEG PNG"), + ("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ @@ -149,7 +156,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), - ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), @@ -160,8 +167,8 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG \ + ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. From f6a6cf35183118924bb9c391c522351571b3c479 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:25:22 -0800 Subject: [PATCH 077/533] Tests: a template key naming eval runs strings as code in the test262 runner runs_strings_as_code matched a string token naming eval, Function or constructor, but not a template, so this[`eval`](`new Map()`) did not skip when Map is missing. Templates now match the same names, as needs_missing_builtin_in already reads both forms. --- crates/js/tests/test262.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index fc90beb905..77de4c13f6 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -446,12 +446,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: } /// The tokens can run a string as code: they name `eval`, `Function` or a `constructor` property, -/// as an identifier or as a string key (`this["eval"]`), called directly or through an alias. +/// as an identifier or as a string or template key (`this["eval"]`), called directly or through an alias. /// `Function.prototype` alone does not count. fn runs_strings_as_code(tokens: &[Token]) -> bool { const RUNNERS: [&str; 3] = ["eval", "Function", "constructor"]; tokens.iter().enumerate().any(|(i, t)| match &t.kind { - TokenKind::String(units) => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), + TokenKind::String(units) | TokenKind::Template { cooked: units, .. } => RUNNERS.iter().any(|r| r.encode_utf16().eq(units.iter().copied())), TokenKind::Ident(name) if name == "eval" || name == "constructor" => true, TokenKind::Ident(name) if name == "Function" => { let prototype = tokens.get(i + 1).is_some_and(|d| d.is_punct(Punct::Dot)) @@ -1161,6 +1161,9 @@ fn a_missing_name_in_a_template_that_can_run_as_code_skips() { let modern = Options { es2015: true, ..Options::default() }; assert!(needs_missing_builtin_in(&[r#"eval("new Map()");"#], &missing, &modern)); assert!(needs_missing_builtin_in(&["eval(`new Map()`);"], &missing, &modern)); + // A template key names the runner, as a string key does. + assert!(needs_missing_builtin_in(&["this[`eval`](`new Map()`);"], &missing, &modern)); + assert!(needs_missing_builtin_in(&[r#"var F = this[`Function`]; F("return new Map()")();"#], &missing, &modern)); assert!(!needs_missing_builtin_in(&["assert(true, `a Map`);"], &missing, &modern)); } From f5090591bc05bd272612bcde7f4e6ac93cf9f60f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:11:44 -0800 Subject: [PATCH 078/533] Scripts: setActiveArtboardIndex keeps the artboard when one is inserted before it An assignment that chooses the artboard already active by default now records it, so a later insert moves it to the next index. hasSelectedArtwork = true counts only the art it would add toward the 10,000-object limit. --- crates/engine/src/script/dom/layers.rs | 30 +++++++++++++---------- crates/engine/src/tests/script_dom.rs | 33 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 75938cc6df..3da57533fb 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -297,29 +297,30 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let (ids, total) = with_doc(h, doc, |_, st| { + let (ids, over) = with_doc(h, doc, |_, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; if !on { - return (selected.iter().copied().filter(inside).collect::>(), 0); + return (selected.iter().copied().filter(inside).collect::>(), false); } let locks = st.doc.locked_artboards(); let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); for o in art { - if selected.len() + ids.len() > MAX_LISTED { - break; + if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + continue; } - if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { - have.insert(o); - ids.push(o); + // Only art that would be added counts toward the limit. + if selected.len() + ids.len() >= MAX_LISTED { + return (ids, true); } + have.insert(o); + ids.push(o); } - let total = selected.len() + ids.len(); - (ids, total) + (ids, false) }); - if total > MAX_LISTED { + if over { return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); } if ids.is_empty() { @@ -1291,16 +1292,19 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer { } /// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the -/// document changes, and no command runs. +/// document changes, and no command runs. The artboard is kept by its id even when it is already +/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later +/// in the run moves it to the next index instead of taking its place. fn boards_set_active(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); let i = board_index_arg(arg(a, 1), len, "index")?; - if i != now { + { let mut s = h.session.borrow_mut(); let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); - drop(s); + } + if i != now { let mut moved = h.dom.active_artboards.borrow_mut(); if !moved.contains(&doc.uid) { moved.push(doc.uid); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e2d6a25442..6e02f9dca9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2109,6 +2109,24 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it +/// moves it to the next index, and the report gives that index. +#[test] +fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() { + let (mut s, _, _) = doc(); + assert_eq!(s.active().unwrap().active_artboard, None); + let first = s.active().unwrap().doc.artboards[0].id; + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); @@ -2193,6 +2211,21 @@ fn has_selected_artwork_keeps_the_rest_of_the_selection() { assert_eq!(sel.guides.len(), 1); } +/// The selection limit counts only the art an assignment would add: a layer with nothing to add +/// changes nothing beside a selection already at the limit, and one with art to add throws. +#[test] +fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { + let (mut s, a, _) = doc(); + run(&mut s, "app.activeDocument.layers.add();").unwrap(); + // A selection of 10,001 entries, as the limit counts them. + s.active_mut().unwrap().selection.objects = vec![a; 10_001]; + run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_001); + s.active_mut().unwrap().selection.objects = vec![a; 10_000]; + let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;"); + assert!(e.contains("at most 10000"), "{e}"); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); From 19e1e5126831c929264f6f36bd850d56ed51878c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:07:37 -0800 Subject: [PATCH 079/533] Scripts: a host constructor called with new must give an object A host class constructor that returned a number, string or other primitive made new return it. new now throws a TypeError for a primitive result. --- crates/js/src/host_tests.rs | 9 +++++++++ crates/js/src/interp.rs | 3 +++ 2 files changed, 12 insertions(+) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..3f4bf1bf13 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -715,6 +715,15 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0))); + with_thing(&mut r, Some(make)); + r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); +} + #[test] fn objects_of_a_host_class_report_its_available_members_as_their_own() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 9edea621c5..d938ac9eb2 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2952,6 +2952,9 @@ impl Interp { let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); self.constructing = was; let v = v?; + if !matches!(v, Value::Object(_)) { + return Err(self.type_error("a constructor gave a value that is not an object")); + } if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? From 3650f71cdcacc585f0f59f02c1913ca5ab994f1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:37:40 -0800 Subject: [PATCH 080/533] Scripts: removeAll on a compound path's paths keeps the compound path pathItems.removeAll() on a compound path deleted the compound path with its last path, which made its handle stale. It now stays, empty, as remove() on its last path leaves it. --- crates/engine/src/script/dom/layers.rs | 2 +- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3da57533fb..e5f371046e 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -726,7 +726,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6e02f9dca9..0742b3ff28 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1329,6 +1329,24 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path, +/// empty, as `remove()` on its last path does. +#[test] +fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]); + assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1); +} + #[test] fn move_and_duplicate_refuse_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); From 244472e98da464f34574fb0138a490261f32d43c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:53:42 -0800 Subject: [PATCH 081/533] Recolor Artwork: the library swatch that decides Tint takes the Global Adjust first With Limit to Library, recolor.apply adjusts a row's new color before it snaps it to the library. The dialog looked up the library swatch with the unadjusted color, so a red row with Brightness -50 could show the Tint slider for a red spot swatch while the art took a dark red process swatch. The lookup now applies the Global Adjust first, as recolor.apply does. --- crates/ui-egui/src/dialogs/recolor.rs | 11 ++++++----- crates/ui-egui/src/tests/recolor.rs | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index b5b51a89ab..8c3dec166e 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2081,10 +2081,11 @@ fn mode_id(m: Mode) -> String { } /// What decides how `recolor.apply` links the art of the rows to swatches, read once for all rows: -/// Limit to Library's palette and color swatches, and the names of the color group's global swatches -/// that OK's rewrite gives another color ([`rewritten_to_another`]). +/// Limit to Library's palette and color swatches, the Global Adjust, and the names of the color +/// group's global swatches that OK's rewrite gives another color ([`rewritten_to_another`]). struct RowLinks { library: Option<(vectorcraft_color::recolor::Palette, Vec)>, + adjust: GlobalAdjust, rewritten: Vec, } @@ -2093,14 +2094,14 @@ impl RowLinks { let lib = d.str("limitTo"); let library = if lib.is_empty() { None } else { limit_palette_before_preview(app, &lib).zip(limit_swatches(app, &lib)) }; let rewritten = rewritten_to_another(app, d, library.as_ref().map(|(palette, _)| palette)); - Self { library, rewritten } + Self { library, adjust: global_adjust(adjust_values(d)), rewritten } } /// The library swatch (Limit to Library) that `recolor.apply` gives new color `c`: the first - /// swatch of the library color nearest `c`. + /// swatch of the library color nearest `c` after the Global Adjust. fn library_swatch(&self, c: &Color) -> Option<&vectorcraft_color::swatch::Swatch> { let (palette, swatches) = self.library.as_ref()?; - let near = palette.nearest(*c); + let near = palette.nearest(self.adjust.apply(*c)); swatches.iter().find(|w| w.paint.color() == Some(near)) } } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 6086f0de26..847b729ac4 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -480,6 +480,29 @@ fn a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch() { assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "C").is_some(), "the CMYK sliders"); } +/// With Limit to Library and a Global Adjust, a row shows Tint only when the library's swatch +/// nearest its adjusted new color is a spot color: `recolor.apply` adjusts the color before it +/// snaps it to the library. +#[test] +fn a_global_adjust_picks_the_library_swatch_that_decides_the_tint() { + let mut app = app(); + let lib = library_of( + &mut app, + &[ + json!({"name": "Red Ink", "color": {"c": 0, "m": 1, "y": 1, "k": 0}, "spot": true}), + json!({"name": "Dark Red", "color": {"c": 0, "m": 1, "y": 1, "k": 0.5}}), + ], + ); + art(&mut app, &["cmyk 0 100 100 0"]); + let mut h = assign_harness(app, json!({"library": lib})); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_some(), "without an adjust the row takes Red Ink: Tint"); + set(h.state_mut(), "globalAdjust", json!({"brightness": -50.0})); + h.run_steps(2); + assert!(h.query_by_role_and_label(egui::accesskit::Role::Slider, "T").is_none(), "the darker red snaps to the process swatch: no Tint"); +} + /// A row picked from a spot swatch of the color group being edited shows Tint while OK leaves the /// swatch its color, and not once another row gives the swatch a new color: `recolor.apply` then /// links the row's art to nothing. From 7369b03a7e4a0d1da6e5da5588aeb11b60cfd208 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:15:00 -0800 Subject: [PATCH 082/533] Recolor Artwork: OK on a reopened Color Picker keeps the row's swatch A row picked from a global or spot swatch lost its swatch and tint when the Color Picker was opened on it again and closed with OK and no edit. In a CMYK document the picker converted the swatch's RGB color to CMYK, which no longer matched the row. The picker now opens with the row's swatch, so OK without an edit keeps the swatch in its own color model. --- crates/ui-egui/src/dialogs/color_picker.rs | 7 ++++++ crates/ui-egui/src/tests/recolor.rs | 29 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 32d1b1a565..d78e47596a 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -342,6 +342,13 @@ pub(super) fn over_recolor(parent: &Dialog, color: Color, row: usize, swatches: let mut d = Dialog::new(KIND, fields); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(color)); + // A row picked from a global or spot swatch keeps that swatch, in its own color model, while + // OK leaves its color as it is. + let row_swatch = parent.fields.get("rows").and_then(|r| r.get(row)).and_then(|r| r.get("swatch")); + if let Some(w) = row_swatch.filter(|w| w.get("name").is_some_and(Value::is_string)) { + let picked = json!({"name": w["name"], "library": w["library"], "color": color_json(&color), "keep": true}); + d.fields.insert(PICKED_SWATCH.into(), picked); + } d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); d } diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 847b729ac4..d9d7d33804 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -2052,6 +2052,35 @@ fn a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library() { let _ = std::fs::remove_file(&path); } +/// In a CMYK document, a row picked from an RGB spot swatch keeps the swatch and its tint when the +/// Color Picker is opened on it again and closed with OK and no edit: the picker does not convert +/// the swatch's color to CMYK. +#[test] +fn reopening_the_picker_on_a_swatch_row_keeps_the_swatch() { + use egui::accesskit::Role; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200, "colorMode": "cmyk"})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": "#ff0000", "spot": true})).unwrap(); + art(&mut app, &["cmyk 0 100 0 0"]); + let mut h = assign_harness(app, json!({})); + let mut rows = field(h.state(), "rows"); + rows[0]["to"] = json!(ColorKey::of(&Color::rgb(1.0, 0.0, 0.0)).to_string()); + rows[0]["swatch"] = json!({"name": "Ink", "library": "document"}); + rows[0]["tint"] = json!(40.0); + set(h.state_mut(), "rows", rows.clone()); + h.run_steps(2); + row_context_menu(&mut h, 0); + h.get_by_label(" Pick from Swatches").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + h.get_by_role_and_label(Role::Button, "OK").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("recolor")); + let row = field(h.state(), "rows")[0].clone(); + assert_eq!((&row["swatch"], &row["tint"]), (&rows[0]["swatch"], &rows[0]["tint"]), "{row}"); +} + /// Whether the dialog's button `name` is disabled. fn disabled(h: &egui_kittest::Harness<'_, VectorcraftApp>, name: &str) -> bool { h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled() From 8330a6d8f0045d6b27ea6ee2b529658599ac3feb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:53:14 -0800 Subject: [PATCH 083/533] Scripts: transforms keep stroke-only and tiny changes, and edits keep the current layer - translate, rotate, resize and transform: a move of any size other than 0 runs; a changeLineWidths scale with changePositions false throws an error that says it is not available yet instead of changing nothing; the scale a matrix gives for changeLineWidths is taken past the range of a number; a transformation whose bounds reach past the canvas is kept when the transformed object itself stays inside it. - An edit of a page item puts back the current layer that selecting the item changed (layer.setCurrent), and an edit whose selection cannot be put back is undone with it. - addDocument starts from the built-in preset of the profile's category, not a saved preset with the same name (file.new and file.newPresets.save take presetCategory), and refuses previewMode OverprintPreview before it makes a document. - The values assigned to a run's DocumentPresets hold at most 64 MiB. - zOrder leaves out the ruler guides at the top of a layer when it checks whether the item is already at the front. - concatenateMatrix rounds a sum next to the largest number once, and getRealPreference rounds a 0x, 0o or 0b number once. - On Windows, the check that a New Document profile or recovery lock is still the file that was opened does not follow a link at its path. - JavaScript: new on a host constructor that gives a value other than an object throws a TypeError, and an array method on a host object that takes a class with an indexer during the call visits the rest of its elements. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 22 ++++-- crates/engine/src/cmd/recovery.rs | 16 +++- crates/engine/src/script/dom.rs | 78 ++++++++++++++++--- crates/engine/src/script/dom/matrix.rs | 24 +++++- crates/engine/src/script/dom/preferences.rs | 42 +++++++++- crates/engine/src/script/dom/transform.rs | 29 +++++-- crates/engine/src/tests/script_dom.rs | 53 +++++++++++++ crates/engine/src/tests/script_dom_prefs.rs | 25 +++++- .../engine/src/tests/script_dom_transform.rs | 48 +++++++++++- crates/js/src/builtins/array.rs | 4 +- crates/js/src/host_classes.rs | 5 +- crates/js/src/host_tests.rs | 33 ++++++++ crates/js/src/interp.rs | 5 ++ docs/mcp.md | 9 ++- 15 files changed, 356 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 99fdba20bc..c62ce14531 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 617a4f8b16..8749fdfbdf 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -799,6 +799,18 @@ pub fn find(s: &Session, name: &str) -> Option { .or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name))) } +/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names +/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without +/// `preset`. +fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))) +} + impl Session { /// New Document's starting settings: Letter in Preferences ▸ Units ▸ General. fn default_settings(&self) -> DocSettings { @@ -812,10 +824,7 @@ const RECENT: usize = 12; /// `file.new`: a new document from a preset and/or explicit settings. pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { const C: &str = "file.new"; - let base = match str_param(p, "preset") { - Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); @@ -900,10 +909,7 @@ fn save(s: &mut Session, p: &Value) -> Result { .map(str::trim) .filter(|n| !n.is_empty() && n.chars().count() <= 64) .ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?; - let base = match str_param(p, "preset") { - Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?, - None => s.default_settings(), - }; + let base = preset_param(s, p, C)?; let mut preset = base.with_params(p, C)?; preset.name = name.to_string(); let saved = &mut s.prefs.new_doc_presets; diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 7719496fac..c55ad05ca3 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -419,7 +419,8 @@ impl FolderStore { /// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on /// Windows they must be the same file (volume serial number and file index); elsewhere `path` - /// must exist. When either file can't be read, it does not. + /// must exist. A link at `path` is not followed, so it names the link and not `file`. When + /// either file can't be read, it does not. pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool { #[cfg(unix)] { @@ -431,8 +432,19 @@ impl FolderStore { } #[cfg(windows)] { + use std::os::windows::fs::OpenOptionsExt as _; + // FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and + // FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path` + // opens one. + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; let opened = file.try_clone().and_then(same_file::Handle::from_file); - match (opened, same_file::Handle::from_path(path)) { + let named = std::fs::OpenOptions::new() + .read(true) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .and_then(same_file::Handle::from_file); + match (opened, named) { (Ok(a), Ok(b)) => a == b, _ => false, } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 27a95eb321..3ab67b8942 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -91,13 +91,16 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made with the bytes +/// they hold. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, presets: RefCell>>, + /// The bytes the values assigned to `presets` hold ([`MAX_PRESET_BYTES`]). + preset_bytes: Cell, } impl State { @@ -541,17 +544,31 @@ fn done_unless_refused(r: std::result::Result) -> std::result:: /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. +/// hidden or locked; the current layer, which selecting art changes, is put back too while it is +/// still a layer that can be edited. With `keep_selection`, `f`'s commands and the putting back are +/// kept together or put back together ([`atomically`]), so an error in putting the selection back +/// leaves the document as it was. fn on_doc( h: &Host, uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before) = { + if keep_selection { atomically(h, |h| on_doc_once(h, uid, true, f)) } else { on_doc_once(h, uid, false, f) } +} + +/// [`on_doc`] without its savepoint. +fn on_doc_once( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before, layer) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - (index, s.active_index(), s.documents()[index].selection.clone()) + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.layer_rows.clone())) }; let switch = active != Some(index); if switch { @@ -567,6 +584,7 @@ fn on_doc( if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); } + restored = restored.and(restore_layer(h, uid, layer)); } // The document that was active is active again before any error is given: `f`'s error first, // then the selection's, then the switch back's. @@ -580,6 +598,30 @@ fn on_doc( Ok(v) } +/// Makes the layer `layer` gives (the current layer and the highlighted Layers panel rows before an +/// edit) current in the active document `uid` again, when selecting art made another layer current +/// and that layer is still one that can be edited. It runs `layer.setCurrent`, and `layer.highlight` +/// for rows that keep that layer current, so a replay of the run's commands ends with the same +/// current layer. A refused command changes nothing ([`done_unless_refused`]). +fn restore_layer(h: &Host, uid: u64, layer: (Option, Vec)) -> std::result::Result<(), HostError> { + let (was, rows) = layer; + let (back, keeps) = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + let back = was.filter(|l| st.active_layer != Some(*l) && st.doc.node(*l).is_some_and(|n| n.is_layer()) && st.doc.is_editable(*l)); + let keeps = rows.last().is_some_and(|r| back.is_some() && st.doc.layer_containing(*r) == back); + (back, keeps) + }; + let Some(back) = back else { return Ok(()) }; + if !done_unless_refused(command(h, "layer.setCurrent", &json!({"id": back.0})))? { + return Ok(()); + } + if keeps && rows != [back] { + done_unless_refused(command(h, "layer.highlight", &json!({"ids": rows.iter().map(|r| r.0).collect::>()})))?; + } + Ok(()) +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -808,7 +850,10 @@ impl NewDoc<'_> { let mode = match d { Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", - Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + // Overprint Preview is a view of the whole app, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => { + return Err(HostError::Error("previewMode OverprintPreview is not available yet".into())); + } _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), }; p.insert("previewMode".into(), json!(mode)); @@ -917,9 +962,11 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), } // The document starts from the first preset of the profile's category (Print: Letter). + // It is looked up in that category, so a saved preset of the same name is not used instead. let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); - if let Some(first) = first { + if let (Some(first), Some(category)) = (first, profile) { p.insert("preset".into(), json!(first.name)); + p.insert("presetCategory".into(), json!(category)); } p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { @@ -964,6 +1011,9 @@ fn new_preset(h: &Host) -> Answer { /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; +/// The most bytes the values assigned to one run's `DocumentPreset` objects can hold together. +const MAX_PRESET_BYTES: u64 = 64 << 20; + /// The settings a `DocumentPreset` has, each a property a script reads and assigns. const PRESET_FIELDS: &[&str] = &[ "artboardLayout", @@ -1011,11 +1061,20 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let l = link.clone(); let set: HostFunction = Rc::new(move |a: Vec| { let h = current(&l)?; - let value = arg(&a, 1).clone(); - h.charge_call(16 + data_size(&value))?; + let size = data_size(arg(&a, 1)); + h.charge_call(16 + size)?; let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; + // The run's presets keep their values outside the script's heap: the value replaced is + // taken off what they hold before the new one is counted. + let old = fields.iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v)); + let held = h.dom.preset_bytes.get().saturating_sub(old).saturating_add(size); + if held > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("a script's DocumentPresets can hold at most {} MiB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(held); + let value = arg(&a, 1).clone(); match fields.iter_mut().find(|(k, _)| k == key) { Some((_, v)) => *v = value, None => fields.push((key.to_string(), value)), @@ -1786,9 +1845,10 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } + // The ruler guides at the top of a layer stay above its art, as Arrange keeps them. let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(|c| vectorcraft_doc::Node::guide_run_start(c))).unwrap_or(0); (at.map(|(_, i, _)| i), count) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 99b0a9aa05..d2ca769913 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -96,15 +96,19 @@ fn then(m: Matrix, n: Matrix) -> Matrix { } /// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only term that is not 0, the sum is taken as numbers are. Otherwise the -/// products are summed past the range of a number and rounded at the end, so a finite value is not -/// lost to a product too large or too small for a number. +/// normal numbers is the only term that is not 0, the sum is taken as numbers are, unless adding +/// `t` to the rounded sum of the products can come within a step of 2^1024. Otherwise the products +/// are summed past the range of a number and rounded at the end, so a finite value is not lost to +/// a product too large or too small for a number, and a sum is not taken past the largest number, +/// or kept below it, by a rounding on the way. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; - if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + let near_overflow = |v: f64| v.abs() >= pow2(1023); + let overflow_safe = t == 0.0 || !(near_overflow(plain) || near_overflow(plain + t)); + if plain.is_finite() && overflow_safe && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return plain + t; } // Each product is split into its rounded value and the part that rounding drops, both exact. @@ -357,6 +361,18 @@ fn determinant(m: Matrix) -> Wide { products_difference(m[0], m[3], m[1], m[2]) } +/// The square root of the size of `m`'s determinant: the factor by which `m` scales lengths on +/// average. It is infinite only when that factor is too large for a number. +pub(super) fn area_scale(m: Matrix) -> f64 { + let d = determinant(m); + let (mut v, mut e) = (d.m.abs(), d.e); + if e % 2 != 0 { + v *= 2.0; + e -= 1; + } + Wide::new(v.sqrt(), e / 2).value() +} + pub(super) fn singular(m: Matrix) -> bool { determinant(m).m == 0.0 } diff --git a/crates/engine/src/script/dom/preferences.rs b/crates/engine/src/script/dom/preferences.rs index e1c25e387e..31fa78682b 100644 --- a/crates/engine/src/script/dom/preferences.rs +++ b/crates/engine/src/script/dom/preferences.rs @@ -123,9 +123,7 @@ fn text_number(t: &str) -> f64 { _ => 0, }; if radix != 0 { - let digits = t.get(2..).unwrap_or(""); - let whole = digits.chars().try_fold(0.0_f64, |n, c| c.to_digit(radix).map(|d| n * f64::from(radix) + f64::from(d))); - return whole.filter(|_| !digits.is_empty()).unwrap_or(f64::NAN); + return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN); } match t.strip_prefix(['+', '-']).unwrap_or(t) { "Infinity" => { @@ -140,6 +138,44 @@ fn text_number(t: &str) -> f64 { } } +/// The whole number `digits` writes in base `radix` (16, 8 or 2), rounded once to the nearest +/// number, ties to the even one, and infinite past the largest; `None` when it is empty or holds a +/// character that is not a digit of that base. +fn radix_number(digits: &str, radix: u32) -> Option { + if digits.is_empty() { + return None; + } + let width = radix.trailing_zeros(); + // The first 64 bits from the leading 1, how many bits come after them, and whether any of + // those is 1. + let (mut top, mut taken, mut past, mut sticky) = (0u64, 0u32, 0u64, false); + for c in digits.chars() { + let d = c.to_digit(radix)?; + for bit in (0..width).rev().map(|i| (d >> i) & 1 == 1) { + if taken == 0 && !bit { + continue; + } + if taken < 64 { + top = (top << 1) | u64::from(bit); + taken += 1; + } else { + past = past.saturating_add(1); + sticky |= bit; + } + } + } + if taken <= 53 { + return Some(top as f64); + } + // Keep 53 bits; the dropped ones round them to the nearest, ties to even. + let drop = taken - 53; + let (kept, rest, half) = (top >> drop, top & ((1u64 << drop) - 1), 1u64 << (drop - 1)); + let up = rest > half || (rest == half && (sticky || kept & 1 == 1)); + let kept = kept + u64::from(up); + let exp = i32::try_from(u64::from(drop).saturating_add(past)).unwrap_or(i32::MAX).min(2000); + Some(kept as f64 * 2f64.powi(exp)) +} + #[allow(clippy::cast_precision_loss)] fn as_number(v: &ScriptPreference) -> f64 { match v { diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 2a3ff3ec6e..3f056589b1 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -18,7 +18,8 @@ //! that says so. //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale -//! with it, as Scale Strokes & Effects does); any other value throws an error that says so. +//! with it, as Scale Strokes & Effects does); any other value, and a scale other than 100 with +//! positions left as they are, throws an error that says so. //! - A locked object, one inside a locked layer or group, a group that holds one, and an object on //! a locked artboard are refused with nothing changed, and so are a scale of 0, a matrix whose //! determinant is 0 and a transformation that would take the object past the canvas. @@ -78,8 +79,10 @@ fn line_widths(d: &Data, m: Matrix) -> std::result::Result { Data::Undefined => return Ok(false), d => number(d, "changeLineWidths")?, }; - let own = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * 100.0; - if (lw - own).abs() <= 1e-9 * own.max(1.0) { + // The determinant is taken past the range of a number, so a scale whose square is too large + // for one still has its own value. + let own = matrix::area_scale(m) * 100.0; + if own.is_finite() && (lw - own).abs() <= 1e-9 * own.max(1.0) { return Ok((own - 100.0).abs() > 1e-9); } if (lw - 100.0).abs() <= 1e-9 { @@ -118,6 +121,16 @@ fn on_page(m: Matrix, o: Point) -> Affine { Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) } +/// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol +/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. +fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { + d.node(id).is_some_and(|n| { + let mut n = n.clone(); + n.transform(xf, false); + n.geometric_bounds_with(&d.symbol_boxes()).is_none_or(crate::sanity::rect_in_range) + }) +} + /// Applies `m` (Y up) to the item `this` names, about the point `about` names (`None`: the matrix /// acts as a move, which needs no point), with `opts`. fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) -> Answer { @@ -152,14 +165,20 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); + if opts.strokes && !opts.objects { + return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); + } if let Some(r) = bounds.filter(|_| opts.objects) { + // The transformed corners of the bounds hold the transformed object. When one of them is + // past the canvas, the transformed object itself is measured. let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; - if corners.iter().map(|p| xf * *p).any(|p| !(p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD)) { + let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; + if !corners.iter().all(|p| inside(xf * *p)) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { return Err(HostError::Range("the transformation would take the object past the canvas".into())); } } let c = xf.as_coeffs(); - let identity = c.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(v, i)| (v - i).abs() <= 1e-12); + let identity = xf == Affine::IDENTITY; let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; if changes { let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 10de309e4d..4603599578 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -856,6 +856,59 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); } +#[test] +fn a_startup_preset_uses_its_own_size_beside_a_saved_preset_of_the_same_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 300, "height": 200})).unwrap(); + let first = crate::cmd::newdoc::category(&s, "Print").unwrap().remove(0); + assert_eq!(first.name, "Letter"); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height]);"); + assert_eq!((out[0][0].as_f64(), out[0][1].as_f64()), (Some(first.width), Some(first.height)), "{out:?}"); +} + +#[test] +fn overprint_preview_is_refused_before_a_document_is_made() { + let mut s = Session::new(); + let e = + failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"); + assert!(e.contains("OverprintPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); +} + +#[test] +fn document_presets_hold_a_limited_amount_of_data() { + let mut s = Session::new(); + // A 4 MiB string: replacing one preset's value does not add up, 17 presets holding it do. + let out = log( + &mut s, + "var t = 'x'; for (var k = 0; k < 22; k++) t += t; var p = new DocumentPreset();\ + for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);", + ); + assert_eq!(out, vec![json!(4 << 20)]); + let e = failure( + &mut s, + "var t = 'x'; for (var k = 0; k < 22; k++) t += t;\ + for (var k = 0; k < 17; k++) { var p = new DocumentPreset(); p.title = t; }", + ); + assert!(e.contains("DocumentPresets can hold at most"), "{e}"); +} + +#[test] +fn moving_art_on_another_layer_keeps_the_current_layer() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.active().unwrap().current_layer().unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let b = s.active().unwrap().current_layer().unwrap(); + assert_ne!(a, b); + rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + s.active_mut().unwrap().active_layer = Some(a); + log(&mut s, "var i = app.activeDocument.pageItems[0]; i.left = i.left + 5; i.translate(5, 0);"); + assert_eq!(s.active().unwrap().current_layer(), Some(a)); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fa01766d63..d51b66336d 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -201,8 +201,15 @@ fn missing_keys_read_as_empty_values_and_getters_convert() { vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\ vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\ var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\ - p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));", + p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));\ + p.setStringPreference('n', '0x200000000000018'); var r = [p.getRealPreference('n') === Math.pow(2, 57) + 32];\ + p.setStringPreference('n', '0x' + new Array(301).join('f')); r.push(String(p.getRealPreference('n')));\ + p.setStringPreference('n', '0b' + new Array(60).join('0') + '1' + new Array(53).join('0') + '1'); r.push(p.getRealPreference('n') === Math.pow(2, 53));\ + vc.log(r);", ); + // Each whole number in base 16, 8 or 2 is rounded once: 2^57 + 24 to 2^57 + 32, 1,200 bits to + // Infinity, and 2^53 + 1 after leading zeros to 2^53 (ties to even). + assert_eq!(out.pop(), Some(json!([true, "Infinity", true]))); assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN"))); assert_eq!( out, @@ -417,6 +424,22 @@ fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_numbe ); } +#[test] +fn a_concatenated_translation_next_to_the_largest_number_is_rounded_once() { + let mut s = Session::new(); + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var a = Math.pow(2, 969), b = Math.pow(2, 970);\ + function tx(f, t) { try { return app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, f]), mat([1, 0, 1, 1, t, 0])).mValueTX === Number.MAX_VALUE; }\ + catch (e) { return e.name; } }\ + vc.log(tx(-a, b)); vc.log(tx(a, a));", + ); + // MAX + 2^969 is below the halfway point to 2^1024, and MAX + 2^970 is that point, which rounds + // to 2^1024. + assert_eq!(out, vec![json!(true), json!("RangeError")]); +} + #[test] fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index 1be3046209..b861716b35 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -146,11 +146,55 @@ fn transforms_that_change_nothing_add_no_undo_step() { &mut s, "var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\ i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\ - i.translate(7000000, 0, false, false, false, false);", + i.translate(7000000, 0, false, false, false, false);\ + i.transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 100);", ); assert_eq!(undo_steps(&s), steps); } +#[test] +fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() { + let (mut s, _, _) = doc(); + let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 70);"; + let e = failure(&mut s, call); + assert!(e.contains("other than 100 or the scale itself"), "{e}"); +} + +#[test] +fn a_move_too_small_to_round_away_moves_the_object() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0], l = i.left; i.translate(5e-13, 0); vc.log(i.left > l);"); + assert_eq!(out, vec![json!(true)]); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // A diagonal line through the origin, 0.6 of the canvas limit out each way. + let a = 0.6 * crate::MAX_COORD; + let line = NodeId(s.execute("shape.line", &json!({"x1": -a, "y1": a, "x2": a, "y2": -a})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + // On the page (Y down), x' = x + y about the center: the line becomes upright at x = 0, while + // a corner of its bounds would go to 1.2 times the limit. + log( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -1, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.width() < 1e-6 && (r.height() - 2.0 * a).abs() < 1e-3, "{r:?}"); + // The same shear twice takes the line itself past the canvas. + let e = failure( + &mut s, + "var m = {mValueA: 1, mValueB: 0, mValueC: -2, mValueD: 1, mValueTX: 0, mValueTY: 0};\ + app.activeDocument.pageItems[0].transform(m);", + ); + assert!(e.contains("past the canvas"), "{e}"); +} + #[test] fn locked_art_and_art_on_a_locked_artboard_are_refused() { let (mut s, a, b) = doc(); @@ -208,6 +252,8 @@ fn bad_arguments_throw_and_change_nothing() { ("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"), ("rotate(5, true, true, true, true, 3)", "Transformation value"), ("resize(1e9, 1e9)", "past the canvas"), + // Stroke weights cannot scale while the object stays where it is. + ("resize(50, 50, false, false, false, false, 50)", "with changePositions false is not available yet"), ] { let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); assert!(e.contains(says), "{call}: {e}"); diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 3b6806ea20..54b74464b9 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -174,8 +174,10 @@ impl Indices { if self.lo >= self.hi { return Ok(None); } + // The object may have become one of a host class with an indexer meanwhile, whose + // elements are not properties: the rest of the range is then visited index by index. if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) { - self.sparse = Some(self.gather(interp)?); + self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { Some(self.gather(interp)?) }; } let k = match &mut self.sparse { None if self.ascending => self.lo, diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..320207b958 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -145,13 +145,16 @@ impl Interp { if let Some(&id) = self.host_objects.get(&made) && is_made(&self.heap, &self.host_classes, id, &made) { - // An object of another class of the family becomes one of `class`. + // An object of another class of the family becomes one of `class`. Its indexer and the + // indices its prototypes hold can change with it, so a list of the indices it has is + // made again ([`crate::heap::Heap::index_epoch`]). let o = self.object_mut(id)?; if let Class::Host(h) = &mut o.class && h.class != class { h.class = class; o.proto = Some(proto); + self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1); } return Ok(Value::Object(id)); } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index be840c6ddc..b61e037171 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -676,6 +676,39 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + with_thing(&mut r, Some(make)); + let out = r.run("var e; try { new Thing(); } catch (x) { e = x; } [e instanceof TypeError, typeof Thing()].join()").unwrap(); + assert_eq!(out, JsValue::String("true,undefined".into())); +} + +#[test] +fn an_array_method_visits_every_element_after_its_object_takes_a_class_with_an_indexer() { + let mut r = realm(10_000_000); + // `Base` has a length of 5,000, an element `0` on its prototype and no indexer; `Indexed`, of + // the same family, gives `list[i]` for each index. `upgrade()` gives the same object as an + // `Indexed`. + let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0))); + let zero: HostFunction = Rc::new(|_| Ok(Data::Number(0.0))); + let upgrade: HostFunction = Rc::new(|_| Ok(host_ref("Indexed", &[1.0]))); + let members = vec![ + ("length".to_string(), HostMember::Get(length)), + ("0".to_string(), HostMember::Get(zero)), + ("upgrade".to_string(), HostMember::Method(upgrade)), + ]; + let base = HostClass { name: "Base".into(), parent: None, members, index: None, construct: None }; + let index: HostFunction = Rc::new(|a| Ok(a.get(1).cloned().unwrap_or(Data::Undefined))); + let indexed = HostClass { name: "Indexed".into(), parent: Some("Base".into()), members: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![base, indexed], vec![("list".into(), host_ref("Base", &[1.0]))]).unwrap(); + let out = r + .run("var n = 0; Array.prototype.forEach.call(list, function () { if (n === 0) list.upgrade(); n++; }); [list instanceof Indexed, n].join()") + .unwrap(); + assert_eq!(out, JsValue::String("true,5000".into())); +} + #[test] fn array_methods_visit_every_element_of_a_long_host_list() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..fdfd0d5d79 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2407,6 +2407,11 @@ impl Interp { let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); self.constructing = was; let v = v?; + // `new` gives an object ([[Construct]]): a constructor that gives another value + // is a TypeError. + if !matches!(v, Value::Object(_)) { + return Err(self.type_error(&format!("the constructor {name} did not give an object"))); + } if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? diff --git a/docs/mcp.md b/docs/mcp.md index 86737f7fdb..b23b0eb569 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2636,11 +2636,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot columns for the other layouts), 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()` + `file.newPresets` lists for that profile (a saved preset of the same name is not used), and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. A + the preset it is given holds one of them with a value other than `null`, and makes no document; it does the same + for a `previewMode` of `DocumentPreviewMode.OverprintPreview`. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the @@ -9005,7 +9006,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes ## New Document -`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` +`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a +built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in +that category), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are From 4180df830d982adfbb0ec1059b7a08c56907e450 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:08:47 -0800 Subject: [PATCH 084/533] Tests: the script tests follow main's page item order and preset checks - The rasterize tests read `a` and `b` as the second and first page items, since the list starts with the topmost object. - The DocumentPreset byte-limit tests fill the 4 MB with 4,096-byte titles across many presets, since a title holds at most 4,096 bytes and the other settings take only their own kind of value. - The plugin test's ScriptGate gives the `held` field. --- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom.rs | 26 ++++++++++++------- .../engine/src/tests/script_raster_capture.rs | 11 ++++---- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1fc9de10d7..35164c3958 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1117,17 +1117,20 @@ fn document_preset_applies_only_its_given_fields() { #[test] fn document_preset_settings_are_limited_in_bytes() { let mut s = Session::new(); + // A title holds at most 4,096 bytes, so 1,005 presets with such a title and their six defaults + // hold 4,192,860 bytes, and the next preset's defaults bring that to 4,192,934 of 4,194,304. let out = log( &mut s, - "var big = new Array(1572865).join('a'), p = new DocumentPreset(), q = new DocumentPreset();\ - p.title = big; p.units = big; p.title = big; q.title = 'x'; vc.log(p.title.length);\ - try { q.colorMode = big; } catch (e) { vc.log([e.name, e.message]); }\ - vc.log(q.colorMode === undefined); p.title = 'short'; q.colorMode = big; vc.log(q.colorMode.length);", + "var big = new Array(4097).join('a'), ps = [];\ + for (var i = 0; i < 1005; i++) { var p = new DocumentPreset(); p.title = big; ps.push(p); }\ + var q = new DocumentPreset(); ps[0].title = big; vc.log(ps[0].title.length);\ + try { q.title = big; } catch (e) { vc.log([e.name, e.message]); }\ + vc.log(q.title === undefined); ps[0].title = 'short'; q.title = big; vc.log(q.title.length);", ); - assert_eq!(out[0], json!(1_572_864)); + assert_eq!(out[0], json!(4096), "a setting assigned again replaces what it held"); assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); assert_eq!(out[2], json!(true), "a refused setting is not stored"); - assert_eq!(out[3], json!(1_572_864), "replacing a setting frees what it held"); + assert_eq!(out[3], json!(4096), "replacing a setting frees what it held"); } /// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the @@ -1135,15 +1138,18 @@ fn document_preset_settings_are_limited_in_bytes() { #[test] fn a_new_document_preset_is_refused_past_the_byte_limit() { let mut s = Session::new(); - // The six defaults hold 74 bytes; the two strings leave 10 bytes of the 4 MB free. + // The six defaults hold 74 bytes and a 4,096-byte title 4,098, so 1,005 presets with such a + // title and one more with a 1,358-byte title leave 10 bytes of the 4 MB free. let out = log( &mut s, - "var p = new DocumentPreset(); p.title = new Array(2097153).join('a'); p.units = new Array(2097065).join('b');\ + "var big = new Array(4097).join('a');\ + for (var i = 0; i < 1005; i++) { var f = new DocumentPreset(); f.title = big; }\ + var p = new DocumentPreset(); p.title = new Array(1359).join('b');\ try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ - p.colorMode = 1; vc.log(p.colorMode); p.title = 'x'; vc.log(new DocumentPreset().width);", + p.documentBleedLink = true; vc.log(p.documentBleedLink); p.title = 'x'; vc.log(new DocumentPreset().width);", ); assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[1], json!(1), "a refused preset adds nothing to the count"); + assert_eq!(out[1], json!(true), "a refused preset adds nothing to the count"); assert_eq!(out[2], json!(612), "a preset below the limit is still made"); } diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 863b5d1db6..1dbbfe7b75 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -58,8 +58,9 @@ fn images(s: &Session) -> Vec<(u32, u32)> { out } -/// A script that selects `b` and rasterizes `a` (the first and second page items). -const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[0], b = d.pageItems[1]; b.name = 'b'; d.selection = [b];"; +/// A script that selects `b` and rasterizes `a` (the second and first page items: the list starts +/// with the topmost object). +const RASTERIZE_A: &str = "var d = app.activeDocument, a = d.pageItems[1], b = d.pageItems[0]; b.name = 'b'; d.selection = [b];"; #[test] fn script_rasterize_explicit_sources_preserves_selection() { @@ -249,12 +250,12 @@ fn script_rasterize_rejects_bad_clip_bounds() { ("'all'", "four numbers"), ]; for (bounds, message) in cases { - refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[0], {bounds});"), message); + refused(&mut s, &format!("var d = app.activeDocument; d.rasterize(d.pageItems[1], {bounds});"), message); } // `a` spans x 10 to 40: a rectangle at x 42 to 48 reaches only the 10 pt padding around it. refused( &mut s, - "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[0], [42, 280, 48, 240], o);", + "var d = app.activeDocument, o = new RasterizeOptions(); o.padding = 10; d.rasterize(d.pageItems[1], [42, 280, 48, 240], o);", "does not overlap the art", ); } @@ -262,7 +263,7 @@ fn script_rasterize_rejects_bad_clip_bounds() { #[test] fn script_rasterize_rejects_an_image_past_the_size_limit() { let (mut s, ..) = doc(); - let source = "var d = app.activeDocument, b = d.pageItems[1]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; + let source = "var d = app.activeDocument, b = d.pageItems[0]; b.width = 3000; b.height = 3000; var o = new RasterizeOptions(); o.resolution = 2400; d.rasterize(b, undefined, o);"; let e = failure(&mut s, source); assert!(e.contains("too large"), "{e}"); assert_eq!(images(&s), Vec::<(u32, u32)>::new()); From b54c9f063f9103f14e211d60def24bb1fe1b7e26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:10:27 -0800 Subject: [PATCH 085/533] Scripts: placedItems and rasterItems list the topmost image first, as pageItems does pageItems on main lists the topmost object first, and the image lists are built from it, so their order now follows it. The raster metadata test places its images in the order that keeps its assertions, and the plugins test that main added gives ScriptGate the held field this branch adds. --- crates/engine/src/script/dom/images.rs | 3 ++- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 3 ++- docs/mcp.md | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 0e7be90dfe..4528151057 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -135,7 +135,8 @@ pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, Ho Ok(Some([run, uid, high, low])) } -/// The ids of a document's linked (`placed`) or embedded images in paint order. +/// The ids of a document's linked (`placed`) or embedded images, topmost first, in the order of +/// `pageItems`. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; if let Some(l) = &*h.dom.images.lists.borrow() diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 594582e9f9..f1f58a3c96 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -319,8 +319,9 @@ fn raster_metadata_uses_encoded_header_not_rgb_fallback() { std::fs::write(&g, gray_png(6, 4)).unwrap(); std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap(); let mut s = session(); - place(&mut s, &g, false); + // `rasterItems` lists the topmost image first, so the gray image placed last is `r[0]`. place(&mut s, &c, false); + place(&mut s, &g, false); let out = log( &mut s, &base, diff --git a/docs/mcp.md b/docs/mcp.md index 85c29806de..fbba0226f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2933,7 +2933,8 @@ other files through `$`: keeps the preset's value. A bad value throws an error before anything is written. - `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, - in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and + `removeAll()`. `placedItems.add()` gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` From eb31682d720dbd82bfd7c1cb5fe906d02cc6e85b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:11:18 -0800 Subject: [PATCH 086/533] Scripts: reference-error tests name BridgeTalk now that Window is defined The tests on main checked the `vc` advice with `new Window('dialog')`, which throws a ReferenceError only where ScriptUI is missing. This branch defines `Window`, so those runs succeeded and the tests failed. They now use `BridgeTalk`, which stays undefined and is still in the list of other applications' objects. --- crates/engine/src/tests/script_run.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 9489921682..b9cdafb9c1 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`")); // The application's members need no `app.`, so naming one alone is not an error. assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), + ("throw 'ReferenceError: BridgeTalk is not defined';", "thrown", "ReferenceError: BridgeTalk 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"), @@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "new Window('dialog');").unwrap_err(); + run(&mut s, "new BridgeTalk();").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. From d6bb6429f4abf4a48df27d505e33741d05846db2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:11:19 -0800 Subject: [PATCH 087/533] Scripts: controlBounds, placedItems and rasterItems follow main's empty-object and topmost-first rules On main, a page item's bounds are an Option, and an object with nothing in it reads its bounds as zeros. controlBounds now does the same: it joins the visible bounds with the handle bounds when either exists, and reads zeros when neither does. Main lists pageItems topmost first. placedItems and rasterItems take their order from pageItems, so they list the images topmost first too; docs/mcp.md says so, and the tests that read the newest object or the bottom one by index read it at its new position. The plug-in test main added that builds a ScriptGate by hand now sets the held field this branch added to it. --- crates/engine/src/script/dom.rs | 8 ++++++-- crates/engine/src/script/dom/images.rs | 3 ++- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom.rs | 2 +- crates/engine/src/tests/script_dom_images.rs | 9 +++++---- docs/mcp.md | 2 +- 6 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9fae8ab13e..1a0ecbc44b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1811,12 +1811,16 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } -/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths. +/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an +/// object with nothing in it. fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, true)?; let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); - Ok(f.bounds(h.dom.coords.get(), handles.map_or(r, |b| r.union(b)))) + match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) { + Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), + None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } /// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 921cbef27f..24c40006e2 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -127,7 +127,8 @@ fn pending_handle(d: &Data) -> Option<[f64; 3]> { } } -/// The ids of a document's linked (`placed`) or embedded images in paint order. +/// The ids of a document's linked (`placed`) or embedded images, topmost first as [`page_items`] +/// lists them. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; if let Some(l) = &*h.dom.images.lists.borrow() diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 91598e766a..6eca338c60 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -140,7 +140,7 @@ fn page_item_control_bounds_take_in_the_handles() { let (mut s, _, _) = doc(); let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); s.execute("path.create", &json!({"anchors": anchors})).unwrap(); - let out = log(&mut s, "var p = app.activeDocument.pageItems, i = p[p.length - 1]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; let (visible, control) = (b(&out[0]), b(&out[1])); assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 8101e17ab0..639020ab18 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -326,9 +326,10 @@ fn raster_metadata_uses_encoded_header_not_rgb_fallback() { &base, "var r = app.activeDocument.rasterItems, t = [];\ for (var i = 0; i < r.length; i++) t.push([r[i].imageColorSpace, r[i].channels, r[i].bitsPerChannel, r[i].transparent, r[i].colorizedGrayscale]);\ - vc.log(t); vc.log(r[0].boundingBox); vc.log(r[1].imageColorSpace === ImageColorSpace.RGB); var m = r[1].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", + vc.log(t); vc.log(r[1].boundingBox); vc.log(r[0].imageColorSpace === ImageColorSpace.RGB); var m = r[0].matrix; vc.log([m.typename, m.mValueA, m.mValueD]);", ); - assert_eq!(out[0], json!([["ImageColorSpace.Grayscale", 1, 8, false, false], ["ImageColorSpace.RGB", 4, 8, true, false]])); + // The collection lists the images topmost first, as `pageItems` does: the color image placed last comes first. + assert_eq!(out[0], json!([["ImageColorSpace.RGB", 4, 8, true, false], ["ImageColorSpace.Grayscale", 1, 8, false, false]])); assert_eq!(out[1], json!([0, 4, 6, 0])); assert_eq!(out[2], json!(true)); let m = out[3].as_array().unwrap(); @@ -577,9 +578,9 @@ fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ - x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log(d.pageItems[0].typename);", + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log([d.pageItems[0].typename, d.pageItems[1].typename]);", ); - assert_eq!(out, vec![json!("Stale page item"), json!("PathItem")]); + assert_eq!(out, vec![json!("Stale page item"), json!(["RasterItem", "PathItem"])]); assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); let _ = std::fs::remove_dir_all(base); } diff --git a/docs/mcp.md b/docs/mcp.md index 59bc92d6dd..1b22e2896a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2938,7 +2938,7 @@ other files through `$`: keeps the preset's value. A bad value throws an error before anything is written. - `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, - in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` From cd1d1c0b340032038e336bb9fa262ac2a4e13083 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:26:10 -0800 Subject: [PATCH 088/533] i18n: Bulgarian asks before a script turns off the external script warning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bulgarian joined the complete-message languages on main, and the confirm a script shows before it turns off the warning for scripts picked with File › Scripts › Other Script… had no Bulgarian row, so script_warning_off_question_is_translated failed for bg. --- crates/ui-egui/src/i18n/bg.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fe6dc33df5..1bbdb83729 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1319,6 +1319,7 @@ font-technology Variable Променливи @msg a drag or an undo group is open; finish it before running a script има отворено влачене или група за отмяна; завършете го, преди да изпълните скрипт @msg the script left a document that cannot be kept скриптът остави документ, който не може да се запази @msg the script is no longer in the Scripts folder скриптът вече не е в папката Scripts +@msg The script asks to turn off the warning shown before a script picked with File › Scripts › Other Script… runs. Scripts picked later would then run without it. Turn the warning off? Скриптът иска да изключи предупреждението, което се показва преди изпълнението на скрипт, избран с Файл › Скриптове › Друг скрипт… След това избраните по-късно скриптове ще се изпълняват без него. Да се изключи ли предупреждението? @msg the script's run is no longer available изпълнението на скрипта вече не е налично @msg a failed command changed undo steps that could not be put back, so the script was stopped неуспешна команда промени стъпки за отмяна, които не можаха да се възстановят, затова скриптът беше спрян @msg a recovery copy could not be written, so the script was not run не можа да се запише копие за възстановяване, затова скриптът не беше изпълнен From f4aeabaddab8e88f8cdf13d330237225b852d55b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:44:50 -0800 Subject: [PATCH 089/533] Scripts: the Copy test reads what the run wrote to the system clipboard a_scripts_copy_is_offered_to_other_apps_when_the_run_ends checked app.clipboard_out, which only the panels' text copies set. A Copy's formats go to the clipboard backend, so the test failed at its first Copy. It now installs the fake clipboard from tests/sysclip.rs and counts the app's writes, and checks that the formats include SVG. CI did not report it because its test shard stopped at the first failure. --- crates/ui-egui/src/tests/script_run.rs | 44 +++++++++++++++++--------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 18ae9854c6..fef7526658 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -1,15 +1,19 @@ //! File › Scripts › Other Script… (`ui.runScript`): the chooser, the warning and its preference, //! a run advanced frame by frame, Stop, and the questions a run and quitting ask. +use std::sync::{Arc, Mutex}; + use craft::host::{PickKind, Picked}; use craft::ui::dialog::{DialogResult, StackDialog}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use vectorcraft_engine::cmd::clipboard::SVG; use vectorcraft_engine::cmd::scripts::TOO_LARGE; use vectorcraft_engine::script::MAX_SOURCE_BYTES; use vectorcraft_engine::script::folder::Clock; use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set}; +use super::sysclip::{Board, fake, writes, written}; use crate::dialogs::script_run::{ self, BY_PERSON, CLOSE_KIND, FilesAnswer, GROWTH_KIND, GrowthQuestion, KIND, PICKER_KIND, RunQuestion, ScriptFiles, }; @@ -612,38 +616,48 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +/// Whether the app wrote the fake system clipboard since `seen` writes, once the formats it is making +/// are written. `seen` becomes the new count. +fn offered(app: &mut VectorcraftApp, board: &Arc>, seen: &mut usize) -> bool { + let _ = app.written_clipboard_text(); + let now = writes(board); + std::mem::replace(seen, now) != now +} + #[test] fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { - let mut app = app(); + let (fake, board) = fake(); + let services = crate::Services { clipboard: Some(Box::new(fake)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({})).unwrap(); app.session.prefs.show_external_script_warning = false; - app.clipboard_out = None; + let mut seen = writes(&board); let draw = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": draw })).unwrap().unwrap(); finish(&mut app); - assert!(app.clipboard_out.is_none(), "a run without a Copy offers nothing"); + assert!(!offered(&mut app, &board, &mut seen), "a run without a Copy offers nothing"); let copy = "vc.run('select.all', {}); app.copy();"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": copy })).unwrap().unwrap(); finish(&mut app); - assert!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains("'});"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": import })).unwrap().unwrap(); finish(&mut app); assert_eq!(app.ui.status, "Ran script"); - assert!(app.clipboard_out.is_none()); + assert!(!offered(&mut app, &board, &mut seen)); // An import in a batch that fails and is rolled back leaves the copied clipboard to be offered. let rolled_back = "app.copy(); try { vc.run('command.batch', {commands: [{command: 'clipboard.importSvg', params: {svg: ''}}, {command: 'no.such', params: {}}]}); } \ @@ -651,25 +665,25 @@ fn a_scripts_copy_is_offered_to_other_apps_when_the_run_ends() { menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": rolled_back })).unwrap().unwrap(); finish(&mut app); assert_eq!(app.ui.status, "Ran script"); - assert!(app.clipboard_out.is_some()); + assert!(offered(&mut app, &board, &mut seen)); // A run that copies and then fails leaves the clipboard and what other apps were offered alone. - app.clipboard_out = None; let fails = "app.cut(); throw new Error('stop');"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": fails })).unwrap().unwrap(); finish(&mut app); - assert!(app.clipboard_out.is_none()); + assert!(!offered(&mut app, &board, &mut seen)); assert_eq!(objects(&app), 1); // A Copy with nothing selected copies nothing, and other apps keep what they were offered. let empty = "vc.run('select.none', {}); app.copy();"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": empty })).unwrap().unwrap(); finish(&mut app); assert_eq!(app.ui.status, "Ran script"); - assert!(app.clipboard_out.is_none()); + assert!(!offered(&mut app, &board, &mut seen)); // A run that automation takes to its end at once offers its Copy too. app.session.script_frames = false; let reply = app.run("script.run", json!({ "source": copy, "name": "t.js" })).unwrap(); assert_eq!(reply["copied"], true); - assert!(app.clipboard_out.as_deref().is_some_and(|svg| svg.contains(" Date: Fri, 27 Nov 2026 18:36:32 -0800 Subject: [PATCH 090/533] Scripts: textFrames.removeAll() refuses type on a locked artboard - textFrames.removeAll() deleted a text frame on a locked artboard, although its editable property reads false. It now throws "cannot delete objects on a locked artboard" with the ids before anything is deleted, as pathItems.removeAll() and remove() do. - add(contents, relativeObject) with a text range of a removed frame threw a type error. It now throws "Stale text range"; only an argument of another class gets the type error. - The hidden or locked edit test starts each case from a fresh frame, and checks run sizes and justification after each refused edit. The add test also checks the text of the frame the script edits. --- crates/engine/src/script/dom/text.rs | 23 ++++++++++----- crates/engine/src/tests/script_text.rs | 41 +++++++++++++++++++++++--- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 4a25a8300f..0d993057ce 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -48,9 +48,9 @@ use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, - float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, - typename_of, whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, + edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, + property, text, typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -744,8 +744,10 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let rel = arg(a, 2); let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 + } else if handle_of(rel, "TextRange").is_some() { + span_of(h, rel, &["TextRange"])? } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into())); }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); @@ -1381,19 +1383,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index dcecba422f..eef6b274e3 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -299,8 +299,10 @@ fn bad_text_paint_is_refused_without_a_change() { #[test] fn hidden_or_locked_type_is_not_edited() { - let (mut s, id) = doc_with("abc"); - let (runs, text) = (paints(&s, id), plain(&s, id)); + let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify), + _ => panic!("not text"), + }; for hide in ["t.locked = true;", "t.hidden = true;"] { for edit in [ "r.characters[1].fillColor = red;", @@ -309,14 +311,17 @@ fn hidden_or_locked_type_is_not_edited() { "r.characters.add('!');", "r.justification = Justification.CENTER;", ] { + // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. + let (mut s, id) = doc_with("abc"); + let before = state(&s, id); let e = failure( &mut s, &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), ); assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + assert_eq!(state(&s, id), before, "{hide} {edit}"); } } - assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); } #[test] @@ -605,7 +610,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { } // Empty contents add nothing; bad arguments throw before anything changes. let (mut s, id) = doc_with("ab"); - s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap()); let before = undo_steps(&s); let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); @@ -620,7 +625,35 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, other), "other"); assert_eq!(plain(&s, id), "ab"); + // A range of a frame that was removed is stale, not of the wrong class. + let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);"); + assert!(e.contains("Stale text range"), "{e}"); + assert_eq!(plain(&s, id), "ab"); +} + +/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as +/// `pathItems.removeAll()` does. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("ab"); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}"); + assert_eq!(plain(&s, id), "ab"); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); } #[test] From 11d20c346fcd0fc6bf239857233f079b598c6187 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:40:01 -0800 Subject: [PATCH 091/533] Scripts: refused saves call no writer, white matte, relative paths, checker reassignments - A save of several files whose file access refuses one returns that error without calling the writer for any file, and the check before the write no longer lists the paths as written. - ExportOptionsPNG24 and ExportOptionsJPEG accept matteColor at its default, white (red, green and blue 255); other colors still throw. - Document.path of a file saved under a relative name is the working folder the engine wrote the file in. - The script checker keeps reporting saveAs and exportFile on a variable holding the script's own object when a declaration follows a label, a function body assigns the variable, a member assignment writes a property of that name, code runs from text, or the script includes another file. - docs/mcp.md: saveAs to a .vctemplate file without options writes a template copy and leaves fullName and the saved state as they were. --- crates/engine/src/cmd/fileio/save.rs | 10 ++- crates/engine/src/file_access.rs | 10 ++- crates/engine/src/script/dom/save_open.rs | 23 +++++-- crates/engine/src/tests/script_save_open.rs | 35 +++++++++-- crates/scriptcheck/src/analyze.rs | 29 +++++++-- crates/scriptcheck/src/analyze/declared.rs | 67 +++++++++++++++++++-- crates/scriptcheck/src/tests.rs | 31 +++++++++- docs/mcp.md | 4 +- 8 files changed, 183 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..2234144f54 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. The first refusal is the save's error, and `write` is not called for any of + // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(crate::EngineError::Other(e)); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 5951df8a64..0dd95b7546 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -461,8 +461,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -473,6 +472,13 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without adding `path` to the files a script run reports as written, for a +/// check made before anything is written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write) +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index a091d229f4..3f56e65b8e 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -141,6 +141,9 @@ enum Default { /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for /// `DownsampleMethod.NODOWNSAMPLE`). Member(&'static str, &'static str), + /// White as an RGB color: an object whose `red`, `green` and `blue` are 255 (its `typename`, when + /// it has one, `RGBColor`). + White, /// The help page gives no default: any value throws. Unset, } @@ -152,6 +155,15 @@ impl Default { (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, (Default::Text(a), Data::String(b)) => a == b, (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + (Default::White, Data::Object(items)) => { + let full = |c: &str| items.iter().any(|(k, v)| k == c && matches!(v, Data::Number(n) if (n - 255.0).abs() < 1e-9)); + let rgb = items.iter().all(|(k, v)| match k.as_str() { + "typename" => matches!(v, Data::String(s) if s == "RGBColor"), + "red" | "green" | "blue" => true, + _ => false, + }); + rgb && ["red", "green", "blue"].into_iter().all(full) + } _ => false, } } @@ -502,7 +514,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::R raster_map("ExportOptionsPNG24", name, d, p) } -const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn png24_starts() -> Vec<(&'static str, Data)> { vec![ @@ -530,7 +542,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } const JPEG_KEPT: &[(&str, Default)] = - &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn jpeg_starts() -> Vec<(&'static str, Data)> { vec![ @@ -1005,12 +1017,15 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. +/// document that has none. A file saved under a relative path, which the engine wrote in the +/// process's working folder, is in that folder. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + let p = std::path::Path::new(p); + let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; + let parent = full.parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 5b36ffc5da..86a6e35807 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -110,13 +110,17 @@ fn omitted_options_are_a_new_options_objects_defaults() { d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\ d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\ d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\ + var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\ + var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\ d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\ d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\ d.saveAs(new File(dir + '/a1.pdf'));\n\ d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());" ), ); - for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] { + for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] { assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ"); } for name in ["a1.pdf", "a2.pdf"] { @@ -287,7 +291,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose last file is refused hands none of them to the writer, the refused one included. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -324,9 +328,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { Ok(()) }) }); - assert!(r.is_err(), "{r:?}"); + let e = r.unwrap_err().to_string(); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert!(e.contains(DENIED) && e.contains(&refused), "{e}"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -583,6 +588,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "ExportOptionsPNG24.matteColor is not available yet", + ), (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), ( format!( @@ -794,6 +805,22 @@ fn full_name_path_saved_and_close_follow_the_documents_file() { let _ = std::fs::remove_dir_all(base); } +/// A document whose file was saved under a relative name is in the working folder the file was +/// written in. +#[test] +fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { + let base = folder("relative"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.active_mut().unwrap().path = Some("drawing.svg".into()); + let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(out[0][0], json!(true), "{out}"); + let shown = PathBuf::from(out[0][1].as_str().unwrap()); + assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. #[test] fn a_document_without_unsaved_changes_closes_with_any_save_options() { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..a4da181c75 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -56,6 +56,9 @@ pub(crate) struct Known { /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts /// as a Folder object whatever the path names. pub unsure: bool, + /// The script includes another file ([`Declared::includes`]), whose code may give a file's + /// variables values the scan of that file does not read. + pub others: bool, } impl Known { @@ -70,6 +73,7 @@ impl Known { /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { self.unsure |= other.unsure; + self.others |= other.others; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -281,8 +285,8 @@ struct ObjectValue { /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly - /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or - /// a loop's parentheses: only then does the variable hold `bits` after it. + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a + /// loop's parentheses or a label: only then does the variable hold `bits` after it. whole: bool, /// The bit of the method whose value is being read, and how far that value has been read. value: Option<(u8, Value)>, @@ -647,6 +651,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`]. + others: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + others: known.others || declared.includes, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1386,7 +1393,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1432,9 +1439,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// No variable joins when code the scan does not follow at that point may give it another value: + /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a + /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as + /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.unsure + && !self.others + && !self.declared.rebound.contains(&name) + && !self.declared.body_assigned.contains(name.as_str()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); @@ -1734,7 +1749,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; + let known = Known { + bound: std::mem::take(&mut self.bound), + files: std::mem::take(&mut self.files), + folders, + unsure: self.unsure, + others: self.others, + }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..f00a7240c9 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,8 +1,11 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; +use super::{ + Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, + unquote, word, +}; /// The names that give variables values the analysis doesn't read: a `with` statement makes an /// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, @@ -36,6 +39,14 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than + /// in a `var` statement's declarations, unless a body around the assignment declared the name with + /// `var` before it. The function may run at any time after it is defined, + /// also before its body in the text when it is a declaration, so a variable of that name may lose + /// the value an assignment the analysis read gave it. + pub(super) body_assigned: HashSet<&'s str>, + /// The file has an `#include` line: the included file's code may give its variables values. + pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -82,6 +93,9 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, + /// The names the bodies being read declare so far, each with the number of those bodies that + /// declare it. + declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -101,6 +115,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], + declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -109,7 +124,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { for t in lexer.by_ref() { match breaks.read(&t) { Read::Skip => {} - Read::Directive => d.directive(), + Read::Directive => d.directive(&t), Read::Token(sig) => d.token(sig), } } @@ -164,9 +179,41 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } + if !self.bodies.is_empty() || self.untracked.is_some() { + self.body_assignment(&t, depth); + } self.h = [Some(t), h0, h1]; } + /// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one + /// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`]. + fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) { + let [h0, h1, _] = self.h; + let name = |s: Option>| s.filter(|s| s.kind == T::Ident).map(|s| s.text); + let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth)); + let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) { + // `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`. + name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares)) + } else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) { + // `++d`. + Some(t.text) + } else if t.word("in") && (is(h1, "(") || word(h1, "var")) { + // `for (d in …)`. + name(h0) + } else { + None + }; + // A name a body around `t` has declared with `var` before it is that body's own. + let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + if let Some(name) = assigned.filter(|n| !own(n)) { + if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { + self.out.body_assigned.insert(name); + } else { + self.out.unsure = true; + } + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -261,6 +308,14 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + for name in body.names { + if let Some(n) = self.declared_around.get_mut(name) { + *n = n.saturating_sub(1); + if *n == 0 { + self.declared_around.remove(name); + } + } + } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -285,6 +340,7 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); + *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } @@ -297,7 +353,10 @@ impl<'s> Declarations<'s, '_, '_> { /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), /// so the name may be any. - fn directive(&mut self) { + fn directive(&mut self, t: &Token<'s>) { + if directives::parse(t.text).known == Some("include") { + self.out.includes = true; + } if self.keys.iter().any(|k| k.member) { self.out.unsure = true; } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1524d4d7ae..341ad3b3d0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -615,7 +615,7 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", - "c[k] = w;\n", + "c = app.activeDocument;\n", "delete d.saveAs;\n", "var h = e;\n", "use(g);\n", @@ -633,6 +633,9 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "s.saveAs(f);\n", )); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); + // A computed key may name any property, a variable's on the global object included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name @@ -664,6 +667,32 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give +/// the variable another value: a declaration after a label, which `if` may skip, a function body that +/// assigns the variable (its own method's, or a declaration's that runs before its text), a member +/// assignment of a property of that name, which may be the global object's, code given as text and an +/// included file each leave the write reported. A function that declares its own variable of the name +/// leaves it the script's own. +#[test] +fn a_save_as_other_code_may_replace_writes_a_file() { + let cases: [(&str, &[usize]); 7] = [ + ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), + ( + "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", + &[10], + ), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), + ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ]; + for (src, lines) in cases { + let r = report(src); + assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}"); + } +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 0c6a0bfcbe..902d38a355 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2895,7 +2895,9 @@ other files through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. -- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a + `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its + saved state. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). From 306c24c120e8e6f02d748d53007a9e6b94597009 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:05:06 -0800 Subject: [PATCH 092/533] Scripts: absolute paths for relative document files, save warnings in the console - Document.fullName of a file saved or opened under a relative path is the file in the process's working folder, as Document.path already was, and close with SaveOptions.SAVECHANGES saves it there. - saveAs, exportFile, app.open and close with SAVECHANGES write each warning their command gives to the Script Console, starting with the method's name. - The checker tests cover a with statement and an include between a literal and its call. --- crates/engine/src/script/dom/save_open.rs | 55 ++++++++++++++------- crates/engine/src/tests/script_save_open.rs | 35 +++++++++++-- crates/scriptcheck/src/tests.rs | 4 +- docs/mcp.md | 7 ++- 4 files changed, 76 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 3f56e65b8e..1eac9cd9cb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -47,8 +47,8 @@ //! save of one artboard writes only the file at the path, holding that artboard. Without //! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of //! artboard numbers throws. -//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no -//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened +//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw //! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. //! - `Document.close` with unsaved changes closes without them with @@ -71,8 +71,8 @@ use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, - property, text, this_doc, whole, + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, get, given, method, named, num, + on_doc, property, text, this_doc, whole, }; /// The most a scale factor of an export takes, in percent. @@ -863,10 +863,20 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } +/// Runs command `id` as [`command`] does, and writes each warning its result gives to the console as +/// `method: warning`, as `addDocument` writes the warnings of `file.new`. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (data, value) = command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(data) +} + /// `path` with the extension of `kind` added, unless its name already ends with one of them. fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; @@ -933,7 +943,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -979,7 +989,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -992,15 +1002,25 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } -/// The document's file, `None` for a document that has none, or `Script file access denied` with -/// the document's name when the automation read roots do not allow the file to be named +/// A document's file as the engine reads and writes it: a relative path is in the process's working +/// folder. It stays as it is when the working folder is not known. +fn absolute(path: &str) -> String { + let p = std::path::Path::new(path); + match std::env::current_dir() { + Ok(cwd) if p.is_relative() => cwd.join(p).to_string_lossy().into_owned(), + _ => path.to_string(), + } +} + +/// The document's file ([`absolute`]), `None` for a document that has none, or `Script file access +/// denied` with the document's name when the automation read roots do not allow the file to be named /// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. -fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { match st.path.as_deref() { Some(p) if crate::file_access::check_read(p).is_err() => { Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) } - p => Ok(p), + p => Ok(p.map(absolute)), } } @@ -1010,22 +1030,19 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; super::with_doc(h, doc, |_, st| { Ok(match shown_file(st)? { - Some(p) => vectorcraft_js::file_ref(p), + Some(p) => vectorcraft_js::file_ref(&p), None => vectorcraft_js::file_ref(&st.title()), }) }) } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. A file saved under a relative path, which the engine wrote in the -/// process's working folder, is in that folder. +/// document that has none. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let p = std::path::Path::new(p); - let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; - let parent = full.parent()?.to_string_lossy().into_owned(); + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; @@ -1077,12 +1094,12 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { - let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + let path = absolute(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?); // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 86a6e35807..f0ba05bb6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -813,11 +813,40 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { let mut s = session(&base); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.active_mut().unwrap().path = Some("drawing.svg".into()); - let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let out = logged( + &mut s, + &base, + "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);", + ); let cwd = std::env::current_dir().unwrap(); assert_eq!(out[0][0], json!(true), "{out}"); - let shown = PathBuf::from(out[0][1].as_str().unwrap()); - assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let same = |shown: &str, want: &Path| { + let shown = PathBuf::from(shown); + shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b) + }; + assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}"); + let file = out[0][2].as_str().unwrap(); + assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}"); + assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go +/// to the Script Console. +#[test] +fn a_saves_warnings_go_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let save = format!( + "Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("one.pdf")) + ); + let r = run(&mut s, &base, &save).unwrap(); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 341ad3b3d0..fa8d8eecbc 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -675,7 +675,7 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 7] = [ + let cases: [(&str, &[usize]); 9] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -685,6 +685,8 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { diff --git a/docs/mcp.md b/docs/mcp.md index 902d38a355..809caffb8a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2897,7 +2897,9 @@ other files through `$`: themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its - saved state. + saved state. Each warning the command gives, here and for `exportFile`, `app.open` and `close` with + `SaveOptions.SAVECHANGES`, goes to the Script Console as a line that starts with the method's name, such as + `saveAs: `. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). @@ -2964,7 +2966,8 @@ other files through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an From 51778505363acbe79a38e0f4fd5497e17acbe329 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:17:08 -0800 Subject: [PATCH 093/533] Scripts: placed and raster items take contentVariable Every page item kind that holds content now binds a variable through contentVariable on main, and the placed and raster item classes this branch adds defined it as not available yet. They now take the same member, so a linked image binds an image variable and an embedded one refuses it, as script_variables' an_embedded_image_cannot_take_an_image_variable checks. --- crates/engine/src/script/dom/images.rs | 6 ++++-- docs/mcp.md | 3 +-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 4528151057..06e1774536 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -660,7 +660,8 @@ pub(super) fn classes(l: &Link) -> Vec { ("matrix", property(l, placed_matrix, placed_set_matrix)), ("boundingBox", get(l, placed_box)), ]); - placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + placed.extend(super::variables::item_members(l, "PlacedItem")); + placed.push(later(l, "PlacedItem", "trace")); let mut raster = named(vec![ ("bitsPerChannel", get(l, raster_bits)), ("channels", get(l, raster_channels)), @@ -673,7 +674,8 @@ pub(super) fn classes(l: &Link) -> Vec { ("transparent", get(l, raster_transparent)), ("boundingBox", get(l, raster_box)), ]); - raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + raster.extend(super::variables::item_members(l, "RasterItem")); + raster.extend(["colorants", "colorize", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); vec![ class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), diff --git a/docs/mcp.md b/docs/mcp.md index 2b40fb55e5..b43a7c7841 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2960,8 +2960,7 @@ other files through `$`: item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a - file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not - available yet. + file is dropped at the end of the run. `trace`, `colorants`, `colorize` and `overprint` are not available yet. - A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` From ab75ac0c13e25eaa61848dd518edabfa19b252e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:19:22 -0800 Subject: [PATCH 094/533] Plug-ins: a module with a manifest section that lists events must export vc_event Changes on main needed the events code and its tests to follow them. - A module that carries its manifest in the `vc_manifest` custom section is loaded without being instantiated, and its exports are checked by `check_exports`. That check now also requires `vc_event` with the type (param i32 i32) (result i32) when the manifest lists `events`, as the instantiated path already did. The `an_event_plugin_exports_vc_event` test covers a sectioned module without `vc_event`, with the wrong type and with the right one. - JavaScript plug-ins have no `vc_event`, so their manifest may not list the permission `events`, next to `settings`, `cache` and `commands`. The JavaScript bundle test and docs/plugins.md say so. - The craft UI framework port removed `VectorcraftApp::begin_host_iteration`, so the two UI-pass event tests no longer call it. - On the framework, the whole window draws only on a context with the framework's runtime installed. `a_change_made_in_a_ui_pass_is_delivered_in_that_pass` drew it on a plain `egui::Context`, where the runtime panics ("the runtime plugin's hooks did not run for the previous pass") and the test did not finish. It now draws its passes with `testing::ui_context` and `testing::part_frame`, as the window tests on main do. --- crates/plugins/src/js.rs | 2 ++ crates/plugins/src/manifest.rs | 4 ++-- crates/plugins/src/runtime.rs | 10 +++++++--- crates/plugins/tests/abi.rs | 10 ++++++++++ crates/ui-egui/src/tests/plugins.rs | 8 +++----- crates/ui-egui/src/tests/script_run.rs | 1 - docs/plugins.md | 4 ++-- 7 files changed, 26 insertions(+), 13 deletions(-) diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs index a8fa158c41..b10506011f 100644 --- a/crates/plugins/src/js.rs +++ b/crates/plugins/src/js.rs @@ -460,6 +460,8 @@ mod tests { assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.events", ok, json!({"api": 2, "permissions": ["events"], "events": ["selection.changed"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("can't list the permission `events`")), "{e:?}"); let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 5b06ed24c5..611d51ebbf 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -704,7 +704,7 @@ impl Manifest { } /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions - /// it lists only `progress`: its realm has no settings, cache or command calls. + /// it lists only `progress`: its realm has no settings, cache, command calls or `vc_event`. fn validate_runtime(&self) -> Result<()> { if self.runtime == Runtime::Wasm { return Ok(()); @@ -714,7 +714,7 @@ impl Manifest { return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); } let listed = self.permissions.as_deref().unwrap_or_default(); - for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + for p in [Permission::Settings, Permission::Cache, Permission::Commands, Permission::Events] { if listed.iter().any(|n| n == p.name()) { let name = p.name(); return Err(Error::Manifest(format!( diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 9dd6d574e7..ce8ca5e32c 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -322,8 +322,9 @@ fn check_tables(bytes: &[u8]) -> Result<()> { } /// Checks the exports a run needs without instantiating `module`: its memory as `memory`, whose -/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types. -fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { +/// initial size fits in `max_memory_bytes`, and `vc_alloc` and `vc_run` with the ABI's types, and +/// `vc_event` with its type when `events` is set (the manifest lists events). +fn check_exports(module: &Module, max_memory_bytes: usize, events: bool) -> Result<()> { use ValType::{I32, I64}; let export = |name: &str| module.exports().find(|e| e.name() == name).map(|e| e.ty().clone()); let Some(ExternType::Memory(memory)) = export("memory") else { @@ -341,6 +342,9 @@ fn check_exports(module: &Module, max_memory_bytes: usize) -> Result<()> { return Err(Error::Abi(format!("the module must export `{name}` with the type {signature}"))); } } + if events && !matches!(export("vc_event"), Some(ExternType::Func(f)) if f.params() == [I32, I32] && f.results() == [I32]) { + return Err(Error::Abi("the module lists `events`, so it must export `vc_event` with the type (param i32 i32) (result i32)".into())); + } Ok(()) } @@ -428,7 +432,7 @@ impl Plugin { } } None => { - check_exports(&module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes, !p.manifest.events.is_empty())?; check_tables(bytes)?; } } diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 634762ef4e..206faa721e 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -1264,6 +1264,16 @@ fn an_event_plugin_exports_vc_event() { assert!(e.to_string().contains("vc_event"), "{e}"); assert!(Plugin::load(&build(&tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)), Limits::default()).is_ok()); assert!(Plugin::load(&ok_module(tpl::ECHO), Limits::default()).is_ok(), "no events, no vc_event"); + // A module whose manifest is in its custom section is checked without being instantiated. + let section = + r#"{"id":"test.events.section","name":"T","kind":"filter","api":2,"permissions":["events"],"events":["selection.changed"],"abi":1}"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, "", 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let one_param = r#"(func (export "vc_event") (param i32) (result i32) (i32.const 0))"#; + let e = Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, one_param, 1)), Limits::default()).unwrap_err(); + assert!(e.to_string().contains("vc_event"), "{e}"); + let handler = r#"(func (export "vc_event") (param i32 i32) (result i32) (i32.const 0))"#; + assert!(Plugin::load(&build(&tpl::sectioned(section, tpl::ECHO, handler, 1)), Limits::default()).is_ok()); } /// `vc_event` is given the event JSON in its own memory and returns 0; anything else, a trap and a diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 1eb8f2081a..53e4f89f33 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -838,20 +838,18 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); let r = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); app.run("select.none", json!({})).unwrap(); - let ctx = egui::Context::default(); + let ctx = crate::testing::ui_context(); let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)); let pass = |app: &mut VectorcraftApp, select: bool| { - app.begin_host_iteration(); - let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |app, ui| { app.tick(ui.ctx()); if select { app.session.execute("select.set", &json!({"ids": [r]})).unwrap(); } app.ui(ui); }); - out.textures_delta.clear(); }; - // Fonts install on the first pass and are ready on the second. + // The window lays itself out in the first two passes. pass(&mut app, false); pass(&mut app, false); pass(&mut app, true); diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index a5bd95e881..91803e6b70 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -343,7 +343,6 @@ fn a_finished_run_delivers_its_plugin_events_in_the_frame_it_ends() { if !app.session.script_running() { break; } - app.begin_host_iteration(); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); out.textures_delta.clear(); } diff --git a/docs/plugins.md b/docs/plugins.md index 385925d30f..1646097587 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1308,8 +1308,8 @@ function run(input, params) { The manifest has the keys of a module's [manifest](#manifest), with `"runtime": "js"` and `script`, a file name of 1 to 128 bytes ending in `.js`, without a folder or `:`, and not starting with `.`. Left out, `runtime` is WebAssembly, so existing modules load as before; a module's own manifest may not give `"js"`. A JavaScript plug-in is a filter (`kind` -`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache` or -`commands`, so it has no `commandAllowlist`. +`"filter"`), and of the host's [permissions](#permissions) it may list `progress` but not `settings`, `cache`, +`commands` or `events`, so it has no `commandAllowlist` and no `events`. `plugin.install {path}` and `plugin.inspect {path}` take the `.vcplugin` file, and File › Open and `plugin.reload` install it like a `.wasm` file. The host refuses a manifest without `script`, with `source`, or with a `runtime` other From c58763daf6cfb7d7def224487c6e5af4dd8afb29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:39:33 -0800 Subject: [PATCH 095/533] Save: a refused file of a save without a path is named by its file name A save of several files that the file access refuses before anything is written gave the refused file's full path in its error, also when the client did not give the path and the folder is outside the read roots. The check before the write now names the file as the writer did, so document.save with separateArtboards keeps the folder out of the error. --- crates/engine/src/cmd/fileio/save.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 2234144f54..d3b7fd62b8 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// The client did not give the path: a file the file access refuses before anything is + /// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]). + hides_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.hides_paths = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1086,10 @@ impl SaveJob { // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err().map(|e| (p, e))) { - return Err(crate::EngineError::Other(e)); + let e = crate::EngineError::Other(e); + return Err(if self.hides_paths { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refusals() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) From b086db0fbbf171d330f76b3618c112cd411fa129 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:49:55 -0800 Subject: [PATCH 096/533] Script check: a function that sets saveAs or exportFile keeps the write reported A function declared before an object literal could replace the literal's saveAs or exportFile method when it ran later, and the check still treated the method as the script's own and left the write out of filesWritten. When any function body assigns a property of that name, no variable's method of that name counts as the script's own. --- crates/scriptcheck/src/analyze.rs | 7 +++++-- crates/scriptcheck/src/analyze/declared.rs | 8 ++++++++ crates/scriptcheck/src/tests.rs | 18 ++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a4da181c75..fbcc62ae0a 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1441,8 +1441,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// closes a function body, so a literal given to the body's own variable stays inside the body. /// No variable joins when code the scan does not follow at that point may give it another value: /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a - /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as - /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). + /// property of that name, which may be the global object's ([`Declared::rebound`]), a function + /// body that assigns a `saveAs` or `exportFile` property of any object + /// ([`Declared::body_writer_assigned`]), code given as text or a `with` statement + /// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) @@ -1450,6 +1452,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && !self.others && !self.declared.rebound.contains(&name) && !self.declared.body_assigned.contains(name.as_str()) + && !self.declared.body_writer_assigned && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index f00a7240c9..c03efdd819 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -45,6 +45,11 @@ pub(crate) struct Declared<'s> { /// also before its body in the text when it is a declaration, so a variable of that name may lose /// the value an assignment the analysis read gave it. pub(super) body_assigned: HashSet<&'s str>, + /// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`] + /// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is + /// defined, and the object may be any variable's, so no variable's method of that name stays + /// the script's own. + pub(super) body_writer_assigned: bool, /// The file has an `#include` line: the included file's code may give its variables values. pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or @@ -245,6 +250,9 @@ impl<'s> Declarations<'s, '_, '_> { None }; if let Some(name) = property { + if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) { + self.out.body_writer_assigned = true; + } if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { self.out.rebound.insert(name); } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index fa8d8eecbc..1b931a2cca 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -670,12 +670,13 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// A literal's `saveAs` stays the script's own only while no code the check does not follow may give /// the variable another value: a declaration after a label, which `if` may skip, a function body that /// assigns the variable (its own method's, or a declaration's that runs before its text), a member -/// assignment of a property of that name, which may be the global object's, code given as text and an -/// included file each leave the write reported. A function that declares its own variable of the name -/// leaves it the script's own. +/// assignment of a property of that name, which may be the global object's, a function body that +/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement +/// and an included file each leave the write reported. A function that declares its own variable of the +/// name, or assigns another property of it, leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 9] = [ + let cases: [(&str, &[usize]); 12] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -687,6 +688,15 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), + ( + "var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n", + &[5], + ), + ( + "var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n", + &[5], + ), + ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { From 2f786096a50b28bffd73acf07ff87e5a0c7ad583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:54:54 -0800 Subject: [PATCH 097/533] Scripts: path and type edits refuse objects on a locked artboard - A point edit (anchor, leftDirection, rightDirection, setEntirePath) and a paint, stroke or transform change of a path on a locked artboard changed it, although its editable property reads false. They now throw "Cannot edit PathItem : it is on a locked artboard" with nothing changed. - A text edit, createOutline() or a point/area conversion of type on a locked artboard, and areaText() or pathText() given a hidden or locked path, now throw "Cannot edit" with nothing changed. - A point assigned more than 4,000,000 pt from the origin was queued without a check and written by a later call. It now throws a range error when it is assigned, and the path keeps its points. --- crates/engine/src/script/dom/paths.rs | 46 ++++++++++++++----- crates/engine/src/script/dom/text.rs | 23 ++++++++-- crates/engine/src/tests/script_dom_paths.rs | 49 +++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 27 ++++++++++++ docs/mcp.md | 11 +++-- 5 files changed, 138 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ea57a3f49b..bb3759d62e 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -15,7 +15,9 @@ //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden -//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing +//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it +//! is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -106,6 +108,27 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } +/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is +/// hidden or locked, or it is on a locked artboard. +fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { + if !editable(&st.doc, id) { + Some(cannot_edit(id)) + } else if super::on_locked_artboard(h, st, id) { + Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else { + None + } +} + +/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +fn in_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) + } +} + /// The path `d` names, which must still be in its document. fn path_of(h: &super::Host, d: &Data) -> std::result::Result { let item = item_of(h, d)?; @@ -179,7 +202,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// locked or is on a locked artboard, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() @@ -190,14 +213,15 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); - let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, editable(d, item.id), aligned) + let same = pd.subpaths == subs; + (same, if same { None } else { protected(h, st, item.id) }, aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = refused { + return Err(e); } *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { @@ -253,9 +277,8 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) { + return Err(e); } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); @@ -676,7 +699,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let f = with_doc(h, item.doc, |_, st| frame(st))?; let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; let c = h.dom.coords.get(); - let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); + let anchors: Vec = + script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); @@ -1351,7 +1375,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul let p = point(arg(a, 1), what)?; let (item, _) = this_point(h, a)?; let fr = with_doc(h, item.doc, |_, st| frame(st))?; - Ok(fr.to_document(h.dom.coords.get(), p)) + in_canvas(fr.to_document(h.dom.coords.get(), p), what) } fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0d993057ce..b051fcbb43 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -302,14 +302,26 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } /// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing -/// changed, when the frame or a layer or group it is in is hidden or locked. +/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a +/// locked artboard. fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { - if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { - return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); - } + refuse_protected(h, item, "TextFrame")?; edit_item(h, item, id, params) } +/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is +/// hidden or locked, or it is on a locked artboard. +fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> { + let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id))); + if !ok { + return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0))); + } + Ok(()) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -548,6 +560,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { /// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; + refuse_protected(h, item, "TextFrame")?; let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; super::command_value(h, "type.createOutlines", &json!({})) @@ -569,6 +582,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), Some(true) => {} } + refuse_protected(h, item, "TextFrame")?; let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) @@ -1365,6 +1379,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); } + refuse_protected(h, path, "PathItem")?; let orientation = if on_path { 4 } else { 2 }; let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 06c4670e93..591f0f1b05 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -854,6 +854,55 @@ fn locked_paths_and_wrong_objects_are_refused() { assert!(e.contains("not a PathPoint"), "{e}"); } +/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. +#[test] +fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = art(&s); + let steps = undo_steps(&s); + for source in [ + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a +/// later member call does not lose an assignment that returned. +#[test] +fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { + let (mut s, a, _) = doc(); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let far = crate::MAX_COORD * 1.5; + for source in [ + format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), + format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), + format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), + ] { + let e = failure(&mut s, &source); + assert!(e.contains("outside the canvas"), "{source}: {e}"); + } + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ + q.anchor = [45, 285];\ + try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ + vc.log(q.anchor); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); + let after = node(&s, a).path_data().unwrap().subpaths.clone(); + assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); + assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index eef6b274e3..62e4d28a92 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -633,6 +633,33 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert_eq!(plain(&s, id), "ab"); } +/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are +/// not changed. +#[test] +fn protected_type_and_paths_are_not_converted_or_edited() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}")); + assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}"); + } + assert_eq!(plain(&s, id), "abc"); + assert_eq!(undo_steps(&s), steps); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] { + let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};")); + assert!(e.contains("Cannot edit PathItem"), "{call}: {e}"); + assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]); + } +} + /// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as /// `pathItems.removeAll()` does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7edcb0be3e..726081df2c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2901,7 +2901,10 @@ other files through `$`: with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + available yet. `removeAll()` throws and deletes nothing when any type object is hidden or locked, is in a hidden or + locked layer or group, or is on a locked artboard (`cannot delete objects on a locked artboard`). A text edit, + `createOutline()` or a conversion of such a type object, and `areaText` or `pathText` given such a path, throw + `Cannot edit` with nothing changed. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to @@ -3033,8 +3036,10 @@ other files through `$`: `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path - that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing - changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws + `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or + `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. From 7c7bdff24b1bf5dd2c9fe3be54ab21212334902e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:32:28 -0800 Subject: [PATCH 098/533] Scripts: only the person turns off the external script warning Automation could answer Yes to the question a script asks before it turns off the external script warning, through the dialog's answer field or a pass it drives, and the warning was turned off. Setting Yes as the answer now fails with "Only the person at the keyboard can turn off the external script warning", and a Yes given while automation is acting is refused: the warning stays on and the question opens again. No is still taken from anyone, as Deny is in a script's file dialog. --- crates/ui-egui/src/dialogs/script_run.rs | 15 ++++++++++ crates/ui-egui/src/tests/script_dialogs.rs | 34 ++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 5bb70e52ad..744fae0aa6 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -67,6 +67,8 @@ pub const PICKER_KIND: &str = "scriptFiles"; /// Why Allow Once and Always Allow are refused to automation. pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; +/// Why Yes to turning off the external script warning is refused to automation. +pub(crate) const WARNING_BY_PERSON: &str = "Only the person at the keyboard can turn off the external script warning"; /// The note the file dialog shows when the person picked more files than a script is given. const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; @@ -273,6 +275,9 @@ impl StackDialog for ScriptNotice { let Some(answer) = answers_for(&self.kind).split(", ").find(|answer| *answer == wanted) else { return Err(format!("`answer` for this {} dialog must be one of: {}", self.kind, answers_for(&self.kind))); }; + if answer == "yes" && self.message == WARNING_OFF_QUESTION { + return Err(WARNING_BY_PERSON.into()); + } self.answer = Some(answer); } _ => return Err(FieldRefusal::Unknown.message(field)), @@ -663,6 +668,16 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult(&app) { + let id = open_id(&app, script_run::KIND); + script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap(); + pump(&mut app); + } + assert!(until_dialog(&mut app)); + assert_eq!(set(&app, NOTICE_KIND, "answer", json!("yes")).unwrap_err(), script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question stays open"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + + script_run::forget::(&app); + app.ui.answering_control = true; + let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new() }; + script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes)); + app.ui.answering_control = false; + assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question opens again"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + + set(&app, NOTICE_KIND, "answer", json!("no")).unwrap(); + assert!(confirm(&mut app, NOTICE_KIND), "No is taken from automation"); + assert!(!until_dialog(&mut app)); + assert!(app.session.prefs.show_external_script_warning, "the warning stays on"); +} From f1cb106d0293397c9f9a53bc39cc3e9eed289473 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:08:29 -0800 Subject: [PATCH 099/533] Docs: point limits name the x or y coordinate A script point is refused when its x or y is past MAX_COORD, not when its distance from the origin is. The module comment, the helper doc comment and docs/mcp.md now say so. --- crates/engine/src/script/dom/paths.rs | 6 +++--- docs/mcp.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bb3759d62e..a9f36c1b4d 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -16,8 +16,8 @@ //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing -//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it -//! is assigned. +//! changed. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a +//! range error when it is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -120,7 +120,7 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { } } -/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin. fn in_canvas(p: Point, what: &str) -> std::result::Result { if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { Ok(p) diff --git a/docs/mcp.md b/docs/mcp.md index 726081df2c..dbb5934740 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3038,7 +3038,7 @@ other files through `$`: `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or - `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + `rightDirection` whose x or y is more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and From e46f697d50e43f82b375ea5f3de97ad38fedad8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:10:24 -0800 Subject: [PATCH 100/533] Script check: a nested function that assigns an outer body's variable keeps the write reported A function body's assignment was left out of the names other code may change when any enclosing body had declared the name with var. A nested function such as swap() { d = app.activeDocument; } called before d.saveAs(f) then left d trusted as the script's own literal, and the write went unreported. Only a name the innermost body declared now counts as that body's own; plain, compound, increment and for-in assignments to an outer body's variable all keep the write reported. --- crates/scriptcheck/src/analyze/declared.rs | 21 +++++---------------- crates/scriptcheck/src/tests.rs | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index c03efdd819..85d1f7eb9c 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use super::{ Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, @@ -98,9 +98,6 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, - /// The names the bodies being read declare so far, each with the number of those bodies that - /// declare it. - declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -120,7 +117,6 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], - declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -208,8 +204,10 @@ impl<'s> Declarations<'s, '_, '_> { } else { None }; - // A name a body around `t` has declared with `var` before it is that body's own. - let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + // A name the innermost body around `t` has declared with `var` before it is that body's own. A + // name only an outer body declared is that body's variable, which a nested function may assign + // before a call in the outer body runs. + let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name)); if let Some(name) = assigned.filter(|n| !own(n)) { if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { self.out.body_assigned.insert(name); @@ -316,14 +314,6 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; - for name in body.names { - if let Some(n) = self.declared_around.get_mut(name) { - *n = n.saturating_sub(1); - if *n == 0 { - self.declared_around.remove(name); - } - } - } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -348,7 +338,6 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); - *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1b931a2cca..cd97a3b380 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,10 +673,11 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// assignment of a property of that name, which may be the global object's, a function body that /// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement /// and an included file each leave the write reported. A function that declares its own variable of the -/// name, or assigns another property of it, leaves it the script's own. +/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns +/// a variable its enclosing body declared leaves the write reported too. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 12] = [ + let cases: [(&str, &[usize]); 16] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -698,6 +699,22 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ), ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n", + &[5], + ), ]; for (src, lines) in cases { let r = report(src); From 6b7e9f01a23831494c1416af7b500c4f3fc68c32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:26:06 -0800 Subject: [PATCH 101/533] Scripts: concatenateMatrix rounds once at the edges of the number range The quick path in products_sum took a product that rounded up to the smallest normal number as exact, so a sum that needed the dropped part rounded twice: [N, N+S, 0, 1, 0, 0] then [1-2^-53, 0, -1, 1, 0, 0] gave mValueA = -S instead of -2S. A product at the smallest normal number now goes through the exact sum. The quick path also returned p + q + t when p + q was finite but adding t overflowed, although the exact sum was finite (MAX + 2^969); such a sum now goes through the exact sum too, and one that really overflows still throws a RangeError. --- crates/engine/src/script/dom/matrix.rs | 17 ++++++++++------- crates/engine/src/tests/script_dom_prefs.rs | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 7e93d4832a..bae77602cc 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,17 +103,20 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When both products and their sum are finite, and a product below the range of -/// normal numbers is the only term that is not 0, the sum is taken as numbers are. Otherwise the -/// products are summed past the range of a number and rounded at the end, so a finite value is not -/// lost to a product too large or too small for a number. +/// `x·y + z·w + t`. When both products and the whole sum are finite, and a product at or below the +/// smallest normal number is the only term that is not 0, the sum is taken as numbers are. +/// Otherwise the products are summed past the range of a number and rounded at the end, so a +/// finite value is not lost to a product too large or too small for a number, or to a sum that +/// rounds twice. A product that rounds up to the smallest normal number can have dropped part of a +/// step below it, so it counts as one too small. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); - let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() < f64::MIN_POSITIVE; + let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() <= f64::MIN_POSITIVE; let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; - if plain.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { - return plain + t; + let total = plain + t; + if total.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + return total; } // Each product is split into its rounded value and the part that rounding drops, both exact. // The five parts are added one at a time into a list of values that do not overlap, smallest diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fa01766d63..fae628e3c5 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -371,6 +371,25 @@ fn concatenation_applies_the_first_matrix_first() { ); } +#[test] +fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_number() { + let mut s = Session::new(); + // N·(1 - 2^-53) is N - S/2, which rounds up to N; the exact A is -1.5·S, which rounds to -2·S. + // MAX - 2^969 + 2^970 rounds to MAX, while adding the rounded MAX - 2^969 and 2^970 overflows. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var n = Math.pow(2, -1022), s = Number.MIN_VALUE;\ + vc.log(app.concatenateMatrix(mat([n, n + s, 0, 1, 0, 0]), mat([1 - Math.pow(2, -53), 0, -1, 1, 0, 0])).mValueA === -2 * s);\ + vc.log(app.concatenateMatrix(mat([n, 0, 0, 1, 0, 0]), mat([1, 0, 0, 1, 0, 0])).mValueA === n);\ + var shift = mat([1, 0, -1, 1, Math.pow(2, 970), 0]);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 969)]), shift).mValueTX === Number.MAX_VALUE);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), shift); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError")]); +} + #[test] fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { let mut s = Session::new(); From b32b14dc573234679bdc0c7052aa77b713c49dfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:00:37 -0800 Subject: [PATCH 102/533] Scripts: concatenateMatrix takes the exact sum near the overflow point The quick path in products_sum returned a finite coefficient whenever the rounded sum was finite. Rounding a product first can drop the part that puts the exact sum past the overflow midpoint, so a coefficient that should throw a RangeError came back as Number.MAX_VALUE. The quick path now runs only when the rounded sum is below half the largest number; every larger sum goes through the exact expansion and rounds once. --- crates/engine/src/script/dom/matrix.rs | 4 ++-- crates/engine/src/tests/script_dom_prefs.rs | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index bae77602cc..211ff9e8b0 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,7 +103,7 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When both products and the whole sum are finite, and a product at or below the +/// `x·y + z·w + t`. When the whole sum is below half the largest number, and a product at or below the /// smallest normal number is the only term that is not 0, the sum is taken as numbers are. /// Otherwise the products are summed past the range of a number and rounded at the end, so a /// finite value is not lost to a product too large or too small for a number, or to a sum that @@ -115,7 +115,7 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; let plain = p + q; let total = plain + t; - if total.is_finite() && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + if total.abs() < f64::MAX / 2.0 && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { return total; } // Each product is split into its rounded value and the part that rounding drops, both exact. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index fae628e3c5..e41bb319a5 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -376,6 +376,8 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe let mut s = Session::new(); // N·(1 - 2^-53) is N - S/2, which rounds up to N; the exact A is -1.5·S, which rounds to -2·S. // MAX - 2^969 + 2^970 rounds to MAX, while adding the rounded MAX - 2^969 and 2^970 overflows. + // MAX·(1 - 2^-53) + 2^971 + 2^970 - 2^917 is past the overflow midpoint by 2^917, which rounding + // the first product drops. let out = log( &mut s, "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ @@ -385,9 +387,12 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe var shift = mat([1, 0, -1, 1, Math.pow(2, 970), 0]);\ vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 969)]), shift).mValueTX === Number.MAX_VALUE);\ try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, 0]), shift); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var near = mat([1 - Math.pow(2, -53), 0, 1, 1, Math.pow(2, 970) - Math.pow(2, 917), 0]);\ + try { app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, Math.pow(2, 971)]), near); vc.log('finite'); }\ catch (e) { vc.log(e.name); }", ); - assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError")]); + assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]); } #[test] From bac470decb57aea5ec4dc54a4685afbf479a2bcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:47:58 -0800 Subject: [PATCH 103/533] Scripts: concatenateMatrix keeps a value that a later term cancels down to products_sum added the rounded products and then the translation, so a rounding error that the translation cancels came back as the result: joining a move by (2^53, 1) with x + y - 2^53 gave an X move of 0 instead of 1. A sum now takes the quick path only when it has one term that is not 0, or when both products and their sum are exact. Every other sum goes through the exact expansion and rounds once. The expansion is held in a fixed array, so a composition does not allocate. Docs: docs/mcp.md and the scripting line in docs/target-app-parity.md state that each joined value is rounded once. --- crates/engine/src/script/dom/matrix.rs | 74 +++++++++++++-------- crates/engine/src/tests/script_dom_prefs.rs | 13 ++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 211ff9e8b0..467a5fc10e 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -103,19 +103,23 @@ fn then(m: Matrix, n: Matrix) -> Matrix { ] } -/// `x·y + z·w + t`. When the whole sum is below half the largest number, and a product at or below the -/// smallest normal number is the only term that is not 0, the sum is taken as numbers are. -/// Otherwise the products are summed past the range of a number and rounded at the end, so a -/// finite value is not lost to a product too large or too small for a number, or to a sum that -/// rounds twice. A product that rounds up to the smallest normal number can have dropped part of a -/// step below it, so it counts as one too small. +/// `x·y + z·w + t`. When at most one of the three terms is not 0 and it is finite, that term is the +/// sum, rounded once. When both products and their sum are exact numbers, adding `t` rounds once. +/// Otherwise the products are summed past the range of a number and rounded at +/// the end, so a finite value is not lost to a product too large or too small for a number, to a +/// sum that rounds twice, or to a rounding error that a later term cancels down to. fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { let (p, q) = (x * y, z * w); - let lost = |v: f64, a: f64, b: f64| a != 0.0 && b != 0.0 && v.abs() <= f64::MIN_POSITIVE; - let alone = |a: f64, b: f64| (a == 0.0 || b == 0.0) && t == 0.0; + let terms = [x != 0.0 && y != 0.0, z != 0.0 && w != 0.0, t != 0.0]; + let total = p + q + t; + if terms.iter().filter(|&&on| on).count() <= 1 && total.is_finite() { + return total; + } + // A product at or above 2^-969 that rounds drops a part a number can hold, so a zero + // remainder shows the product is exact. + let exact = |v: f64, a: f64, b: f64| a == 0.0 || b == 0.0 || (v.abs() >= f64::MIN_POSITIVE * 2f64.powi(53) && a.mul_add(b, -v) == 0.0); let plain = p + q; - let total = plain + t; - if total.abs() < f64::MAX / 2.0 && (!lost(p, x, y) || alone(z, w)) && (!lost(q, z, w) || alone(x, y)) { + if total.is_finite() && exact(p, x, y) && exact(q, z, w) && plain - p == q && plain - q == p { return total; } // Each product is split into its rounded value and the part that rounding drops, both exact. @@ -127,32 +131,50 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] }; let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); - let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Vec::with_capacity(10), grow); - nearest(&exact) + let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); + nearest(exact) +} + +/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at +/// most one more, so the five parts of a sum and the two of a comparison fit. +#[derive(Clone, Copy)] +struct Parts { + v: [Wide; 8], + n: usize, +} + +impl Parts { + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 }; + + fn as_slice(&self) -> &[Wide] { + &self.v[..self.n] + } } /// `sums` with `part` added: values that do not overlap, smallest first, whose sum is exactly the /// sum of `sums` and `part`. The last value is the largest and has the sign of the sum. -fn grow(sums: Vec, part: Wide) -> Vec { +fn grow(sums: Parts, part: Wide) -> Parts { let mut carry = part; - let mut kept = Vec::with_capacity(sums.len() + 1); - for h in sums { - let (sum, rest) = carry.two_sum(h); - if rest.m != 0.0 { - kept.push(rest); + let mut kept = Parts::EMPTY; + let mut keep = |w: Wide| { + if w.m != 0.0 && kept.n < kept.v.len() { + kept.v[kept.n] = w; + kept.n += 1; } + }; + for &h in sums.as_slice() { + let (sum, rest) = carry.two_sum(h); + keep(rest); carry = sum; } - if carry.m != 0.0 { - kept.push(carry); - } + keep(carry); kept } /// The sign of the exact sum of `sums`, `0.0 - v` and `offset`: 1, -1 or 0. -fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { - let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums.to_vec(), grow); - match rest.last() { +fn sign_past(sums: Parts, v: f64, offset: Wide) -> i32 { + let rest = [Wide::of(0.0 - v), offset].into_iter().fold(sums, grow); + match rest.as_slice().last() { Some(w) if w.m > 0.0 => 1, Some(w) if w.m < 0.0 => -1, _ => 0, @@ -163,9 +185,9 @@ fn sign_past(sums: &[Wide], v: f64, offset: Wide) -> i32 { /// rounds to 2^1024 or past it. The sum of the values from the smallest up comes within a step of /// it; the halfway points to the neighbors of that number are then compared with the exact sum, so /// the result is rounded once. -fn nearest(sums: &[Wide]) -> f64 { +fn nearest(sums: Parts) -> f64 { let even = |v: f64| v.to_bits() & 1 == 0; - let mut v = sums.iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); + let mut v = sums.as_slice().iter().fold(Wide::of(0.0), |total, &h| total.two_sum(h).0).value().clamp(f64::MIN, f64::MAX); for _ in 0..4 { // Half the step to the next number up, and to the next number down. Past the largest // number the step is to 2^1024, which is 2^971 away. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index e41bb319a5..c56542973e 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -395,6 +395,19 @@ fn concatenation_rounds_once_at_the_smallest_normal_number_and_the_largest_numbe assert_eq!(out, vec![json!(true), json!(true), json!(true), json!("RangeError"), json!("RangeError")]); } +#[test] +fn concatenation_keeps_a_small_translation_that_a_large_one_cancels() { + let mut s = Session::new(); + // 2^53 + 1 rounds to 2^53, so adding the rounded products and then -2^53 gives 0; the exact X is 1. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var big = Math.pow(2, 53);\ + vc.log(app.concatenateMatrix(mat([1, 0, 0, 1, big, 1]), mat([1, 0, 1, 1, -big, 0])).mValueTX);", + ); + assert_eq!(out, vec![json!(1)]); +} + #[test] fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_number() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 129e7e53a8..bc273c29ed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2992,7 +2992,8 @@ other files through `$`: `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own rules: `concatenateMatrix(m, n)` applies `m` and then `n`, and the other `concatenate…` functions apply the record and then the transformation they make; a left-out move or angle is 0, a left-out `scaleX` is 100 and a left-out - `scaleY` is `scaleX`; quarter turns are exact; a matrix whose determinant is 0 is singular, and `invertMatrix` of one + `scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products + rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`, and a result too large for a number throws a `RangeError`. - `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4ac11713c..bff1400bb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1109,7 +1109,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. + - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: 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/). `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`. `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`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. From 2666d077129235b965ad11620f54db55b88fefd0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 19:51:43 -0800 Subject: [PATCH 104/533] Scripts: a list made with items counts each one in its revision Main's new_items builds a list's items in one step without counting them in the list's revision, so a palette event for a list made with two items carried a revision the list no longer had and was refused. Count each item as add does. Also apply rustfmt to two lines from the merge. --- crates/js/src/scriptui.rs | 12 +++++++++++- crates/ui-egui/src/dialogs/script_window.rs | 4 +--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 45ce3b4496..1f15cfb006 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -885,6 +885,9 @@ fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { let kept = list(i, &items, false)?; i.temp_roots.push(Value::Object(kept)); set_items(i, o, kept)?; + // Each item counts as one change of the list's items ([`REVISION`]), as `add` counts it. + let revision = number_slot(i, o, REVISION)? + items.len() as f64; + set_slot(i, o, REVISION, Value::Number(revision))?; let copy = list(i, &items, true)?; set_open(i, o, "items", Value::Object(copy))?; Ok(items.len()) @@ -1204,7 +1207,14 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, (event, phase, cutoff): (ObjId, f64, f64), taker: Taker) -> JsResult> { +fn run_listeners( + i: &mut Interp, + at: ObjId, + ty: &str, + capture: Option, + (event, phase, cutoff): (ObjId, f64, f64), + taker: Taker, +) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index ae84b4138f..074b2a5567 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -333,9 +333,7 @@ impl StackDialog for ScriptWindow { let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); // The body can run twice in a pass (measure, then paint), so it only reports what the // person did; the dialog applies the last run's report after the container. - let shown = dialog.show(ui, |ui, _| { - controls(ui, window, drafts, waiting) - }); + let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting)); let pass = shown.inner.unwrap_or_default(); if pass.layer.is_some() { self.layer = pass.layer; From bb80534f3ea8b90512ff98f07e15442e778d9e93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:37:42 -0800 Subject: [PATCH 105/533] Scripts: path edits honor locked guides, keep selections and stay atomic PathItem handles carry the document's revert count, as main's page item handles now do, so points and new paths resolve again. resize() scales and changes the stroke weight in one step; paint writes that the command skips throw; Lock Guides refuses edits and removeAll on guide paths; removing a point remaps the selected anchors and segments; new paths go on the active layer while a group is isolated; translate's reflected parameters include changePositions; point tracking revisits only the paths an edit changed. StoryRange lists its fillColor, strokeColor and strokeWeight rows. --- crates/engine/src/script/dom/paths.rs | 177 +++++++++++++---- crates/engine/src/tests/script_dom_paths.rs | 184 ++++++++++++++++++ crates/engine/src/tests/script_text.rs | 4 +- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- 4 files changed, 323 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 1f308db41e..808567d3b6 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -115,6 +115,8 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { Some(cannot_edit(id)) } else if super::on_locked_artboard(h, st, id) { Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))) } else { None } @@ -158,9 +160,10 @@ fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d }) } +/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count). fn path_ref(h: &super::Host, item: Item) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + host_ref("PathItem", &handle) } /// How many points a path with the subpaths `subs` has. @@ -264,9 +267,15 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) /// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active /// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { +fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); let r = f(); + if let Some((uid, isolation)) = isolation + && let Some(st) = h.session.borrow_mut().document_mut(uid) + { + st.isolation = isolation; + } h.session.borrow_mut().draw_mode = kept; r } @@ -283,7 +292,13 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } - keeping_paint(h, || edit_item(h, item, id, ¶ms)) + let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); + } + Ok(result) } /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color @@ -378,11 +393,16 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); + if h.session.borrow().menu.guides_locked + && let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); + } let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) - }); + Ok((ids, refused, on_locked)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); @@ -407,7 +427,8 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { /// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -566,7 +587,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -1137,19 +1159,22 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - if (sx != 100.0 || sy != 100.0) - && let (Some(r), _) = item_rect(h, item, false)? - { - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } - Ok(Data::Undefined) + // The scale and the stroke weight change together, or neither does. + super::atomically(h, |h| { + if (sx != 100.0 || sy != 100.0) + && let (Some(r), _) = item_rect(h, item, false)? + { + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(Data::Undefined) + }) } // ---- PathPoints ---- @@ -1216,7 +1241,10 @@ fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { let node = { let s = h.session.borrow(); - s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone()); + node_arc(&st.doc, NodeId(key.1)).cloned() + }) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1242,31 +1270,39 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// at is skipped, as are its paths. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { - let seen = h.dom.point_nodes.borrow(); - if seen.is_empty() { - return; - } let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); - // The documents that changed since the last look, kept as they are now. - let mut changed = std::collections::HashSet::new(); - for (uid, _) in seen.keys() { - if changed.contains(uid) { - continue; + let seen = h.dom.point_nodes.borrow(); + let mut keys = Vec::new(); + docs.retain(|uid, before| { + let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + if after.is_some_and(|after| Arc::ptr_eq(before, after)) { + return true; } - match s.documents().iter().find(|d| d.uid == *uid) { - Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => {} - Some(st) => { - docs.insert(*uid, st.doc.clone()); - changed.insert(*uid); + let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { + Some(item) => node_arc(before, item.id).into_iter().collect(), + None => before.layers.iter().collect(), + }; + while let Some(node) = todo.pop() { + if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + continue; } - None => { - docs.remove(uid); - changed.insert(*uid); + let key = (*uid, node.id.0); + if seen.contains_key(&key) { + keys.push(key); + } + if let Some(children) = node.children() { + todo.extend(children); } } - } - seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + if let Some(after) = after { + *before = after.clone(); + true + } else { + false + } + }); + keys }; let editing = h.dom.editing.get(); for (uid, id) in keys { @@ -1549,16 +1585,71 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { + let mut selection = with_doc(h, item.doc, |_, st| st.selection.clone()); + // The endpoints of the path's selected segments, before the point goes. + let old_ends: std::collections::BTreeSet<(usize, usize)> = match selection.segments.get(&item.id) { + Some(segments) => read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())])) + .flatten() + .collect() + })?, + None => std::collections::BTreeSet::new(), + }; + let removed = edit_points(h, item, |subs| { if let Some((s, j)) = locate(subs, i) && let Some(sp) = subs.get_mut(s) { + let (n, closed) = (sp.anchors.len(), sp.closed); sp.anchors.remove(j); if sp.anchors.is_empty() { subs.remove(s); } + Some((s, j, n, closed)) + } else { + None } })?; + if let Some((s, j, n, closed)) = removed { + let remap = |(sub, at): (usize, usize)| { + if sub == s && (n == 1 || at == j) { None } else { Some((sub - usize::from(sub > s && n == 1), at - usize::from(sub == s && at > j))) } + }; + // Anchors held only as a selected segment's endpoints come back from the kept segments below. + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + *anchors = anchors.iter().copied().filter(|a| !old_ends.contains(a)).filter_map(remap).collect(); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + *segments = segments + .iter() + .copied() + .filter(|&(sub, at)| sub != s || (at != j && (j == 0 || at != j - 1) && (!closed || j != 0 || at != n - 1))) + .filter_map(remap) + .collect(); + let ends: Vec<_> = read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| { + subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())]) + }) + .flatten() + .collect() + })?; + // Directly selected anchors stay selected; the kept segments' endpoints are added. + selection.anchors.entry(item.id).or_default().extend(ends); + } + if let Some((id, at)) = selection.key_anchor + && id == item.id + { + selection.key_anchor = remap(at).map(|at| (id, at)); + } + if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { + selection.remove(item.id); + } + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + st.selection = selection; + } + } cut_points(h, item); Ok(Data::Undefined) } @@ -1570,7 +1661,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec { let changes = [("changePositions", "boolean"), ("changeFillPatterns", "boolean"), ("changeFillGradients", "boolean"), ("changeStrokePattern", "boolean")]; let mut translate = vec![("deltaX", "number"), ("deltaY", "number")]; - translate.extend(changes.iter().skip(1)); + translate.extend(changes); let mut rotate = vec![("angle", "number")]; rotate.extend(changes); rotate.push(("rotateAbout", "Transformation")); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 591f0f1b05..b4da0d6850 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -299,6 +299,190 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ + var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ + vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ + vc.log(p.pathPoints[0].selected);", + ); + assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); + assert!(s.active().unwrap().selection.contains(b)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(s.active().unwrap().selection.contains(b)); + + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); +} + +#[test] +fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { + let (mut s, a, _) = doc(); + s.execute( + "path.setAnchors", + &json!({"id": a.0, "subpaths": [ + {"anchors": [{"x": 0, "y": 0}]}, + {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} + ]}), + ) + .unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); +} + +#[test] +fn locked_guides_refuse_path_edits_and_bulk_removal() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.pathPoints[0].anchor = [0, 0]", + "p.pathPoints[0].remove()", + "p.pathPoints.removeAll()", + "p.setEntirePath([[0, 0], [1, 1]])", + "p.closed = false", + "p.translate(1, 0)", + "p.filled = false", + "p.strokeWidth = 12", + "app.activeDocument.pathItems.removeAll()", + ] { + let out = + log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); + } + assert!(is_guide(&s, a)); + s.set_guides_locked(false); + log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); + assert_ne!(art(&s), before); +} + +#[test] +fn document_path_creators_use_the_active_layer_during_isolation() { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let (mut s, a, b) = doc(); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let before = node(&s, group); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let st = s.active().unwrap(); + let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); + assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); + assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); + assert_eq!(node(&s, group), before, "{create}"); + assert_eq!(st.isolation, Some(group), "{create}"); + assert_eq!(st.selection, selection, "{create}"); + assert_eq!(undo_steps(&s), steps + 1, "{create}"); + } +} + +#[test] +fn paint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + for unpainted in [false, true] { + let (mut s, a, _) = doc(); + if unpainted { + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + } + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({ + "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + let path = paths[0]; + s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.fillColor = c", + "p.strokeColor = c", + "p.filled = !p.filled", + "p.stroked = !p.stroked", + "p.strokeWidth = 12", + "p.strokeCap = StrokeCap.ROUNDENDCAP", + "p.strokeJoin = StrokeJoin.BEVELENDJOIN", + "p.strokeMiterLimit = 22", + "p.strokeDashes = [3, 4]", + ] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ + try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" + ), + ); + assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); + } + } + } +} + +#[test] +fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { + let (mut s, a, b) = doc(); + for i in 0..100 { + rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); + } + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ + for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ + for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ + var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ + vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ + try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ + paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ + vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ + try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", + a = a.0, + b = b.0 + ), + ); + assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); +} + #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 0decf96eaf..29b676a377 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -360,7 +360,9 @@ fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character( var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", ); assert_eq!(plain(&s, id), "\u{1F600}!X"); - assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's + // end joins the range. + assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]); // An empty range there sits after the character too, and styling it changes nothing. let runs = paints(&s, id); let out = log( diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1b74138da6..2a8b017f06 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -251,12 +251,12 @@ const INSIDE: &[(&str, &str)] = &[ "StoryRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ - contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \ getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ - strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ underline underline= verticalScale verticalScale= words", ), ("StoryCharacters.", "prototype"), From 20f06e95866127f9177a2c350f9199f4f9dd1f8f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:37:43 -0800 Subject: [PATCH 106/533] Scripts: transforms measure clipped art against the canvas and keep tiny moves A transform of a clipping group or clipped layer now measures each object inside it against the canvas limit, as the native file's canvas check does, so a clipped object cannot be moved past the canvas while its clipping path stays inside. A pure move is applied as a translation, so a move far smaller than the pivot's coordinates still moves the object, and a transform that changes nothing is not measured. The transform tests build the 30 x 40 pt rectangle on top, since pageItems lists art topmost first, and the tests from main that named rotate as a member not available yet, the overprint preview error and the preset title limit follow main's current behavior. --- crates/engine/src/script/dom/transform.rs | 41 ++++++++++++----- crates/engine/src/tests/script_dom.rs | 18 +++----- .../engine/src/tests/script_dom_transform.rs | 46 ++++++++++++++++++- 3 files changed, 81 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 3f056589b1..7515fe42e3 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -117,17 +117,30 @@ fn anchor(h: &Host, item: Item, r: Rect, d: &Data) -> std::result::Result Affine { let [a, b, c, d, tx, ty] = m; - let page = Affine::new([a, 0.0 - b, 0.0 - c, d, tx, 0.0 - ty]); - Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2()) + let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty); + if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] { + return Affine::translate((tx, ty)); + } + Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y)) } /// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol -/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. +/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The +/// object is measured whole, and a group is looked into object by object, as the native file's +/// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its +/// clipping path's and leave out the art it clips. fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { + fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool { + if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) { + n.children().into_iter().flatten().all(|c| within(c, symbols)) + } else { + n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range) + } + } d.node(id).is_some_and(|n| { let mut n = n.clone(); n.transform(xf, false); - n.geometric_bounds_with(&d.symbol_boxes()).is_none_or(crate::sanity::rect_in_range) + within(&n, &d.symbol_boxes()) }) } @@ -141,17 +154,19 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) if matrix::singular(m) { return Err(HostError::Error("the transformation is singular and would flatten the object".into())); } - let (locked, on_locked, bounds, uses_pattern) = with_doc(h, item.doc, |_, st| { + let (locked, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let mut locked = d.ancestry(item.id).is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); - let mut uses = false; + let (mut uses, mut clipped) = (false, false); if let Some(n) = d.node(item.id) { n.walk(&mut |c| { locked |= c.locked; uses |= vectorcraft_doc::pattern::uses_pattern(c, None); + clipped |= + matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); }); } - (locked, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses) + (locked, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped) }); if locked { return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); @@ -168,12 +183,16 @@ fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) if opts.strokes && !opts.objects { return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); } - if let Some(r) = bounds.filter(|_| opts.objects) { + if opts.objects && xf != Affine::IDENTITY { // The transformed corners of the bounds hold the transformed object. When one of them is - // past the canvas, the transformed object itself is measured. - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; + // past the canvas, or the object holds a clipping group (whose bounds leave out the art + // it clips), the transformed object itself is measured. let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; - if !corners.iter().all(|p| inside(xf * *p)) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { + let outside = bounds.is_some_and(|r| { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; + !corners.iter().all(|p| inside(xf * *p)) + }); + if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { return Err(HostError::Range("the transformation would take the object past the canvas".into())); } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d4ffe2523a..196f29bafd 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1495,26 +1495,22 @@ fn overprint_preview_is_refused_before_a_document_is_made() { let mut s = Session::new(); let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.OverprintPreview; app.documents.addDocument('Print', p);"); - assert!(e.contains("OverprintPreview is not available yet"), "{e}"); + assert!(e.contains("overprintPreview"), "{e}"); assert!(s.documents().is_empty()); } #[test] fn document_presets_hold_a_limited_amount_of_data() { let mut s = Session::new(); - // A 4 MiB string: replacing one preset's value does not add up, 17 presets holding it do. + // A 4,096-byte title fits and replacing it does not add up; one byte more is refused. let out = log( &mut s, - "var t = 'x'; for (var k = 0; k < 22; k++) t += t; var p = new DocumentPreset();\ + "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset();\ for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);", ); - assert_eq!(out, vec![json!(4 << 20)]); - let e = failure( - &mut s, - "var t = 'x'; for (var k = 0; k < 22; k++) t += t;\ - for (var k = 0; k < 17; k++) { var p = new DocumentPreset(); p.title = t; }", - ); - assert!(e.contains("DocumentPresets can hold at most"), "{e}"); + assert_eq!(out, vec![json!(4096)]); + let e = failure(&mut s, "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset(); p.title = t + 'x';"); + assert!(e.contains("the title is too long"), "{e}"); } #[test] @@ -2217,7 +2213,7 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index b861716b35..e5f1fad0c3 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -23,12 +23,13 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) } -/// A 400 × 300 pt document with a 30 × 40 pt rectangle and a 50 × 50 pt one above it. +/// A 400 × 300 pt document with a 30 × 40 pt rectangle above a 50 × 50 pt one, so that `pageItems` +/// (topmost first) lists the 30 × 40 pt one first. fn doc() -> (Session, NodeId, NodeId) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); (s, a, b) } @@ -169,6 +170,47 @@ fn a_move_too_small_to_round_away_moves_the_object() { assert_eq!(undo_steps(&s), steps + 1); } +#[test] +fn a_tiny_move_about_a_distant_center_moves_the_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The center is at x = 100, where 1e-15 rounds away; the left edge at 0 keeps it. + rect(&mut s, 0.0, 0.0, 200.0, 10.0); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0], l = i.left;\ + i.transform({mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: 1e-15, mValueTY: 0}); vc.log(i.left > l);", + ); + assert_eq!(out, vec![json!(true)]); +} + +#[test] +fn a_scale_and_translation_about_the_center_straddle_the_origin() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 127, "y1": 0, "x2": 129, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + log( + &mut s, + "app.activeDocument.pageItems[0].transform({mValueA: Math.pow(2, -55), mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: -128, mValueTY: 0});", + ); + let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap(); + assert!(r.x0 < 0.0 && r.x1 > 0.0, "{r:?}"); +} + +#[test] +fn a_clipped_object_moved_past_the_canvas_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let far = rect(&mut s, 0.9 * crate::MAX_COORD, 0.0, 10.0, 10.0); + let mask = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [far.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].translate({}, 0);", 0.2 * crate::MAX_COORD)); + assert!(e.contains("past the canvas"), "{e}"); + assert_eq!(s.active().unwrap().doc.node(far), before.node(far)); +} + #[test] fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() { let mut s = Session::new(); From e9010cd36384e0b643b1fd3e6ca230dac9e85636 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:03:07 -0800 Subject: [PATCH 107/533] Scripts: point handles go stale after a revert; flush keeps only live selections PathPoints and PathPoint handles carry the document's revert count. Writing point edits drops selected anchors and segments that no longer exist, in the same step as the edit. Overprint writes that the command skips throw, and changeFillGradients true with changePositions false throws until it is available. --- crates/engine/src/script/dom/paths.rs | 65 +++++++---- crates/engine/src/tests/script_dom_paths.rs | 113 ++++++++++++++++++++ 2 files changed, 159 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 808567d3b6..0a5aeacf31 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -54,7 +54,8 @@ //! are locked; assigning the value the path has runs no command. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, -//! so `changeFillGradients` false throws an error that says it is not available yet. +//! so `changeFillGradients` false throws an error that says it is not available yet, as does +//! `changeFillGradients` true with `changePositions` false. use std::rc::Rc; use std::sync::Arc; @@ -70,8 +71,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, - on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, + edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -142,9 +143,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result std::result::Result { +/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; path_of(h, &path_ref(h, Item { doc, id })) } @@ -255,7 +259,27 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + super::atomically(h, |h| { + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + let selection = &mut st.selection; + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count())); + if segments.is_empty() { + selection.segments.remove(&item.id); + } + } + if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { + selection.key_anchor = None; + } + if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || point_count(&subs) == 0 { + selection.remove(item.id); + } + } + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})) + })?; Ok(()) } @@ -293,8 +317,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r o.entry("ids").or_insert_with(|| json!([item.id.0])); } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; - if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") - && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + let count = if id == "object.setOverprint" { "changed" } else { "objects" }; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) { return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); } @@ -603,8 +628,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { fn path_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - let [high, low] = id_parts(item.id); - Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + Ok(host_ref("PathPoints", &handle)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { @@ -1091,6 +1116,9 @@ fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::R if flags[2] == Some(false) { return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); } + if flags[0] == Some(false) && flags[2] == Some(true) { + return Err(HostError::Error(format!("{} true with {} false is not available yet", names[2], names[0]))); + } if let (Some(f), Some(s)) = (flags[1], flags[3]) && f != s { @@ -1181,8 +1209,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - path_at(h, *run, *uid, *high, *low) + let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + path_at(h, *run, *uid, *high, *low, *reverts) } fn points_length(h: &super::Host, a: &[Data]) -> Answer { @@ -1196,8 +1224,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { } fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) + let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec(); + handle.extend([float(i as u64), float(point_cuts(h, item))]); + host_ref("PathPoint", &handle) } /// How many times the points read of `item` have gone stale, after [`see_points`] notes a change @@ -1368,8 +1397,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); } @@ -1576,9 +1605,7 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { out })?; h.charge_call(picked.len() as u64)?; - let [high, low] = id_parts(item.id); - let cuts = float(point_cuts(h, item)); - let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); Ok(Data::Array(points)) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b4da0d6850..b08ed50e9a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -329,6 +329,56 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { + for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = selected_anchors(&s, a); + let steps = undo_steps(&s); + let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); + assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); + assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); + let selection = &s.active().unwrap().selection; + assert!(selection.contains(b)); + assert_eq!(selected_anchors(&s, a), anchors); + let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); + assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); + } + } +} + +#[test] +fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = node(&s, a); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ + p.name = 'changed'; vc.run('file.revert');\ + try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ + var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ + fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" + ), + ); + assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); + assert_ne!(node(&s, a).path_data(), before.path_data()); + s.execute("file.revert", &json!({})).unwrap(); + } +} + #[test] fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { let (mut s, a, _) = doc(); @@ -458,6 +508,46 @@ fn paint_writes_refuse_generated_graph_design_paths() { } } +#[test] +fn overprint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut s, a, _) = doc(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); + let before = (art(&s), undo_steps(&s)); + for property in ["fillOverprint", "strokeOverprint"] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ + try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" + ), + ); + assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); + assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); + assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); + } + } +} + #[test] fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { let (mut s, a, b) = doc(); @@ -1087,6 +1177,29 @@ fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); } +#[test] +fn transforms_refuse_moving_gradients_without_the_path() { + for transform in + ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] + { + let (mut s, a, b) = doc(); + s.execute( + "paint.setFill", + &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); + let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); + assert!( + out[1].as_str().unwrap().contains("changeFillGradients true with changePositions false is not available yet"), + "{transform}: {out:?}" + ); + assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); + } +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); From 5dbd4357c182f392dcb3717f02ea6e437319bc93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:21:54 -0800 Subject: [PATCH 108/533] Scripts: rasterize clips to fractional clip bounds and refuses clipping paths Rasterize with clipBounds keeps the pixel grid outward and clips the art to the exact rectangle, so a partial edge pixel keeps only its in-bounds coverage. A clipping path given by id is refused, with a message for clip groups and for clipped layers. app.open sends the file's read warnings to the console. A multi-file export refuses a destination that is a folder before writing any file. The DocumentPreset byte tests use the run's heap limit, which replaced the fixed 4 MB limit; the 4 MB sentence leaves docs/mcp.md. The controlBounds row matches main, where it has no setter. The two new script file messages stay English only, as AGENTS.md asks. --- crates/engine/src/cmd/fileio/export_names.rs | 3 + crates/engine/src/cmd/menucmds.rs | 28 +++++- crates/engine/src/script/dom/save_open.rs | 11 +++ crates/engine/src/tests/script_dom.rs | 98 +++++++++++-------- .../engine/src/tests/script_raster_capture.rs | 60 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 - crates/ui-egui/src/i18n/cs.tsv | 2 - crates/ui-egui/src/i18n/da.tsv | 2 - crates/ui-egui/src/i18n/de.tsv | 2 - crates/ui-egui/src/i18n/el.tsv | 2 - crates/ui-egui/src/i18n/es.tsv | 2 - crates/ui-egui/src/i18n/fi.tsv | 2 - crates/ui-egui/src/i18n/fr.tsv | 2 - crates/ui-egui/src/i18n/hi.tsv | 2 - crates/ui-egui/src/i18n/hu.tsv | 2 - crates/ui-egui/src/i18n/id.tsv | 2 - crates/ui-egui/src/i18n/it.tsv | 2 - crates/ui-egui/src/i18n/ja.tsv | 2 - crates/ui-egui/src/i18n/ka.tsv | 2 - crates/ui-egui/src/i18n/ko.tsv | 2 - crates/ui-egui/src/i18n/nl.tsv | 2 - crates/ui-egui/src/i18n/pl.tsv | 2 - crates/ui-egui/src/i18n/pt-br.tsv | 2 - crates/ui-egui/src/i18n/ru.tsv | 2 - crates/ui-egui/src/i18n/sv.tsv | 2 - crates/ui-egui/src/i18n/tr.tsv | 2 - crates/ui-egui/src/i18n/uk.tsv | 2 - crates/ui-egui/src/i18n/vi.tsv | 2 - crates/ui-egui/src/i18n/zh-hans.tsv | 2 - crates/ui-egui/src/i18n/zh-hant.tsv | 2 - docs/mcp.md | 8 +- 32 files changed, 160 insertions(+), 100 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..6c49622553 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,6 +88,9 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::may_write(p)?; + if std::path::Path::new(p.as_str()).is_dir() { + return Err(EngineError::Other(format!("{p}: is a folder, not a file"))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index a32d7dd3be..c441c73c6e 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -899,6 +899,7 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; let mut b = drawn.inflate(pad, pad); + let mut clip_bounds = None; if let Some(v) = p.get("clipBounds").filter(|v| !v.is_null()) { let [x0, y0, x1, y1] = super::finite_numbers::<4>(v).ok_or_else(|| bad(cmd, "clipBounds must be four finite numbers [x0, y0, x1, y1]"))?; if x1 <= x0 || y1 <= y0 { @@ -910,11 +911,13 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p if on_art.width() <= 0.0 || on_art.height() <= 0.0 { return Err(bad(cmd, "clipBounds does not overlap the art")); } + clip_bounds = Some(clip_rect); b = b.intersect(clip_rect); } let scale = ppi / 72.0; - // Snap to whole pixels. - let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale); + // The image covers the bounds in whole pixels. + let px = |len: f64| (len * scale).ceil().max(1.0); + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.width()) / scale, b.y0 + px(b.height()) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -932,7 +935,15 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .flatten() .map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)); - let tmp = isolated_doc(doc, nodes); + let mut tmp = isolated_doc(doc, nodes); + if let Some(rect) = clip_bounds { + let children = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()).map(std::mem::take).unwrap_or_default(); + let art = Node::group(tmp.alloc_id(), children); + let art = super::rasterfx::clip_group(&mut tmp, vectorcraft_geom::shapes::rectangle(rect), vectorcraft_geom::FillRule::NonZero, art); + if let Some(children) = tmp.layers.first_mut().and_then(|layer| Arc::make_mut(layer).children_mut()) { + children.push(Arc::new(art)); + } + } let opts = raster.render_options(RasterFormat::Png); let (img, warning) = render_pixels(&tmp, region, scale, &opts, look.color_model)?; let png = @@ -977,6 +988,15 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if !parent.is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { return Err(bad(cmd, format!("id {} is part of a compound path or another object; give that object's id", id.0))); } + // A clipping path's image would clip its siblings to a rectangle. + if parent.is_some_and(Node::clips) && d.position(*id).is_some_and(|(_, i, _)| i == 0) { + let message = if parent.is_some_and(Node::is_layer) { + "is a layer's clipping path and cannot be rasterized on its own" + } else { + "is a clipping path; give its clip group's id" + }; + return Err(bad(cmd, format!("id {} {message}", id.0))); + } if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b8491cd284..618d1d4e91 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -705,6 +705,17 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }), _ => None, }; + // Each warning from reading the file (content left out, an image that could not be read) goes + // to the console, as `addDocument` sends its profile's. + if let Data::Object(items) = &r { + for (k, v) in items { + if let ("warnings", Data::Array(ws)) = (k.as_str(), v) { + for w in ws.iter().filter_map(|w| if let Data::String(w) = w { Some(w) } else { None }) { + super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } let s = h.session.borrow(); let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea8cf2a4ea..b80020077e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1476,47 +1476,6 @@ fn document_preset_applies_only_its_given_fields() { assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); } -/// The presets of one run hold at most 4 MB of settings together; a setting that replaces another -/// gives back what the old value held. -#[test] -fn document_preset_settings_are_limited_in_bytes() { - let mut s = Session::new(); - // A title holds at most 4,096 bytes, so 1,005 presets with such a title and their six defaults - // hold 4,192,860 bytes, and the next preset's defaults bring that to 4,192,934 of 4,194,304. - let out = log( - &mut s, - "var big = new Array(4097).join('a'), ps = [];\ - for (var i = 0; i < 1005; i++) { var p = new DocumentPreset(); p.title = big; ps.push(p); }\ - var q = new DocumentPreset(); ps[0].title = big; vc.log(ps[0].title.length);\ - try { q.title = big; } catch (e) { vc.log([e.name, e.message]); }\ - vc.log(q.title === undefined); ps[0].title = 'short'; q.title = big; vc.log(q.title.length);", - ); - assert_eq!(out[0], json!(4096), "a setting assigned again replaces what it held"); - assert_eq!(out[1], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[2], json!(true), "a refused setting is not stored"); - assert_eq!(out[3], json!(4096), "replacing a setting frees what it held"); -} - -/// A new `DocumentPreset`'s default settings count toward the 4 MB, so one that would pass the -/// limit is refused and leaves the count as it was. -#[test] -fn a_new_document_preset_is_refused_past_the_byte_limit() { - let mut s = Session::new(); - // The six defaults hold 74 bytes and a 4,096-byte title 4,098, so 1,005 presets with such a - // title and one more with a 1,358-byte title leave 10 bytes of the 4 MB free. - let out = log( - &mut s, - "var big = new Array(4097).join('a');\ - for (var i = 0; i < 1005; i++) { var f = new DocumentPreset(); f.title = big; }\ - var p = new DocumentPreset(); p.title = new Array(1359).join('b');\ - try { new DocumentPreset(); vc.log('made'); } catch (e) { vc.log([e.name, e.message]); }\ - p.documentBleedLink = true; vc.log(p.documentBleedLink); p.title = 'x'; vc.log(new DocumentPreset().width);", - ); - assert_eq!(out[0], json!(["RangeError", "the DocumentPresets of a script can hold at most 4 MB of settings"])); - assert_eq!(out[1], json!(true), "a refused preset adds nothing to the count"); - assert_eq!(out[2], json!(612), "a preset below the limit is still made"); -} - #[test] fn headless_add_document_dialog_fails_without_creating() { let mut s = Session::new(); @@ -1565,6 +1524,63 @@ fn add_document_takes_only_a_document_preset() { assert_eq!(out, vec![json!(500)]); } +#[test] +fn document_preset_settings_are_limited_in_bytes() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var presets = [];\ + for (var k = 0; k < 1000; k++) { var p = new DocumentPreset(); p.title = 'old'; presets.push(p); }\ + var message = '';\ + try { for (var k = 0; k < presets.length; k++) presets[k].title = title; }\ + catch (e) { message = e.name + ': ' + e.message; }\ + vc.log(message); vc.log(k > 0 && k < presets.length); vc.log(presets[k].title);\ + presets[0].title = 'x'; presets[k].title = title;\ + vc.log(presets[0].title); vc.log(presets[k].title === title);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!( + out, + vec![ + json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)), + json!(true), + json!("old"), + json!("x"), + json!(true), + ] + ); +} + +#[test] +fn a_new_document_preset_is_refused_past_the_byte_limit() { + use crate::script::TEST_ENGINE_HEAP; + let preset_bytes = 6 * std::mem::size_of::() + "DocumentArtboardLayout.GridByRow".len(); + TEST_ENGINE_HEAP.with(|h| h.set(Some(2 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + &format!( + "#targetengine presets\nvar title = 'a'; while (title.length < 4092) title += 'a';\ + var first = new DocumentPreset(); first.title = title;\ + try {{ for (var k = 0; k < 2000; k++) {{ var p = new DocumentPreset(); p.title = title; }} }} catch (e) {{}}\ + var message = '';\ + try {{ for (var k = 0; k < 10000; k++) new DocumentPreset(); }}\ + catch (e) {{ message = e.name + ': ' + e.message; }}\ + vc.log(message); vc.log(k < 10000);\ + first.title = title.substring({preset_bytes});\ + vc.log((new DocumentPreset()).width);\ + var again = ''; try {{ new DocumentPreset(); }} catch (e) {{ again = e.name + ': ' + e.message; }}\ + vc.log(again);" + ), + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + let message = json!(format!("RangeError: the DocumentPreset settings would hold more than {} bytes", 2 << 20)); + assert_eq!(out, vec![message.clone(), json!(true), json!(612), message]); +} + #[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())); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 1dbbfe7b75..0e70175844 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -141,6 +141,66 @@ fn script_rasterize_clip_bounds_cut_the_image() { assert_eq!(images(&s), vec![(15, 40)]); } +/// A clip rectangle that ends partway through a pixel keeps partial coverage in the image's last +/// column and row. +#[test] +fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 72; o.transparency = true; d.rasterize(a, [10, 280, 25.5, 240.5], o);" + ), + ); + assert_eq!(images(&s), vec![(16, 40)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + assert_eq!(pixels.get_pixel(14, 20)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(15, 20)[3]), "the last column keeps only its in-bounds coverage"); + assert_eq!(pixels.get_pixel(7, 38)[3], 255); + assert!((1..255).contains(&pixels.get_pixel(7, 39)[3]), "the last row keeps only its in-bounds coverage"); +} + +/// A clip rectangle from a fractional origin that spans whole pixels keeps every one of them, +/// though the subtraction of its edges is not exact. +#[test] +fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { + for (right, width, partial) in [(10.7, 3, false), (10.75, 4, true)] { + let (mut s, ..) = doc(); + log( + &mut s, + &format!( + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [10.4, 280, {right}, 240], o);" + ), + ); + assert_eq!(images(&s), vec![(width, 400)]); + let st = s.active().unwrap(); + let blob = st.doc.images.values().next().unwrap(); + let pixels = image::load_from_memory(&blob.bytes).unwrap().to_rgba8(); + let alpha = pixels.get_pixel(width - 1, 200)[3]; + if partial { + assert!((1..255).contains(&alpha), "the last column keeps only its in-bounds coverage"); + } else { + assert_eq!(alpha, 255, "the whole boundary pixel stays opaque"); + } + } +} + +#[test] +fn script_rasterize_rejects_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The clipping path is `b`, the topmost of the two. + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [b.0]})).unwrap_err().to_string(); + assert!(e.contains("is a clipping path"), "{e}"); + assert_eq!(undo_steps(&s), undo, "a refused clipping path adds no undo step"); + s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); +} + #[test] fn script_rasterize_disposes_several_sources_in_one_step() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index e76a217f2a..3c910cda0b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -127,7 +127,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds controlBounds= duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 0c091dcc91..c451ec9811 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6647,8 +6647,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi -@msg Script file is read-only El fitxer de l’script és només de lectura -@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4309654e8d..d2a89194fa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5429,8 +5429,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis -@msg Script file is read-only Soubor skriptu je jen pro čtení -@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d356fd7ab2..70c167b084 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,8 +88,6 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning -@msg Script file is read-only Scriptfilen er skrivebeskyttet -@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 3cab0128fe..e2ce6c9202 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5006,8 +5006,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet -@msg Script file is read-only Skriptdatei ist schreibgeschützt -@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 5bc9c90d1a..51b04c5526 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2838,8 +2838,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή -@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση -@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 1d177afc44..053e35e721 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5116,8 +5116,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura -@msg Script file is read-only El archivo del script es de solo lectura -@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index db1a87dbed..05c77549a0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5359,8 +5359,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten -@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa -@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 29a520a0a9..8f843cc11f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5073,8 +5073,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture -@msg Script file is read-only Le fichier du script est en lecture seule -@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 323635ebc9..3bc5aaf219 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7850,8 +7850,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है -@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है -@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index eb7b957794..fedcfcf62b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5951,8 +5951,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva -@msg Script file is read-only A parancsfájl fájlja csak olvasható -@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e43c36b300..3c434256fa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8913,8 +8913,6 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis -@msg Script file is read-only File skrip hanya dapat dibaca -@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cd54480a25..13d0656137 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5144,8 +5144,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura -@msg Script file is read-only Il file dello script è di sola lettura -@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 32eabfa175..97606b7e76 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5980,8 +5980,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません -@msg Script file is read-only スクリプトのファイルは読み取り専用です -@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index cbfae1b8d5..a8d2240536 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8653,8 +8653,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის -@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია -@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 839151841b..96e84b418e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5909,8 +5909,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 -@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 -@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 90facd6389..fada1fc205 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,8 +90,6 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven -@msg Script file is read-only Het scriptbestand is alleen-lezen -@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3cc4572864..01d3571047 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5246,8 +5246,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu -@msg Script file is read-only Plik skryptu jest tylko do odczytu -@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5e9c84ef5e..e3dd5ffeda 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6291,8 +6291,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação -@msg Script file is read-only O arquivo do script é somente leitura -@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 59d5006547..a2235998eb 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5141,8 +5141,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи -@msg Script file is read-only Файл скрипта доступен только для чтения -@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1a6a11ca81..41bda9072e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5014,8 +5014,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning -@msg Script file is read-only Skriptets fil är skrivskyddad -@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 7a624802e4..0ee286faa1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4842,8 +4842,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil -@msg Script file is read-only Betiğin dosyası salt okunur -@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 39c04fe34e..e9dd432e72 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5128,8 +5128,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису -@msg Script file is read-only Файл скрипту доступний лише для читання -@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8d10194145..8e9d5cac87 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5641,8 +5641,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi -@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc -@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 52440db23c..a7e94e826f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5636,8 +5636,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 -@msg Script file is read-only 脚本的文件为只读 -@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a12a6a61cc..3a86a5b728 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2977,8 +2977,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 -@msg Script file is read-only 指令碼的檔案為唯讀 -@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index e427f114c3..0066455f24 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2868,8 +2868,7 @@ other files through `$`: `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()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. The settings of the `DocumentPreset` objects one run makes hold at most - 4 MB together, and an assignment past that throws a `RangeError`. Assigning one of its settings checks the value's kind: a value of the + starts with the defaults that page gives. Assigning one of its settings checks the value's kind: a value of the setting's enumeration, a finite number, a `title` string, `true` or `false` for `documentBleedLink`, or an array of four finite numbers for `documentBleedOffsetRect`. Any setting takes `undefined`, which unsets it. A value of another kind throws a `TypeError`, a `title` longer than 4096 bytes throws a `RangeError`, and the setting keeps @@ -11082,8 +11081,9 @@ Threading text from the in and out ports), and the other frames keep the text th refuses an image larger than 64 million pixels or longer than 32,768 pixels a side, and the art stays as it was. With `ids`, `object.rasterize` rasterizes those objects instead of the selection and leaves the selection as it was, without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id -listed twice, a layer, a path of a compound path or a part of another object that is not a group, and an object that -is locked or in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's +clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or +in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. From e376c81068818f89b80900bd305f3ebbd09d0734 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:57:15 -0800 Subject: [PATCH 109/533] Asset Export: the empty-state hint shows whole in a short panel With no assets, the empty state was drawn in the room the settings, Export and the footer bar left. At the floating panel's first-open size that room was too short for the hint, and in a narrow panel there was no room at all. The empty state now takes its own height with the settings under it, and the column scrolls when the panel is shorter than both. With assets, the grid still fills the room above the settings. --- crates/ui-egui/src/panels/asset_export.rs | 61 +++++++++++++------ .../ui-egui/src/panels/tests_asset_export.rs | 20 ++++++ 2 files changed, 62 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 043918e3b5..f993ef54bc 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -34,8 +34,8 @@ use craft::theme::Variant; use craft::theme::variant::Tone; use craft::ui::buttons::{Button, IconButton}; use craft::ui::contract::{ - Bind, CollectionEvent, Entry, Props as _, RowAlign, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, clicked, - request_rename, + Bind, CollectionEvent, Entry, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, + clicked, request_rename, }; use craft::ui::dialog::StackDialog as _; use craft::ui::display::{Divider, Shade, Text}; @@ -523,8 +523,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let has_art = !st.selection.is_empty(); let (selection, saving) = (&mut model.selection, &mut model.saving); let (mut export_clicked, mut footer, mut screens) = (false, None, false); - // The grid takes the room the settings, Export and the footer bar leave. - let footed = Stack::new().fill().footer(|ui, _| { + let mut settings_part = |ui: &mut Ui| { crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| { let (change, files_each) = settings(ui, st); (seen.change, seen.files_each) = (change, files_each); @@ -544,6 +543,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .show(ui); export_clicked = clicked(&button); }); + }; + let mut bar_part = |ui: &mut Ui| { // The first action sits at the end edge, so Remove comes first and Add stands before it. let remove = FooterAction::new(IconSpec::svg(IconId::new("trash-2")), tl!("Remove Selected Assets")).enabled(!shown_sel.is_empty()); let add = FooterAction::new(IconSpec::svg(IconId::new("plus")), tl!("Add Selected Artwork (Alt: as one asset)")).enabled(has_art); @@ -552,27 +553,49 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); screens = leading.is_some_and(|r| clicked(&r)); footer = Some(bar); - }); - let zone = footed.show(ui, |ui, _| { - let drop_art = DropAction::::new(move |p| p.artwork_for(uid, reverts).is_some()); - drop_art.sizing(Sizing::Fill).show(ui, |ui, _| { - if st.doc.assets.is_empty() { - Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) - .title(tl!("No assets")) - .icon(NoticeIcon::Custom(IconSpec::svg(IconId::new("share-2")))) - .layout(NoticeLayout::Centred) - .show(ui); - } else { + }; + let drop_art = move || DropAction::::new(move |p| p.artwork_for(uid, reverts).is_some()); + let dropped = if st.doc.assets.is_empty() { + // The empty state takes its own height with the settings under it, and the column scrolls when the panel is + // shorter than both. + let footed = Stack::new().fill().footer(|ui, _| bar_part(ui)); + let zone = footed.show(ui, |ui, _| { + Stack::new() + .fill() + .scroll(Scroll::vertical()) + .show(ui, |ui, _| { + let zone = drop_art().sizing(Sizing::FillWidth).show(ui, |ui, _| { + Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects.")) + .title(tl!("No assets")) + .icon(NoticeIcon::Custom(IconSpec::svg(IconId::new("share-2")))) + .layout(NoticeLayout::Centred) + .show(ui); + }); + settings_part(ui); + zone + }) + .inner + }); + zone.inner.flatten().and_then(|zone| zone.output.dropped) + } else { + // The grid takes the room the settings, Export and the footer bar leave. + let footed = Stack::new().fill().footer(|ui, _| { + settings_part(ui); + bar_part(ui); + }); + let zone = footed.show(ui, |ui, _| { + drop_art().sizing(Sizing::Fill).show(ui, |ui, _| { let items = Assets::of(st); let grid = TileGrid::::new(tl!("Assets")).id(grid_id).select(SelectMode::Multi).selection(Bind::bound(&mut *selection)).rename(true); let out = grid.show_items(ui, &items, &mut |id, _| tile(st, *id)); opener = Some(out.response.response.clone()); events = out.response.events; - } - }) - }); - if let Some(payload) = zone.inner.and_then(|zone| zone.output.dropped) + }) + }); + zone.inner.and_then(|zone| zone.output.dropped) + }; + if let Some(payload) = dropped && let Some(ids) = payload.artwork_for(uid, reverts) { seen.dropped = Some((ids.iter().map(|id| id.0).collect(), alt)); diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index 369006b699..5ee65f9461 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -987,6 +987,26 @@ fn tile_menu_rename_opens_the_clicked_assets_inline_field() { assert_eq!(assets(&mut p.app())[0]["name"], "Renamed"); } +/// With no assets, a panel too short for the empty state and the settings under it draws the whole hint, above the +/// settings, and scrolls; at the floating panel's first-open size and in a narrow panel alike. +#[test] +fn the_empty_state_hint_is_whole_in_a_short_panel() { + const HINT: &str = "Drag art here, or select it and click +. Hold Alt for one asset of several objects."; + for room in [egui::vec2(244.0, 280.0), egui::vec2(214.0, 360.0), egui::vec2(244.0, 600.0)] { + let (app, _, _) = app(true); + let mut p = panel(app); + p.room(room); + p.frame(); + p.frame(); + let hint = p.painted(HINT); + assert_eq!(hint.len(), 1, "the hint is drawn once at {room:?}: {:?}", p.texts()); + assert_eq!(p.painted("No assets").len(), 1, "the title is drawn at {room:?}"); + let settings = p.painted("Export Settings"); + assert_eq!(settings.len(), 1, "the settings heading is drawn at {room:?}"); + assert!(hint[0].bottom() <= settings[0].top(), "the hint {:?} ends above the settings {:?} at {room:?}", hint[0], settings[0]); + } +} + /// In a panel narrower than the scale row's fields at their full length, the row's Scale, Suffix, Format and Remove /// share the panel's width, and the Save As Preset row under them stays inside it too. #[test] From 88d9a6e601ab1e4e57318ab161ef804b9e80efd4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 23:02:05 -0800 Subject: [PATCH 110/533] Scripts: script file writes and rasterize report their warnings Document.rasterize, imageCapture, saveAs and exportFile send command warnings to the Script Console, as app.open does. app.open no longer inherits the linked-file permissions of documents open at the start of the run. Rasterize by id refuses art on a locked artboard, and clip bounds within floating-point error of whole pixels use that pixel count. Capture sources leave out link paths the document cannot follow. --- crates/engine/src/cmd/links.rs | 5 +- crates/engine/src/cmd/menucmds.rs | 16 +++++- crates/engine/src/cmd/scripts.rs | 2 +- .../engine/src/script/dom/raster_capture.rs | 3 +- crates/engine/src/script/dom/save_open.rs | 35 +++++++----- crates/engine/src/script/mod.rs | 3 +- crates/engine/src/tests/link_paths.rs | 14 +++++ .../engine/src/tests/script_raster_capture.rs | 51 ++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 55 +++++++++++++++++++ docs/mcp.md | 21 +++++-- 10 files changed, 176 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 78641c711b..9bec029957 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -212,7 +212,8 @@ pub(crate) fn linked_groups(d: &Document) -> Vec<(String, Vec)> { /// from, wherever it is stored, brush art included, whether or not a file is there: each place /// [`locate`] looks at, and beside each one the plate files of an image placed from a DCS file, /// as its plate-change check finds them. A link's absolute stored and relative paths are listed -/// as they are too, for the relative path of every object in a group. +/// too, for the relative path of every object in a group. Document-path restrictions apply before +/// any filesystem probe. pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut out = vec![]; for g in groups(d, None) { @@ -221,7 +222,7 @@ pub(crate) fn link_read_places(d: &Document, base: LinkBase) -> Vec { let mut mains: Vec = std::iter::once(link.path.as_str()) .chain(link.relative.as_deref()) .filter(|p| Path::new(p).is_absolute()) - .map(str::to_string) + .filter_map(|p| fileio::document_path(p, base.doc).ok()) .collect(); mains.extend(places(&link, base)); for main in mains { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index c441c73c6e..e216a5531a 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -916,8 +916,14 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } let scale = ppi / 72.0; // The image covers the bounds in whole pixels. - let px = |len: f64| (len * scale).ceil().max(1.0); - let region = Rect::new(b.x0, b.y0, b.x0 + px(b.width()) / scale, b.y0 + px(b.height()) / scale); + let px = |lo: f64, hi: f64| { + let pixels = (hi - lo) * scale; + let nearest = pixels.round(); + let error = 8.0 * f64::EPSILON * (lo.abs() + hi.abs()) * scale; + let pixels = if (pixels - nearest).abs() <= error { nearest } else { pixels }; + pixels.ceil().max(1.0) + }; + let region = Rect::new(b.x0, b.y0, b.x0 + px(b.x0, b.x1) / scale, b.y0 + px(b.y0, b.y1) / scale); // Create Clipping Mask: the image is clipped to the art's outline with its geometry effects // applied, as on the canvas. let clip = look @@ -975,6 +981,7 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { } } let mut roots = Vec::with_capacity(ids.len()); + let locks = d.locked_artboards(); for id in &ids { // The layers and groups from the top down to the object itself. let Some(up) = d.ancestry(*id) else { return Err(bad(cmd, format!("no such object id {}", id.0))) }; @@ -1000,6 +1007,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); } + if locks.holds_id(*id) { + return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); + } roots.push(*id); } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d895c3969f..4b1dfa0f31 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 9a3daccfbe..54682c1848 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -222,6 +222,7 @@ fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); } let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + super::save_open::command_warnings(h, "rasterize", &r); let image = match &r { Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { ("imageId", Data::Number(n)) => super::whole(*n), @@ -421,7 +422,7 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { h.disk.borrow_mut().exact = true; let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); h.disk.borrow_mut().exact = false; - r?; + super::save_open::command_warnings(h, "imageCapture", &r?); Ok(Data::Undefined) } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 618d1d4e91..9842150b5d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -571,6 +571,23 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { r } +pub(super) fn command_warnings(h: &Host, method: &str, result: &Data) { + if let Data::Object(items) = result { + for (key, value) in items { + let warnings: &[Data] = match (key.as_str(), value) { + ("warning", Data::String(_)) => std::slice::from_ref(value), + ("warnings", Data::Array(warnings)) => warnings, + _ => continue, + }; + for warning in warnings { + if let Data::String(warning) = warning { + super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + } + } + } +} + /// The path to give a command for the real path `real`. fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() @@ -602,7 +619,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + command_warnings(h, "saveAs", &r); Ok(Data::Undefined) } @@ -656,7 +674,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + command_warnings(h, "exportFile", &r); Ok(Data::Undefined) } @@ -705,17 +724,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }), _ => None, }; - // Each warning from reading the file (content left out, an image that could not be read) goes - // to the console, as `addDocument` sends its profile's. - if let Data::Object(items) = &r { - for (k, v) in items { - if let ("warnings", Data::Array(ws)) = (k.as_str(), v) { - for w in ws.iter().filter_map(|w| if let Data::String(w) = w { Some(w) } else { None }) { - super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); - } - } - } - } + command_warnings(h, "open", &r); let s = h.session.borrow(); let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ab50b47586..1f6cfa0b84 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1296,7 +1296,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let gate = host.disk.borrow().gate(documents, host.linked()); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { host.linked() }; + let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); // What the command opened, changed or gave another file is not as the person left it. diff --git a/crates/engine/src/tests/link_paths.rs b/crates/engine/src/tests/link_paths.rs index e39cf66896..b0a4303f23 100644 --- a/crates/engine/src/tests/link_paths.rs +++ b/crates/engine/src/tests/link_paths.rs @@ -100,6 +100,20 @@ fn places_named_from_a_share_are_not_followed_after_a_save_elsewhere() { assert_eq!(follow_from(link, on_share, Some(r"C:\b\poster.vectorcraft"), resolve), None); } +#[test] +fn capture_sources_exclude_paths_the_document_cannot_follow() { + let dir = Folder::new("capture-paths"); + let mut paths = far(&dir); + paths.push(dir.file("local.png")); + let path = save_linked(&dir, &paths); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let st = s.active().unwrap(); + let places = crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)); + assert_eq!(far_reads(&places), Vec::<&String>::new(), "{places:?}"); + assert!(places.contains(&dir.file("local.png")), "local links remain capture sources: {places:?}"); +} + /// The final path Windows gives a folder of the drive `Z:` mapped to `\\server\share`. The /// share's root folder has no trailing separator (`\\?\UNC\server\share`). fn on_share(folder: &str) -> Option { diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 0e70175844..075d49baf5 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -166,12 +166,12 @@ fn script_rasterize_fractional_clip_bounds_stay_inside_the_rectangle() { /// though the subtraction of its edges is not exact. #[test] fn script_rasterize_clip_bounds_from_a_fractional_origin_keep_whole_pixels() { - for (right, width, partial) in [(10.7, 3, false), (10.75, 4, true)] { + for (left, right, width, partial) in [(10.4, 10.7, 3, false), (10.1, 10.4, 3, false), (10.4, 10.75, 4, true)] { let (mut s, ..) = doc(); log( &mut s, &format!( - "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [10.4, 280, {right}, 240], o);" + "{RASTERIZE_A} var o = new RasterizeOptions(); o.resolution = 720; o.transparency = true; d.rasterize(a, [{left}, 280, {right}, 240], o);" ), ); assert_eq!(images(&s), vec![(width, 400)]); @@ -243,6 +243,53 @@ fn script_rasterize_rejects_locked_art() { refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); } +#[test] +fn rasterize_rejects_explicit_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap_err().to_string(); + assert!(e.contains("locked artboard"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked artboard"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0, b.0]})).unwrap(); +} + +#[test] +fn script_rasterize_logs_a_missing_image_warning() { + let (mut s, ..) = doc(); + let id = super::menucmds::place_undecodable_png(&mut s); + let out = run(&mut s, "var d = app.activeDocument; vc.log(d.rasterize(d.pageItems[0]).typename);").unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("rasterize: ") && s.contains("couldn't be decoded")), + "{out}" + ); + assert_eq!(out["log"], json!(["RasterItem"])); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn image_capture_logs_a_missing_image_warning() { + let base = folder("warning"); + let (mut s, dir) = capture_doc(&base); + let id = super::menucmds::place_undecodable_png(&mut s); + let before = s.active().unwrap().doc.clone(); + let out = run_file(&mut s, &base, &format!("app.activeDocument.imageCapture(new File({}));", quoted(&dir.join("capture.png")))).unwrap(); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with("imageCapture: ") && s.contains("couldn't be decoded")), + "{out}" + ); + assert!(dir.join("capture.png").is_file()); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(*s.active().unwrap().doc, *before); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_rasterize_rejects_art_inside_listed_art() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index d8d6a82a50..d08a6f316c 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,61 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn scripted_file_writes_log_command_warnings() { + for (method, extension, call) in [("saveAs", "pdf", "d.saveAs(file)"), ("exportFile", "png", "d.exportFile(file, ExportType.PNG24)")] { + let base = folder(&format!("warning-{method}")); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + super::menucmds::place_undecodable_png(&mut s); + let path = dir.join(format!("output.{extension}")); + let out = run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument, file = new File({}); {call};", quoted(&path))).unwrap(); + assert!(path.is_file(), "{method}"); + let prefix = format!("{method}: "); + let lines = out["console"]["lines"].as_array().unwrap(); + assert!( + lines.iter().filter_map(Value::as_str).any(|s| s.starts_with(&prefix) && s.contains("couldn't be decoded")), + "{method}: {out}" + ); + let _ = std::fs::remove_dir_all(base); + } +} + +#[test] +fn open_does_not_inherit_an_existing_documents_link_permission() { + let base = folder("inherited-link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.png"); + std::fs::write(&linked, super::links::png(2, 2, [255, 0, 0])).unwrap(); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + s.execute("file.place", &json!({"path": linked.to_string_lossy(), "link": true})).unwrap(); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); + let page = dir.join("page.svg"); + std::fs::write( + &page, + format!(""), + ) + .unwrap(); + let capture = dir.join("existing.png"); + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.imageCapture(new File({})); app.open(new File({}));", quoted(&capture), quoted(&page)), + ); + let pixels = image::open(&capture).unwrap().to_rgb8(); + assert!(pixels.pixels().any(|p| p.0 == [255, 0, 0]), "existing art can still read its linked image"); + let mut images = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + images.push((im.width, im.height, im.link.as_ref().is_some_and(|l| l.hash.is_some()))); + } + }); + assert_eq!(images, [(64, 64, false)], "the new document cannot read the inherited link"); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { diff --git a/docs/mcp.md b/docs/mcp.md index 0066455f24..bce70dfbbf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3148,8 +3148,11 @@ other files through `$`: document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the - files a command reads or writes besides the one named, such as an SVG's linked files, are - read and written only where the script's folders allow. `userInteractionLevel` does not change what a command + files `app.open` reads besides the one named, such as an SVG's linked files, are read only where the script's + folders allow, including links inherited from documents that were already open. Rendering existing documents + can still read their inherited linked files. Ancillary writes require the script's write grants. + `saveAs` and `exportFile` send command warnings to the Script Console with the method name. + `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the @@ -3177,7 +3180,10 @@ other files through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group throw an error, and nothing changes. It keeps the selection, less the art it replaces. With + a locked layer or group or on a locked artboard throw an error, and nothing changes. + Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional + dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. + `rasterize` keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an error that says they are not available yet. `imageCapture` writes a PNG, and the file's name must end with `.png`. With @@ -3186,7 +3192,8 @@ other files through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each, and the documents count whether they were open when the run started or were + image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem + probes. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to @@ -11083,8 +11090,10 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or -in a locked layer or group are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) -keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. The result's +in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. +Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions +round up. The result's `imageId` is the image, which is `id` itself unless `clippingMask` put the image in a clip group. ```json From 743e38ebf6549eeff373721e337f4dca3ecfb027 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:08:13 -0800 Subject: [PATCH 111/533] Scripts: path creation and paint edits replay as run; mixed picks keep their anchors Scripted shapes record the layer they were drawn on, so replay does not draw them behind other art or inside an isolated group. Paint edits on objects keep the new-art defaults on replay, and a solid new-art color copied to a path keeps its color model. An anchor picked next to a selected segment stays selected and is listed by selectedPathPoints. closed set on an empty path applies to its first points. Text fillColor and strokeColor reflect as Color. Saved file.new steps keep the old row rounding. --- crates/engine/src/cmd.rs | 6 ++ crates/engine/src/cmd/create.rs | 29 +++++- crates/engine/src/cmd/newdoc.rs | 9 +- crates/engine/src/cmd/paint.rs | 18 +++- crates/engine/src/cmd/select.rs | 9 +- crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/script/dom/paths.rs | 61 +++++------ crates/engine/src/script/dom/text.rs | 1 + crates/engine/src/tests/script_dom.rs | 16 +++ crates/engine/src/tests/script_dom_paths.rs | 108 ++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 11 ++ docs/mcp.md | 24 +++-- 12 files changed, 245 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..4f8a211d51 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -441,6 +441,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..31b9950296 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index db0495ac97..0416c5b406 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -870,7 +870,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut params = p.clone(); + if s.replaying() + && let Some(rows) = params.pointer_mut("/artboardLayout/rows") + && let Some(value) = rows.as_f64().filter(|r| r.is_finite() && *r >= 1.0) + { + *rows = json!(value.round().min(MAX_ARTBOARDS as f64) as u32); + } + let mut settings = base.with_params(¶ms, C)?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..726aada285 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0a5aeacf31..8c8e758c7b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -289,19 +289,11 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) } -/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. -fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); - let r = f(); - if let Some((uid, isolation)) = isolation - && let Some(st) = h.session.borrow_mut().document_mut(uid) - { - st.isolation = isolation; - } - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which @@ -315,6 +307,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; let count = if id == "object.setOverprint" { "changed" } else { "objects" }; @@ -453,7 +448,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -613,9 +608,9 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) })?; @@ -640,7 +635,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -836,10 +837,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1502,12 +1503,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1592,17 +1599,11 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); - if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + if !held && !sel.contains(item.id) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; - } - out + let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); + (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index e96645da43..f5a8c840fe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1617,6 +1617,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4bebfb6ab9..7b44a3eb04 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1024,6 +1024,22 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1001.2, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + assert!(s.execute("file.new", ¶ms).unwrap_err().to_string().contains("rows must be a whole number")); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b08ed50e9a..c1ec77f4e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -49,6 +49,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 29b676a377..a18184d7ce 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 6070ae384a..1ff018d34e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3124,7 +3124,8 @@ through `$`: `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with - `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports + `fillColor` and `strokeColor` as `Color`. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` @@ -3175,7 +3176,9 @@ through `$`: radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and + record this placement for replay. A null `onLayer` draws normally on the active layer. + A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to @@ -3183,8 +3186,11 @@ through `$`: (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through - `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the - points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one + `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. + Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy + and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept + this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`. + Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. @@ -3204,7 +3210,8 @@ through `$`: the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is - closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first + subpath. `setEntirePath` takes at most 100,000 points and gives corner points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed @@ -3212,7 +3219,8 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment + picks. A path in a selected group or compound path is selected as a whole. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's @@ -3228,7 +3236,7 @@ through `$`: was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the - stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, @@ -10492,6 +10500,8 @@ the rows give the current number of artboards, and New Document drops the rows w `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). +Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still +require whole row counts from 1 to 1000. `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets From c04c53ca6cb612a92a61ffe611afa439e206cc1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:24:17 -0800 Subject: [PATCH 112/533] Plug-ins: hold a running script's events and deliver window-key changes in their pass A delivery between a script's slices no longer gives the opens and saves the script queued; they wait until the run ends, so a run that fails never gives the opens of documents it discarded. The desktop app now delivers after the window keys run, so a selection Escape changes when it leaves isolation mode reaches plug-ins in that pass, and the handlers' time counts toward the frame time. The docs state the per-document grouping and the script rule. --- crates/engine/src/plugin_events.rs | 22 +++++++++--- crates/engine/src/tests/plugin_events.rs | 44 ++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 17 +++++---- crates/ui-egui/src/tests/plugins.rs | 33 ++++++++++++++++++ docs/plugins.md | 12 ++++--- docs/target-app-parity.md | 2 +- 6 files changed, 115 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 555f2ac308..f853198ebb 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -281,10 +281,12 @@ impl Session { } } - /// At the end of a script's run. When the run failed (`kept` false), drops the waiting - /// `document.opened` events its commands queued, since the documents they opened were discarded - /// with its working copy. Its saves stay, since the files they wrote stay written, and so do the - /// events of documents a frontend opened while the run was paused. + /// At the end of a script's run. The opens and saves its commands queued wait until then, also + /// through deliveries between its slices ([`Session::deliver_plugin_events`]). When the run + /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since + /// the documents they opened were discarded with its working copy. Its saves stay, since the + /// files they wrote stay written, and so do the events of documents a frontend opened while the + /// run was paused. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { if !kept { self.plugin_events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); @@ -375,7 +377,15 @@ impl Session { // as it was found. let depth = self.depth; self.depth += 1; + // An open or a save a running script queued waits for the end of the run + // ([`Session::plugin_events_script_ended`]), also when a frontend delivers between its + // slices: a run that fails discards the documents it opened. + let mut held = VecDeque::new(); while let Some(p) = self.plugin_events.pending.pop_front() { + if p.by_script { + held.push_back(p); + continue; + } if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } @@ -386,6 +396,10 @@ impl Session { self.run_handler(plugin, &p); } } + // The held events are older than any a handler's calls queued meanwhile. + while let Some(p) = held.pop_back() { + self.plugin_events.pending.push_front(p); + } self.depth = depth; self.plugin_events.dispatching = false; } diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index 9f757b020e..66b8804a58 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -371,6 +371,50 @@ fn a_failed_script_gives_its_save_but_not_its_open() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A delivery between a script's slices, as a frontend makes one for a command it runs while the +/// script is paused, gives the frontend's open but holds the open and the save the script queued +/// until the run ends: the run fails, so its open is never given, and its save is given after it. +#[test] +fn a_delivery_between_script_slices_holds_the_script_events() { + let id = "test.events.between_slices"; + let mut s = session(); + let doc = s.doc().unwrap().uid; + install(&mut s, id, r#"["document.saved","document.opened"]"#, &[], "", tpl::LOG_EVENT, &[]); + s.plugin_event_frames = true; + let dir = std::env::temp_dir().join(format!("vectorcraft-engine-plugin-events-between-slices-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + run(&mut s, "document.save", json!({"path": dir.join("between-slices.vectorcraft").to_string_lossy()})); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})]); + let data = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + + s.script_frames = true; + let source = format!( + "vc.run('document.save', {{}}); vc.run('document.open', {{name: 'b.vectorcraft', dataBase64: '{data}'}}); \ + for (var i = 0; i < 3000000; i++) {{}} throw new Error('stop');" + ); + assert_eq!(run(&mut s, "script.run", json!({"source": source, "name": "t.js"}))["running"], true); + assert!(s.script_pump().is_none(), "paused after its first slice"); + let bytes = vectorcraft_format::base64_decode(&data).unwrap(); + let index = crate::cmd::fileio::open_bytes(&mut s, "front.vectorcraft", &bytes, None).unwrap()["index"].as_u64().unwrap(); + let front = s.documents()[index as usize].uid; + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.opened", "document": front})], "only the frontend's open, while the run is paused"); + let mut slices = 0; + let r = loop { + slices += 1; + assert!(slices < 100_000, "the script ends"); + if let Some(r) = s.script_pump() { + break r; + } + }; + assert!(r.is_err(), "the script threw"); + s.deliver_plugin_events(); + assert_eq!(given(&mut s, id), [json!({"type": "document.saved", "document": doc})], "the script's save, and not its open"); + std::fs::remove_dir_all(&dir).ok(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// A `selection.changed` event of a plug-in without `doc.read` gives the count and no ids; one /// with it lists the selected ids. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d75c545869..d1998ecd1e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -673,6 +673,17 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + // What the canvas, a panel, a dialog or a window key changed in this pass reaches + // the plug-ins that react to it now, since an idle app draws no further frame; a + // line a handler wrote shows in the next one. The handlers' time counts toward the + // frame-time sample of a pass egui presents. + let t0 = monotonic_ms(); + if !self.session.script_running() && self.deliver_plugin_events() { + ctx.request_repaint(); + } + if !ctx.will_discard() { + self.perf.frame_ms += monotonic_ms() - t0; + } }) }) { self.session.set_replaying(false); @@ -757,12 +768,6 @@ impl VectorcraftApp { // A command run by a menu, panel or dialog in this pass may have queued its text copy // after the input. Publish it now: an idle web host may have no further frame to run it in. self.flush_clipboard_out(); - // What the canvas, a panel or a dialog changed in this pass reaches the plug-ins that react - // to it now, since an idle app draws no further frame; a line a handler wrote shows in the - // next one. - if !self.session.script_running() && self.deliver_plugin_events() { - ctx.request_repaint(); - } crate::cursors::request_busy(self, &ctx); // A pass egui will discard and rerun is not a presented frame: it must not become the // frame-time sample, and it must not issue a capture of what it drew. diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 27508fb744..455493afaf 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -1065,6 +1065,39 @@ fn a_change_made_in_a_ui_pass_is_delivered_in_that_pass() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// Escape leaving isolation mode restores the selection from before entry after the window's +/// panels and dialogs are drawn; the plug-in that reacts to `selection.changed` is still given the +/// change in that pass. +#[test] +fn a_selection_a_window_key_changes_is_delivered_in_that_pass() { + let mut app = app(); + app.session.allow_plugin_grants_from_requests(); + let id = "test.UI.window_key_events"; + let grant = json!(["progress", "events"]); + let manifest = format!(r#"{{"id":"{id}","name":"Key Events","kind":"filter","api":2,"permissions":{grant},"events":["selection.changed"]}}"#); + let wasm = wat::parse_str(tpl::reacting(&manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 40, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = app.run("object.group", json!({})).unwrap()["id"].clone(); + app.run("object.isolate", json!({"id": g})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = crate::testing::ui_context(); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + super::synthetic::key_frame(&mut app, &ctx, vec![]); + app.session.deliver_plugin_events(); + let _ = app.session.take_plugin_event_notices(); + let before = app.session.doc().unwrap().selection.objects.clone(); + let esc = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + super::synthetic::key_frame(&mut app, &ctx, vec![esc]); + assert_ne!(app.session.doc().unwrap().selection.objects, before, "Escape left isolation and restored the selection"); + app.session.deliver_plugin_events(); + let left: Vec = app.session.take_plugin_event_notices().into_iter().filter(|n| n.plugin == id).map(|n| n.text).collect(); + assert!(left.is_empty(), "delivered in the pass of the key, not later: {left:?}"); + app.run("plugin.remove", json!({"id": id})).unwrap(); +} + /// The approval names a plug-in whose manifest translates its name in the UI language and also /// gives the manifest's own name, both escaped; a language without a translation shows the /// manifest's name alone. What OK installs stays bound to the id and hash shown. diff --git a/docs/plugins.md b/docs/plugins.md index be672b22b5..cbcdc68d8c 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -873,14 +873,18 @@ or the document's contents. leaves the document as it was (a Layer Options that sets the name it had). Installing a plug-in hands it no past events, also none that were waiting for the next delivery when it was installed. A change made to a document opened or created since the last delivery is an event at the next one, after that document's `document.opened`. -- Changes between two deliveries are one event with the state they ended with. The desktop app delivers in each - frame, after the work that finished in the background and again at the end of the frame, after the canvas, panels - and dialogs have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does +- The selection changes of one document between two deliveries are one `selection.changed` with the state they ended + with, and its layer changes are one `layer.changed`; each document's events are separate. The desktop app delivers + in each frame, after the work that finished in the background and again at the end of the frame, after the canvas, + panels, dialogs and window keys have run, so a burst of selection changes in one frame is one `selection.changed` and an idle window does not hold an event back. Requests through the control channel, and through MCP in remote mode, run in the desktop app and are delivered by the frame too, and several of them can run in one frame. `vectorcraft-cli` and headless MCP deliver after each request, also one that fails: a save in a `command.batch` whose later step fails still gives its `document.saved`. Opens and saves are each their own event, in order, and are delivered even when the - document closed before the delivery. At most 32 events wait; past that the oldest is dropped. + document closed before the delivery. The opens and saves of a running script wait until its run ends, also + through any delivery between its slices. The desktop app does not deliver while a script runs; a frontend that + does can give its own opens and saves made while the run was paused before the script's earlier ones. A run that fails gives its saves and none of its opens. At most 32 + events wait; past that the oldest is dropped. - A handler only reads. VectorCraft applies nothing it returns, and it is outside any undo step. With `commands` and a `commandAllowlist`, it may [call](#command-calls) these commands, when the allowlist also names them, on the active document: `dataset.list`, `graphicStyle.list`, `guide.list`, `image.info`, `object.blend.info`, `swatch.list`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2a01dc47..96e6748b6a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2836,7 +2836,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. -- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: changes between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. +- **Plug-ins react to events (G17, VectorCraft's own API):** a plug-in at API level 2 with the `events` permission names any of `selection.changed`, `document.opened`, `document.saved` and `layer.changed` in its manifest, and its `vc_event` export is given a small JSON event after each change of that kind has finished, outside any undo step: the selection changes of one document between two deliveries (a frame in the desktop app, a request in `vectorcraft-cli` or headless MCP) are one event, and so are its layer changes, while each open and each save is its own event and each document's events stay separate. A handler only reads: it may call only ten listed commands that read, any other call fails with an error naming the event, and what a call changed is put back. It gets 5 M instructions and 200 ms, a handler that fails 3 times in a row gets no more events for the session, and an event raised while a handler runs waits for the next delivery. Regressions: `crates/engine/src/tests/plugin_events.rs`, `crates/engine/src/plugin_events.rs`, `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Apply Last Filter and Last Filter… for filter plug-ins (G17):** Object › Plug-ins starts with Apply Last Filter (`plugin.applyLastFilter`), which runs the filter plug-in that last ran in the session again with the same parameters on the selection, without its dialog, as one undo step, and Last Filter… (`plugin.lastFilter`), which opens that filter's dialog with those parameters; once a filter has run, both items are named after it. [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=357) describes the same pair for filters: one item repeats the last filter with its last settings, the other opens its options. Each filter's own dialog opens with the parameters that filter last ran with. A heavy filter repeats in the background as its menu item runs it. Both items are grayed out with no document open, before a filter ran, and once that filter was removed, installed again or no longer takes the parameters as they are; they don't need a selection (VectorCraft's own rules). Regressions: `crates/ui-egui/src/tests/last_filter.rs`. Scores and hours unchanged. - **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. From 06eb0f252affed9df848712ff016eb9fd77e25e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:35:27 -0800 Subject: [PATCH 113/533] Scripts: saveAs takes its format from the script's file name Document.saveAs without options picks the format from the name the script gave, before a symbolic link is resolved, and a name without a known extension keeps the document's format. A save that writes several files refuses a destination that is a folder before it writes any of them. imageCapture leaves out source paths outside the automation read roots before it probes them. The host and scriptcheck name test lists saveAs as a method, which it is now. --- crates/engine/src/cmd/fileio/save.rs | 14 ++++-- crates/engine/src/cmd/scripts.rs | 2 +- .../engine/src/script/dom/raster_capture.rs | 29 ++++++++++- crates/engine/src/script/dom/save_open.rs | 9 +++- crates/engine/src/tests/script_save_open.rs | 48 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 7 ++- 7 files changed, 99 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f31f01a7aa..3c9c11cb85 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1074,10 +1074,14 @@ impl SaveJob { // written. A refused file goes to `write` first, which refuses it with the error the // caller gives (naming the path as the caller does), so none of the files is written. #[cfg(not(target_arch = "wasm32"))] - if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) - { - write(p, bytes)?; + if files.len() > 1 { + for (p, bytes) in &files { + if super::may_write(p).is_err() { + write(p, bytes)?; + } else if std::path::Path::new(p).is_dir() { + return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } + } } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1383,7 +1387,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written or is a directory, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 1a945e68ba..f9d9c7c33c 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. Document.saveAs without options selects the format from the script's File name before resolving symbolic links; a name without a recognized extension uses the document's current format. imageCapture excludes source paths outside the automation read roots before filesystem probes. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 54682c1848..dfa77fc1f2 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -26,6 +26,7 @@ //! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 //! to 255. The file is written only where the script's `File` objects may write, and never over //! an open document's file or a file one of them links. +//! Source paths outside the automation read roots are excluded before filesystem probes. //! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is //! drawn; the resolution is never lowered to make it fit. //! - `windowCapture` throws an error that says it is not available yet. @@ -295,7 +296,12 @@ fn sources_on_disk(h: &Host) -> Vec { paths.extend(st.path.clone()); paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st))); } - paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect() + paths.iter().filter_map(|p| source_place(p)).collect() +} + +fn source_place(path: &str) -> Option { + crate::file_access::check_read(path).ok()?; + placed(std::path::Path::new(path)) } /// A file as its folder's real path and its name. @@ -495,3 +501,24 @@ pub(super) fn classes(link: &Link) -> Vec { }) .collect() } + +#[cfg(test)] +mod source_tests { + use super::*; + + #[test] + fn capture_sources_exclude_files_outside_automation_roots() { + let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); + let allowed = dir.join("allowed"); + std::fs::create_dir(&allowed).unwrap(); + let inside = allowed.join("doc.vectorcraft"); + let outside = dir.join("linked.png"); + std::fs::write(&inside, b"document").unwrap(); + std::fs::write(&outside, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap(); + crate::file_access::confine(roots.as_ref(), || { + assert!(source_place(&inside.to_string_lossy()).is_some()); + assert!(source_place(&outside.to_string_lossy()).is_none()); + }); + } +} diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 9842150b5d..ff3905c32d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -17,8 +17,9 @@ //! commands may use. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `saveAs` without options saves in the format the path's extension names; it writes the file -//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! - `saveAs` without options selects the format from the script's file name before resolving +//! symbolic links. A name without a recognized extension uses the document's current format. +//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and //! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. //! `exportFile` adds the format's extension unless the name already ends //! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes @@ -617,6 +618,10 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("options".into(), Value::Object(q)); } } + if !p.contains_key("format") { + let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); + p.insert("format".into(), json!(format)); + } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 87c935fca9..beb9d3cc87 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -10,6 +10,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[cfg(unix)] +#[test] +fn save_as_uses_the_scripts_extension_before_following_a_link() { + let base = folder("save-link-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let target = dir.join("target.vectorcraft"); + let alias = dir.join("alias.svg"); + std::fs::write(&target, b"keep").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + assert!(std::fs::read_to_string(&target).unwrap().contains(" PathBuf { let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f0bf02daa9..2d7e9dc97c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -112,7 +112,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ - pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 6c914eb6c0..e10094250a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3272,7 +3272,8 @@ through `$`: `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); - without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and + without options the name supplied by the script picks the format before symbolic links are resolved. + A name without a recognized extension uses the document's current format. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to @@ -3337,7 +3338,7 @@ through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem + image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem probes. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or @@ -12094,6 +12095,8 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. + The save checks every destination before writing. If any destination is a directory or access is refused, + it leaves every file unwritten. The same check applies to EPS saves that write multiple files. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a brush's art shows embedded keeps its pixels either way. A `version` older than the current one saves the placed From c822678ed7dc5695ab2d02106f1dd20a5314672d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:37:09 -0800 Subject: [PATCH 114/533] Scripts: point removal journals its selection, and point reads flush closures Removing a point records the shifted anchor selection as select commands, so replay moves the same points. Reading a point's selection writes waiting closure changes first when they drop a selected segment. selectedPathPoints walks the subpaths once. pathItems[name] looks up a numeric name that is not an index, as pageItems does. --- crates/engine/src/script/dom/paths.rs | 98 +++++++++++++++++++-- crates/engine/src/tests/script_dom_paths.rs | 61 +++++++++++++ 2 files changed, 150 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 8c8e758c7b..a828db6b00 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -178,6 +178,8 @@ fn point_count(subs: &[SubPath]) -> usize { /// The subpath and the place in it of point `i`, among the subpaths `subs`. fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { + #[cfg(test)] + tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1)); if i < sp.anchors.len() { return Some((s, i)); } @@ -380,17 +382,26 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { }; } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let Some(i) = super::position(*n) else { + return match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }; + }; Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = path_items(h, st); h.charge_call(ids.len() as u64)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -398,6 +409,7 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { fn items_index(h: &super::Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match items_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -1526,12 +1538,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when they add or remove points of this path or invalidate +/// selected segments. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| { + !same_layout(subs, &pd.subpaths) + || st + .selection + .segments + .get(&item.id) + .is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count()))) + })?, _ => false, }; if moved { @@ -1602,8 +1621,25 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { if !held && !sel.contains(item.id) { return Vec::new(); } - let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() + let segments = sel.segments.get(&item.id); + let ends: std::collections::BTreeSet<_> = segments + .into_iter() + .flatten() + .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) + .flatten() + .collect(); + let partial = sel.partial(item.id).filter(|_| !held); + let mut picked = Vec::new(); + let mut offset = 0; + for (s, sp) in pd.subpaths.iter().enumerate() { + for j in 0..sp.anchors.len() { + if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { + picked.push(offset + j); + } + } + offset += sp.anchors.len(); + } + picked })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); @@ -1674,8 +1710,22 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { selection.remove(item.id); } - if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { - st.selection = selection; + super::flush(h)?; + let (doc, changed, layer, rows) = + with_doc(h, item.doc, |_, st| (st.doc.clone(), st.selection != selection, st.active_layer, st.highlighted_rows())); + if changed { + on_doc(h, item.doc.uid, false, |h| { + super::restore_selection(h, &doc, &selection)?; + if let Some(anchors) = selection.anchors.get(&item.id) + && with_doc(h, item.doc, |_, st| st.selection.anchors.get(&item.id) != Some(anchors)) + { + command(h, "select.anchors", &json!({"id": item.id.0, "anchors": anchors, "mode": "add"}))?; + if let Some(segments) = selection.segments.get(&item.id).filter(|s| !s.is_empty()) { + command(h, "select.segments", &json!({"id": item.id.0, "segments": segments, "mode": "add"}))?; + } + } + super::restore_layer(h, item.doc.uid, layer, &rows) + })?; } } cut_points(h, item); @@ -1836,3 +1886,33 @@ pub(super) fn classes(l: &Link) -> Vec { ), ] } + +#[cfg(test)] +mod tests { + use std::cell::Cell; + + use serde_json::json; + + use crate::Session; + + thread_local! { + pub(super) static LOCATE_STEPS: Cell = const { Cell::new(0) }; + } + + #[test] + fn selected_points_do_not_rescan_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128]; + s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap(); + LOCATE_STEPS.with(|steps| steps.set(0)); + let out = s + .execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"})) + .unwrap(); + assert_eq!(out["log"], json!([2])); + LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); + } +} diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index c1ec77f4e1..501d027f3b 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -221,6 +221,23 @@ fn path_items_read_with_a_name_give_the_named_path() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } +#[test] +fn path_items_read_non_index_numbers_as_names() { + for name in ["-1", "1.5", "4294967295"] { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ + vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ + vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" + ), + ); + assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); + } +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] @@ -437,6 +454,50 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn removing_a_point_replays_selection_before_moving_anchors() { + for segments in [false, true] { + let setup = || { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); + } else { + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + let a = s.active().unwrap().selection.objects[0]; + assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 0), (0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); + s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "segments: {segments}"); + assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); + } +} + +#[test] +fn point_selection_reads_flush_removed_closing_segments() { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ + p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ + vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); + assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); + } +} + #[test] fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { From b3dede0a252e7a8f1f123829fd43b633fdd95fc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 01:04:03 -0800 Subject: [PATCH 115/533] Scripts: rasterize refuses art holding locked objects Rasterize by id refuses a group that holds a locked object, as it refuses a locked object itself. A save that writes several files refuses an existing read-only destination before it writes any of them. --- crates/engine/src/cmd/fileio/save.rs | 11 +++++-- .../engine/src/cmd/fileio/tests_readonly.rs | 31 +++++++++++++++++++ crates/engine/src/cmd/menucmds.rs | 14 ++++++--- .../engine/src/tests/script_raster_capture.rs | 24 ++++++++++++++ docs/mcp.md | 5 +-- 5 files changed, 75 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 3c9c11cb85..5e9b0f374b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1078,8 +1078,13 @@ impl SaveJob { for (p, bytes) in &files { if super::may_write(p).is_err() { write(p, bytes)?; - } else if std::path::Path::new(p).is_dir() { - return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } else if let Ok(meta) = std::fs::metadata(p) { + if meta.is_dir() { + return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file"))); + } + if meta.is_file() && meta.permissions().readonly() { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } } @@ -1387,7 +1392,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written or is a directory, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when access to one of a save's files is refused, or it is a directory or an existing read-only file, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index ae9762efc3..bee4258f8b 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -28,6 +28,37 @@ fn readonly_error_is_typed_and_other_writers_keep_their_error() { } } +#[test] +fn readonly_sidecar_leaves_every_save_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("save-readonly-sidecar"); + for format in ["vectorcraft", "eps"] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let path = dir.join(format!("Poster.{format}")).to_string_lossy().into_owned(); + let params = if format == "eps" { json!({"path": path, "useArtboards": true}) } else { json!({"path": path, "separateArtboards": true}) }; + let saved = session.execute("file.saveAs", ¶ms).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(std::fs::read).collect::>().unwrap(); + session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let sidecar = files.last().unwrap(); + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = session.execute("file.saveAs", ¶ms); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes, "{file}"); + } + assert_eq!(*session.doc().unwrap().doc, *doc); + assert!(session.doc().unwrap().is_dirty()); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index e216a5531a..0556fe7e20 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -969,8 +969,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p } /// The objects `ids` names for Rasterize, in paint order: each an object of the active document, -/// listed once, and neither it nor a layer or group it is in locked. An object inside another -/// listed one is left out, as `edit::roots_of` leaves it out of a selection. +/// listed once, with no locks on it, its descendants, or a layer or group it is in. An object +/// inside another listed one is left out, as `edit::roots_of` leaves it out of a selection. fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { let ids = super::checked_ids_param(s, p, "ids", cmd)?; let d = &s.doc()?.doc; @@ -1004,8 +1004,12 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { }; return Err(bad(cmd, format!("id {} {message}", id.0))); } - if up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { - return Err(bad(cmd, format!("id {} is locked, or in a locked layer or group", id.0))); + let mut locked = false; + if let Some(node) = d.node(*id) { + node.walk(&mut |n| locked |= n.locked); + } + if locked || up.iter().any(|a| d.node(*a).is_some_and(|n| n.locked)) { + return Err(bad(cmd, format!("id {} is locked, in a locked layer or group, or contains locked art", id.0))); } if locks.holds_id(*id) { return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 2e17a65248..bd4fe83f92 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -243,6 +243,30 @@ fn script_rasterize_rejects_locked_art() { refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); } +#[test] +fn script_rasterize_rejects_groups_with_locked_descendants() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [inner, c.0]})).unwrap(); + let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "locked": true})).unwrap(); + for id in [inner, outer] { + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.objects.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().selection.objects, selection); + assert_eq!(undo_steps(&s), undo); + } + refused(&mut s, "var d = app.activeDocument; d.rasterize(d.pageItems[0]);", "locked"); + s.execute("object.setProps", &json!({"id": a.0, "locked": false})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); +} + #[test] fn rasterize_rejects_explicit_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index e10094250a..24c406d511 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3326,7 +3326,8 @@ through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group or on a locked artboard throw an error, and nothing changes. + a locked layer or group or on a locked artboard throw an error, and nothing changes. An object containing + locked descendants also throws an error. Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -12095,7 +12096,7 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. - The save checks every destination before writing. If any destination is a directory or access is refused, + The save checks every destination before writing. If any destination is a directory, an existing read-only file, or access is refused, it leaves every file unwritten. The same check applies to EPS saves that write multiple files. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a From 54a6a92878b457207a4323613bc0ef00ff9f05fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 04:09:45 -0800 Subject: [PATCH 116/533] Document Tools: Flood Fill Artboards adds an artboard-sized rectangle on its own layer Object > Plug-ins > Document Tools > Flood Fill Artboards... opens a dialog that previews on the canvas and, on OK, runs the new command addon.document.floodFillArtboards as one undo step. The command adds an editable rectangle exactly the size of the active artboard, of listed artboards or of every artboard, painted with the current fill or a given color and no stroke. The rectangles go on top of a top-level layer named "Flood Fill" (or the name given), which is made at the bottom of the layers when the document has none. A layer that already exists keeps its lock and visibility, and the current layer stays as it was. Every given value is checked: null, wrong types, an empty or too long layer name, a color with alpha, unknown artboards, and artboards together with all are errors. A current fill of None without a color is an error. In a preview, the current fill is the one the preview began with. Docs: docs/mcp.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/document.rs | 13 +- .../src/cmd/addons/document/flood_fill.rs | 106 ++++++++++++++ .../engine/src/cmd/addons/document/tests.rs | 131 ++++++++++++++++++ crates/engine/tests/command_sweep.rs | 3 + crates/ui-egui/src/addons/dialogs.rs | 3 +- crates/ui-egui/src/addons/document.rs | 81 ++++++++++- crates/ui-egui/src/addons/document/tests.rs | 108 +++++++++++++++ docs/mcp.md | 16 +++ 9 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/addons/document/flood_fill.rs diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..62474e4b3d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -166,6 +166,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Flood Fill Artboards joins the Document Tools add-on (Object › Plug-ins › Document Tools): an editable rectangle exactly the size of the active artboard, or of every artboard, in the current fill or a chosen color with no stroke, on a layer named Flood Fill (or another name typed), which is made at the bottom of the layers when the document has none and otherwise keeps its lock and visibility. A dialog with Preview, one undo step (`addon.document.floodFillArtboards`). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 68681b50fa..dd20305a2d 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -2,10 +2,12 @@ //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a //! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces -//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! each image of a folder and saves the results to another ([`batch_trace`], #4921); Flood Fill +//! Artboards puts an artboard-sized rectangle on a layer of its own ([`flood_fill`]). Its submenu //! (Object › Plug-ins › Document Tools) is the UI's. mod batch_trace; +mod flood_fill; #[cfg(test)] mod tests; @@ -60,6 +62,15 @@ pub fn specs() -> Vec { has_doc, symbols_from_layers ), + cmd!( + "addon.document.floodFillArtboards", + "Flood Fill Artboards", + ["Object", "Plug-ins", "Document Tools"], + None, + "{artboards?: [index…] (default: the active artboard), all?: bool (true: every artboard; not with artboards), color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused; default: the current fill, in a preview the one the preview began with, an error when that is None), layer?: name (default: \"Flood Fill\"; at most 255 characters)} add an editable rectangle exactly the size of each artboard, painted with the color and no stroke, on top of the top-level layer of that name, made at the bottom of the layers when there is none. A layer that already exists keeps its lock and visibility; the rectangles are selected unless that layer is locked or hidden, and the current layer stays as it was. One undo step. Every value given is checked: null and values of the wrong type are errors. Refused while an opacity mask is edited → {ids: [rectangle id…], layer: layer id, created: bool (a new layer was made)}", + super::super::maskedit::outside_mask_editing, + flood_fill::flood_fill_artboards + ), ] } diff --git a/crates/engine/src/cmd/addons/document/flood_fill.rs b/crates/engine/src/cmd/addons/document/flood_fill.rs new file mode 100644 index 0000000000..a8214572da --- /dev/null +++ b/crates/engine/src/cmd/addons/document/flood_fill.rs @@ -0,0 +1,106 @@ +//! Flood Fill Artboards (`addon.document.floodFillArtboards`): a rectangle exactly the size of each +//! chosen artboard, painted with the current fill or a given color and no stroke, on a layer kept +//! for these rectangles. The rectangles are editable art, unlike an artboard's background color +//! (`artboard.setProps {color}`), which is a property of the artboard. + +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; +use vectorcraft_geom::{Affine, FillRule}; + +use super::super::super::layer::make_layer; +use super::super::super::newart::NewArt; +use super::super::super::panelcmds::listed_artboards; +use super::super::super::{bad, color_value}; +use crate::{Result, Session}; + +const COMMAND: &str = "addon.document.floodFillArtboards"; +/// The layer the rectangles go on when `layer` is left out. +const LAYER: &str = "Flood Fill"; +/// The longest layer name taken, in characters. +const MAX_NAME: usize = 255; + +/// `{artboards?, all?, color?, layer?}`: see the command's params text in [`super::specs`]. +pub(super) fn flood_fill_artboards(s: &mut Session, p: &Value) -> Result { + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(COMMAND, "the document has no artboards")); + } + let all = match p.get("all") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(COMMAND, "`all` must be true or false"))?, + }; + let boards = match p.get("artboards") { + Some(_) if all => return Err(bad(COMMAND, "give `artboards` or `all`, not both")), + Some(v) => listed_artboards(d, v, "artboards", COMMAND)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active_artboard(st)], + }; + // The current fill is the one an interaction in progress began with: a preview's selected + // rectangles may have given their color to the new-art paints since. + let current = st.interaction.as_ref().map_or(&s.paint.fill, |it| &it.paint.fill); + let fill = match p.get("color") { + Some(v) => Paint::solid(color_value(v).ok_or_else(|| bad(COMMAND, format!("bad color {v}")))?), + None => match current { + Paint::None => return Err(bad(COMMAND, "the current fill is None: pick a fill or give `color`")), + paint => paint.clone(), + }, + }; + let name = match p.get("layer") { + None => LAYER.to_string(), + Some(v) => { + let name = v.as_str().map(str::trim).ok_or_else(|| bad(COMMAND, "`layer` must be a string"))?; + if name.is_empty() { + return Err(bad(COMMAND, "`layer` must not be empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(COMMAND, format!("`layer` must be at most {MAX_NAME} characters"))); + } + name.to_string() + } + }; + let rects: Vec<_> = boards.iter().filter_map(|i| d.artboards.get(*i).map(|a| a.rect)).collect(); + let look = NewArt::plain(Appearance::basic(fill, Paint::None, 0.0)); + let (layer, created, ids) = s.edit("Flood Fill Artboards", |d, sel| { + let found = d.layers.iter().find(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())).map(|l| l.id); + let (layer, created) = match found { + Some(id) => (id, false), + // A new layer goes below every other, so the rectangles stay behind the art. + None => { + let n = make_layer(d, Some(&name)); + (d.insert(None, 0, n)?, true) + } + }; + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let live = LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }; + let path = live.to_path(); + let kind = NodeKind::Path { path, rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + // A reused layer keeps its lock and visibility; the rectangles on a locked or hidden one are + // not selected. + if d.node(layer).is_some_and(|l| l.visible && !l.locked) { + sel.set(ids.iter().copied()); + } + Ok((layer, created, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "created": created })) +} + +/// The index of the view's active artboard ([`crate::DocState::active_artboard`]): when the +/// document no longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &crate::DocState) -> usize { + let at = |id: Option| id.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(st.doc.opened_artboard)).unwrap_or(0) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index d1bd77727d..1642a81196 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -195,6 +195,137 @@ fn the_layers_highlighted_in_the_layers_panel_are_the_default() { assert_eq!((r["symbols"].clone(), r["skipped"].as_array().unwrap().len()), (json!(["Icons"]), 1)); } +const FLOOD: &str = "addon.document.floodFillArtboards"; + +/// A document of three 100 × 80 artboards with one rectangle on `Layer 1`, and a red fill. +fn boards() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s +} + +/// The children of the layer `id`. +fn kids(s: &Session, id: u64) -> Vec> { + s.doc().unwrap().doc.node(NodeId(id)).unwrap().children().unwrap().to_vec() +} + +#[test] +fn flood_fill_covers_the_active_artboard_on_a_new_layer_at_the_bottom() { + let mut s = boards(); + let (current, steps) = (s.doc().unwrap().active_layer, s.doc().unwrap().history.undo.len()); + let before = s.doc().unwrap().doc.clone(); + let second = before.artboards[1].clone(); + s.doc_mut().unwrap().active_artboard = Some(second.id); + let r = s.execute(FLOOD, &json!({})).unwrap(); + assert_eq!(r["created"], json!(true), "{r}"); + let st = s.doc().unwrap(); + let layer = &st.doc.layers[0]; + assert_eq!((layer.id.0, layer.name.as_deref()), (r["layer"].as_u64().unwrap(), Some("Flood Fill")), "a new layer below the others"); + assert_eq!(st.doc.layers.len(), 2); + let rects = kids(&s, layer.id.0); + assert_eq!(rects.len(), 1); + let rect = &rects[0]; + assert_eq!(r["ids"], json!([rect.id.0])); + assert_eq!(rect.geometric_bounds(), Some(second.rect), "exactly the active artboard"); + assert!(matches!(&rect.kind, NodeKind::Path { live: Some(live), .. } if matches!(**live, vectorcraft_doc::LiveShape::Rectangle { .. }))); + assert_eq!(rect.appearance.fill_paint(), s.paint.fill, "the current fill"); + assert_eq!(rect.appearance.stroke_paint(), vectorcraft_color::Paint::None, "no stroke"); + let st = s.doc().unwrap(); + assert_eq!((st.selection.objects.clone(), st.active_layer), (vec![rect.id], current), "the rectangle is selected; the current layer stays"); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + assert_eq!(st.history.undo.last().unwrap().label, "Flood Fill Artboards"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before, "undo removes the layer and the rectangle"); +} + +#[test] +fn flood_fill_reuses_its_layer_and_keeps_its_lock_and_visibility() { + let mut s = boards(); + let layer = s.execute(FLOOD, &json!({})).unwrap()["layer"].as_u64().unwrap(); + let first = s.doc().unwrap().doc.layers.iter().find(|l| l.name.as_deref() == Some("Layer 1")).unwrap().id.0; + let art = kids(&s, first)[0].id.0; + s.execute("select.set", &json!({"ids": [art]})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer, "locked": true})).unwrap(); + let selected = s.doc().unwrap().selection.objects.clone(); + assert_eq!(selected.len(), 1); + let r = s.execute(FLOOD, &json!({"all": true, "color": "#00ff00"})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(layer)), "{r}"); + let st = s.doc().unwrap(); + let node = st.doc.node(NodeId(layer)).unwrap(); + assert!(node.locked && node.visible, "the layer stays locked"); + assert_eq!(st.doc.layers.len(), 2, "no second layer"); + assert_eq!(st.selection.objects, selected, "art on a locked layer is not selected"); + let rects = kids(&s, layer); + let added: Vec<_> = rects[1..].iter().map(|n| n.geometric_bounds().unwrap()).collect(); + let artboards: Vec<_> = st.doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(added, artboards, "one rectangle per artboard, on top of the layer's art"); + let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap()); + assert!(rects[1..].iter().all(|n| n.appearance.fill_paint() == green)); + // Hidden: the layer stays hidden, and listed artboards are filled once each, in order. + s.execute("layer.setProps", &json!({"id": layer, "locked": false, "visible": false})).unwrap(); + let r = s.execute(FLOOD, &json!({"artboards": [2, 0, 2]})).unwrap(); + let bounds = |id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + let new: Vec<_> = r["ids"].as_array().unwrap().iter().map(bounds).collect(); + assert_eq!(new, [artboards[0], artboards[2]]); + assert!(!s.doc().unwrap().doc.node(NodeId(layer)).unwrap().visible); + assert_eq!(s.doc().unwrap().selection.objects, selected, "art on a hidden layer is not selected"); + // A layer named by `layer`, found or made. + let r = s.execute(FLOOD, &json!({"layer": "Layer 1", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap(); + assert_eq!((r["created"].clone(), r["layer"].as_u64()), (json!(false), Some(first))); + let r = s.execute(FLOOD, &json!({"layer": " Paper "})).unwrap(); + assert_eq!((r["created"].clone(), s.doc().unwrap().doc.layers[0].name.as_deref()), (json!(true), Some("Paper"))); +} + +#[test] +fn flood_fill_refuses_bad_params_and_a_none_fill() { + let mut s = boards(); + let long = "x".repeat(256); + for p in [ + json!({"color": "#ff000080"}), + json!({"color": "red-ish"}), + json!({"color": null}), + json!({"artboards": [3]}), + json!({"artboards": []}), + json!({"artboards": null}), + json!({"artboards": [0.5]}), + json!({"all": null}), + json!({"all": "yes"}), + json!({"all": true, "artboards": [0]}), + json!({"layer": ""}), + json!({"layer": " "}), + json!({"layer": 5}), + json!({"layer": null}), + json!({"layer": long}), + ] { + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert!(s.execute(FLOOD, &p).is_err(), "{p}"); + assert!(*s.doc().unwrap().doc == *before.0 && s.doc().unwrap().history.undo.len() == before.1, "{p} changed nothing"); + } + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute(FLOOD, &json!({})).unwrap_err().to_string(); + assert!(e.contains("the current fill is None"), "{e}"); + assert!(s.execute(FLOOD, &json!({"color": "#336699"})).is_ok(), "a given color needs no current fill"); +} + +/// With New Art Has Basic Appearance off, a preview in a color selects rectangles whose color the +/// new-art fill takes; a later preview without `color` still uses the fill the interaction began with. +#[test] +fn flood_fill_previews_without_color_use_the_fill_the_interaction_began_with() { + let mut s = boards(); + s.prefs.new_art_basic = false; + let red = s.paint.fill.clone(); + s.begin_interaction("Flood Fill Artboards").unwrap(); + s.preview(FLOOD, &json!({"color": "#0000ff"})).unwrap(); + assert_ne!(s.paint.fill, red, "the previewed rectangles gave their color to the new-art fill"); + let r = s.preview(FLOOD, &json!({})).unwrap(); + s.commit_interaction().unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + assert_eq!(fill, red, "the fill the interaction began with, not the previewed color"); +} + /// #4920: Export All Open Documents writes an SVG of each open document; a folder that can't be /// written lists every document in `failed`, and either way the active document stays active. #[test] diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..36d61a7401 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1030,6 +1030,9 @@ fn structured_junk() { ("addon.document.symbolsFromLayers", json!({"layers": "x", "replace": 3})), ("addon.document.symbolsFromLayers", json!({"layers": [1e308, -1, null, u64::MAX], "replace": true})), ("addon.document.symbolsFromLayers", json!({"layers": [], "replace": true})), + ("addon.document.floodFillArtboards", json!({"artboards": [1e308, -1, null, u64::MAX], "color": [1e308]})), + ("addon.document.floodFillArtboards", json!({"all": true, "artboards": "x", "layer": {"name": 3}})), + ("addon.document.floodFillArtboards", json!({"color": {"c": f64::MAX, "m": -1e308, "y": 0, "k": 0}, "layer": "\u{0}"})), // Packaging Tools add-on. ("addon.packaging.setRole", json!({"role": "cut", "ids": [u64::MAX], "overprint": "no"})), ("addon.packaging.setRole", json!({"role": ["crease"], "ids": "all"})), diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..9a251bd2d2 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -98,8 +98,9 @@ pub(crate) fn open( /// The dialog the menu item of command `id` opens, with no params; `None` for another command. pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option> { - use super::{color, pathtools, select, typetools}; + use super::{color, document, pathtools, select, typetools}; let open: fn(&mut VectorcraftApp) -> Result = match id { + document::FLOOD_FILL => document::open_flood_fill, pathtools::set_corners::COMMAND => pathtools::set_corners::open, pathtools::dashes::COMMAND => pathtools::dashes::open, pathtools::bridge::COMMAND => pathtools::bridge::open, diff --git a/crates/ui-egui/src/addons/document.rs b/crates/ui-egui/src/addons/document.rs index 9fcf01e5c2..37be0c3cc8 100644 --- a/crates/ui-egui/src/addons/document.rs +++ b/crates/ui-egui/src/addons/document.rs @@ -3,15 +3,20 @@ //! each layer's art replaced by an instance). Save a Timestamped Copy of a document never saved //! asks for the folder to put it in ([`save_copy`]). Export All Open Documents as PDF or SVG asks //! for the folder the copies go in ([`export_all`], #4920). Batch Trace Folder asks for the folder of -//! images and then the folder the results go in ([`batch_trace`], #4921). +//! images and then the folder the results go in ([`batch_trace`], #4921). Flood Fill Artboards… +//! opens a dialog ([`open_flood_fill`]) that previews on the canvas and runs +//! `addon.document.floodFillArtboards` on OK. use craft::host::{PickRequest, Picked}; use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind}; use serde_json::{Value, json}; +use super::dialogs::Spec; use crate::VectorcraftApp; use crate::file_asks::{Owner, ask}; -use crate::menus::{Sep, cp}; +use crate::menus::{Sep, c, cp}; /// Save a Timestamped Copy. pub const SAVE_COPY: &str = "addon.document.saveTimestampedCopy"; @@ -21,6 +26,14 @@ pub const EXPORT_ALL: &str = "addon.document.exportAllOpen"; pub const BATCH_TRACE: &str = "addon.document.batchTraceFolder"; /// New Symbols from Layers (Convert Layers to Symbols: with their art replaced by instances). const SYMBOLS: &str = "addon.document.symbolsFromLayers"; +/// Flood Fill Artboards. +pub const FLOOD_FILL: &str = "addon.document.floodFillArtboards"; +/// The layer Flood Fill Artboards puts its rectangles on unless another is named. +const FLOOD_LAYER: &str = "Flood Fill"; +/// The color the Flood Fill Artboards dialog opens with when the current fill is not a solid color. +const GRAY: [f32; 3] = [0.5, 0.5, 0.5]; + +static FLOOD_SPEC: Spec = Spec { command: FLOOD_FILL, params: flood_params, found: None }; /// Object › Plug-ins › Document Tools. pub fn menu() -> Vec { @@ -32,9 +45,73 @@ pub fn menu() -> Vec { Sep, cp("New Symbols from Layers", SYMBOLS, json!({})), cp("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), + Sep, + c("Flood Fill Artboards…", FLOOD_FILL), ] } +/// The rows of the Flood Fill Artboards dialog. +fn flood_rows() -> Vec { + // Each choice opens on its first option. + let choice = |key: &str, label: &'static str, options: [(&str, &'static str); 2]| { + let default = options[0].0.to_string(); + let options = options.iter().map(|&(id, text)| (id.to_string(), tl!(text).into())).collect(); + Param::new(key, tl!(label), ParamKind::choice(options, Some(default))) + }; + vec![ + choice("artboards", "Artboards:", [("active", "Active Artboard"), ("all", "All Artboards")]), + choice("fill", "Fill:", [("current", "Current Fill"), ("color", "Color")]), + Param::new("color", tl!("Color:"), ParamKind::color(Some(GRAY))).enabled_when("fill", "color"), + Param::new("layer", tl!("Layer:"), ParamKind::text(FLOOD_LAYER)), + ] +} + +/// `#rrggbb` of an sRGB color with components from 0 to 1. +fn hex([r, g, b]: [f32; 3]) -> String { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}", byte(r), byte(g), byte(b)) +} + +/// Flood Fill Artboards' params from the dialog: every artboard or the one the dialog opened on (`board`, kept +/// out of sight), the color only when Color is picked, and the layer named. +fn flood_params(fields: &DialogFields) -> Value { + let mut p = match fields.text("artboards") { + Some("all") => json!({ "all": true }), + _ => json!({ "artboards": [fields.int("board").unwrap_or(0)] }), + }; + if fields.text("fill") == Some("color") { + p["color"] = json!(hex(fields.color("color").unwrap_or(GRAY))); + } + p["layer"] = json!(fields.text("layer").unwrap_or(FLOOD_LAYER)); + p +} + +/// Opens Flood Fill Artboards' dialog on the active artboard and the current fill, or, when there is no fill, on +/// Color with gray. +pub(crate) fn open_flood_fill(app: &mut VectorcraftApp) -> Result { + let board = app.view().map_or(0, |v| v.artboard); + let fill = &app.session.paint.fill; + let color = fill.color().map_or(GRAY, |c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b].map(|v| f32::from(v) / 255.0) + }); + let fields = DialogFields::from_pairs([ + ("artboards", FieldValue::Text("active".into())), + ("fill", FieldValue::Text(if fill.is_none() { "color" } else { "current" }.into())), + ("color", FieldValue::Color(color)), + ("layer", FieldValue::Text(FLOOD_LAYER.into())), + ("board", FieldValue::Int(board as i64)), + ]); + super::dialogs::open(app, &FLOOD_SPEC, fields, |fields| { + let named = fields.text("layer").is_some_and(|name| !name.trim().is_empty()); + ParamDialog::new(FLOOD_FILL, tl!("Flood Fill Artboards"), flood_rows()) + .ok_enabled(named) + .ok_reason(tl!("Name the layer.").into()) + .values(Bind::bound(fields)) + .previews(true) + }) +} + /// The params as an object, with the picked folder under `key`. fn with_folder(p: &Value, key: &str, picked: &Picked) -> Result { let folder = picked.first_path().ok_or("no folder picked")?; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 1cc56d18cb..40a9985c38 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -4,6 +4,8 @@ use serde_json::json; use vectorcraft_engine::Session; use super::{BATCH_TRACE, EXPORT_ALL, SAVE_COPY}; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; use crate::tests::picks::{poll, scripted}; use crate::{VectorcraftApp, menus}; use craft::host::PickKind; @@ -237,3 +239,109 @@ fn batch_trace_folder_asks_for_both_folders() { assert_eq!(picker.requests().len(), asked + 1, "declining the source asks nothing more"); let _ = std::fs::remove_dir_all(&dir); } + +/// A window, a document of three 100 × 80 artboards with the second active, and a red fill. +fn boards() -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 80, "artboards": 3})).unwrap(); + app.sync_views(); + if let Some(v) = app.view_mut() { + v.artboard = 1; + } + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app +} + +/// The names of the document's top-level layers, bottom first. +fn layer_names(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +/// The bounds and fill of each object on the bottom layer. +fn bottom_art(app: &VectorcraftApp) -> Vec<(vectorcraft_geom::Rect, vectorcraft_color::Paint)> { + let doc = &app.session.doc().unwrap().doc; + let art = doc.layers[0].children().map(|c| c.to_vec()).unwrap_or_default(); + art.iter().map(|n| (n.geometric_bounds().unwrap(), n.appearance.fill_paint())).collect() +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn flood_fill_typed_layer_name_previews_and_ok_applies_one_step() { + let app = boards(); + let undo = undo_len(&app); + let artboard = app.session.doc().unwrap().doc.artboards[1].rect; + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + panel.click("Layer"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("Paper"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#ff0000").unwrap()); + { + let app = panel.app(); + assert_eq!(layer_names(&app)[0], "Paper", "the preview makes the typed layer at the bottom"); + assert_eq!(bottom_art(&app), [(artboard, red.clone())], "the active artboard, in the current fill"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + } + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer_names(&app), ["Paper", "Layer 1"]); + assert_eq!(bottom_art(&app), [(artboard, red)]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + assert_eq!(app.session.doc().unwrap().history.undo.last().unwrap().label, "Flood Fill Artboards"); +} + +#[test] +fn flood_fill_cancel_rolls_the_preview_back() { + let app = boards(); + let (undo, doc) = (undo_len(&app), app.session.doc().unwrap().doc.clone()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Flood Fill Artboards…"); + panel.frame(); + assert_eq!(layer_names(&panel.app())[0], "Flood Fill", "previewed"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!((*app.session.doc().unwrap().doc == *doc, undo_len(&app)), (true, undo), "nothing kept"); +} + +#[test] +fn flood_fill_all_artboards_in_a_chosen_color() { + let mut app = boards(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + host::set(&app, id, "artboards", json!("all")); + assert_eq!(host::read(&app, id, |f| f.color("color")), Some([1.0, 0.0, 0.0]), "Color opens on the current fill's color"); + host::set(&app, id, "fill", json!("color")); + host::set(&app, id, "color", json!([0.0, 0.0, 1.0])); + let params = host::read(&app, id, super::flood_params); + assert_eq!(params, json!({"all": true, "color": "#0000ff", "layer": "Flood Fill"})); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let blue = vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#0000ff").unwrap()); + let artboards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect, blue.clone())).collect(); + assert_eq!(bottom_art(&app), artboards, "one rectangle per artboard, in the dialog's color"); +} + +#[test] +fn flood_fill_opens_on_color_without_a_fill_and_needs_a_layer_name() { + let mut app = boards(); + app.run("paint.setFill", json!({"none": true})).unwrap(); + click(&mut app, "Flood Fill Artboards…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| f.text("fill").map(str::to_owned)), Some("color".to_owned())); + host::set(&app, id, "layer", json!(" ")); + assert!(!host::confirm(&app, id), "OK is off without a layer name"); + host::set(&app, id, "layer", json!("Back")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(layer_names(&app)[0], "Back"); +} diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..287e858648 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17511,6 +17511,22 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la {"name":"run_command","arguments":{"command":"addon.document.symbolsFromLayers","params":{"replace":true}}} ``` +`addon.document.floodFillArtboards {artboards?, all?, color?, layer?}` adds an editable rectangle exactly the size of +each artboard, painted with `color` and no stroke, as one undo step. `artboards` lists artboard indices (the active +artboard by default), and `all: true` takes every artboard instead; the two can't be given together. `color` takes the +colors the paint commands take (`#rrggbbaa` and `#rgba` are refused); without it the rectangles take the current fill +(in a preview, the fill the preview began with), and a current fill of None is an error. The rectangles go on top of the top-level layer named `layer` (`Flood Fill` by +default, at most 255 characters), which is made at the bottom of the layers when the document has none. A layer that +already exists keeps its lock and visibility. The rectangles are selected unless that layer is locked or hidden, and +the current layer stays as it was. Null and values of the wrong type are errors; the command is refused while an +opacity mask is edited. The desktop app's Flood Fill Artboards… dialog picks the active artboard or all of them, the +current fill or a color, and the layer, and previews on the canvas. → `{ids: [rectangle id…], layer, created}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{}}} +{"name":"run_command","arguments":{"command":"addon.document.floodFillArtboards","params":{"all":true,"color":"#f4e9d8","layer":"Paper"}}} +``` + ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are From 84dc59e4df27eba2abfa166e238bd2d576f4eae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 01:45:01 -0800 Subject: [PATCH 117/533] Dialogs: a number field left on text that is not a number restores the value before it Typing a number into a dialog's number field, then text that is not a number, then leaving the field cancels the typing. These dialogs read the field with value(), which ignores the cancel, so they kept the last number typed. They now read events.landed(), as the tool option form does since #9750, and take back the value the cancel restores. - Rearrange Artboards, Layer Options, Define Perspective Grid, Bullets and Numbering, PNG Options, Composite Fonts, Graph Data, Print, Transform Each, Width Point Edit, Split Into Grid and the gradient stop popover. - Layer Options for several layers sends no Dim Images value when the canceled typing began with the field unset. - Bullets and Numbering puts a blank field back to blank. - Graph Data's Column Width gives back every column's own width. - Width Point Edit: an edit of Side 1, Side 2 or Total Width that ends in a cancel (Escape, or leaving the field on text that is not a number) puts back the side widths from before the edit, but only the sides that still hold the edit's last value. Canceling Total Width after a 0 keeps unequal sides unequal. With several points selected, each point gets back its own widths, also when the field showed no common width and the edit was the wheel turned over the held field and then Escape. OK no longer applies the canceled width. - Width Point Edit, Graph Data's Column Width and Layer Options' Dim Images to put values back only when the user canceled the edit. A value set by anything else while an edit runs stays: ui.dialog.set (in Graph Data also a per-column width set through widths), and in Width Point Edit a link toggle or an edit of the other set of sides, even when it sets the same value as the canceled edit. --- .../ui-egui/src/dialogs/bullets_numbering.rs | 63 +- crates/ui-egui/src/dialogs/composite_fonts.rs | 2 +- .../src/dialogs/composite_fonts/tests.rs | 30 + crates/ui-egui/src/dialogs/gradient_stop.rs | 32 +- crates/ui-egui/src/dialogs/graph_data.rs | 113 +++- crates/ui-egui/src/dialogs/layer_options.rs | 84 ++- crates/ui-egui/src/dialogs/path_ops.rs | 4 +- .../ui-egui/src/dialogs/perspective_grid.rs | 8 +- crates/ui-egui/src/dialogs/png_options.rs | 2 +- crates/ui-egui/src/dialogs/print.rs | 2 +- .../src/dialogs/rearrange_artboards.rs | 31 +- crates/ui-egui/src/dialogs/tests.rs | 61 ++ crates/ui-egui/src/dialogs/tests_export.rs | 34 + .../ui-egui/src/dialogs/tests_perspective.rs | 33 + crates/ui-egui/src/dialogs/tests_print.rs | 41 ++ crates/ui-egui/src/dialogs/transform_each.rs | 14 +- crates/ui-egui/src/dialogs/width_point.rs | 180 +++++- .../ui-egui/src/dialogs/width_point/tests.rs | 607 ++++++++++++++++++ 18 files changed, 1272 insertions(+), 69 deletions(-) diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index dd09594490..5812e37270 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -27,7 +27,7 @@ use std::borrow::Cow; use std::sync::{Arc, Weak}; -use craft::behavior::{Mixed, Selection, SelectionChange, keyed}; +use craft::behavior::{EditEvent, EditEvents, Mixed, Selection, SelectionChange, keyed}; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; @@ -317,8 +317,20 @@ impl BulletsDialog { fn level(&mut self, ui: &mut Ui) { let value = self.fields.get("listLevel").and_then(Value::as_f64); let edit = NumberField::new(tl!("Level:"), Bind::given(value)).range(1.0..=LIST_LEVELS as f64).commit_decimals(0).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("listLevel".into(), json!(v)); + self.land("listLevel", &edit.edit.events); + } + + /// Sets `key` to the number its field's `events` leave: the number entered or the number a canceled edit + /// restores, and no number where a canceled edit restores a blank field. + fn land(&mut self, key: &str, events: &EditEvents>) { + match events.landed() { + Some(Some(v)) => { + self.fields.insert(key.into(), json!(v)); + } + Some(None) if matches!(events.ended(), Some(EditEvent::Cancel { .. })) => { + self.fields.remove(key); + } + _ => {} } } @@ -393,9 +405,7 @@ impl BulletsDialog { .enabled(on == Some(true)) .id_salt("startNumber") .show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert("startNumber".into(), json!(v)); - } + self.land("startNumber", &edit.edit.events); }); } @@ -415,9 +425,7 @@ impl BulletsDialog { fn indent(&mut self, ui: &mut Ui, key: &'static str, label: &'static str) { let value = self.fields.get(key).and_then(Value::as_f64); let edit = NumberField::length(label, Bind::given(value), self.lengths).range(INDENTS).show(ui); - if let Some(Some(v)) = edit.value().copied() { - self.fields.insert(key.into(), json!(v)); - } + self.land(key, &edit.edit.events); } } @@ -1239,4 +1247,41 @@ mod tests { ok(&mut app); assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Dot).at_level(3))); } + + /// Leaving Level, Start at or an indent on text that is not a number cancels the typing: the field goes back to + /// the number it had before it, or to blank where the paragraphs differ, and so does the type. + #[test] + fn a_canceled_number_edit_restores_the_field_and_the_type() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (mut app, id) = app(); + app.run("text.setFormat", json!({"number": "arabic"})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "leftIndent": 30, "start": 0, "end": 0})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1800.0)); + panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap(); + panel.frame(); + set(&mut panel.app(), "startAt", json!(true)); + panel.frame(); + assert!(fields(&panel.app()).get("leftIndent").is_none(), "the paragraphs' left indents differ: blank"); + let state = |panel: &Panel| { + let app = panel.app(); + (sent(&app), first(&app, id)) + }; + for name in ["Level:", "Start at:", "Left Indent:", "First Line Indent:"] { + let before = state(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("7"); + assert_ne!(state(&panel).0, before.0, "typing into {name} proposes a number"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the dialog open"); + assert_eq!(state(&panel), before, "leaving {name} on text that is not a number restores it"); + } + } } diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 0465d1e322..5592a2c274 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -719,7 +719,7 @@ fn percent<'r>(list: ListRow<'r>, spec: &Percent, value: f64, at: usize, edits: let Percent { column, label, range, edit } = spec; let (edit, field) = (*edit, NumberField::new(*label, Bind::given(Some(value))).range((*range).clone()).unit("%")); list.cell_field(column.clone(), field, move |out| { - if let Some(Some(v)) = out.edit.value().copied() { + if let Some(Some(v)) = out.edit.events.landed().copied() { edits.borrow_mut().push((at, edit(v))); } }) diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 48070f0b41..be02c8046c 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -650,6 +650,36 @@ fn a_highlighted_part_style_applies_only_once_it_is_chosen() { assert_ne!(parts(&p), before, "Enter sets the style"); } +/// Leaving a part's Size or Baseline on text that is not a number cancels the typing, and the part goes back to the +/// value it had before it. +#[test] +fn a_canceled_part_percentage_restores_the_part() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut p = Panel::new(app(), crate::tests::picks::dialogs); + p.room(egui::vec2(1280.0, 1100.0)); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + p.frame(); + p.frame(); + let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone())); + for name in ["Size", "Baseline"] { + let before = parts(&p); + p.click_role(name, Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("37"); + assert_ne!(parts(&p), before, "typing into {name} proposes a value"); + p.type_text("x"); + p.key(Key::Tab, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "leaving {name} keeps the dialog open"); + assert_eq!(parts(&p), before, "leaving {name} on text that is not a number restores the part"); + } +} + #[test] fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index 5b2ee66107..585d280e0f 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -524,12 +524,13 @@ fn swatches(ui: &mut Ui, feed: &Feed, filed: &mut Filed) { filed.swatch = at.and_then(|i| feed.swatches.get(i)).cloned(); } -/// A percent field named `label` over `value`; the number the user entered in this pass. +/// A percent field named `label` over `value`; the number the user entered in this pass, or the number a canceled +/// typing gives back. fn percent_field(ui: &mut Ui, label: String, value: f64) -> Option { let field = Field::new(label.clone()).show(ui, |ui, _| { NumberField::new(label.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Percent).range(0.0..=100.0).step(1.0).show(ui) }); - field.inner?.value().copied().flatten() + field.inner?.edit.events.landed().copied().flatten() } /// The popover's size before it has been drawn, for placing it. @@ -869,6 +870,33 @@ mod tests { assert!(set(&app, "color", json!("red")).is_err()); } + /// Leaving Opacity or Location on text that is not a number cancels the typing, and OK then leaves the stop as it + /// was. + #[test] + fn a_canceled_opacity_or_location_leaves_the_stop_as_it_was() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + for name in ["Opacity", "Location"] { + let mut panel = Panel::new(app(), crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open_popover(&mut panel.app()); + panel.frame(); + let before = stops(&panel.app()); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("40"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "leaving {name} keeps the popover open"); + confirm(&mut panel.app()); + assert_eq!(stops(&panel.app()), before, "OK after leaving {name} on text that is not a number leaves the stop as it was"); + } + } + #[test] fn the_popover_discards_a_pending_edit_after_selecting_other_art() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 1eb37190e5..b42f240922 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use std::sync::Arc; -use craft::behavior::{EditEvent, NumberCodec}; +use craft::behavior::{CancelReason, EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; use craft::table::ui::{ CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions, @@ -140,6 +140,8 @@ struct Lines { columns: LineIndex, /// The own width of the column whose edge a drag holds, as it was when the drag began. resize_from: Option>, + /// Cell Style's Column Width and the columns' own widths, as they were when typing a Column Width began. + width_from: Option<(u64, Vec>)>, } impl Lines { @@ -149,6 +151,7 @@ impl Lines { rows: LineIndex::uniform(ROW_H, 0), columns: LineIndex::uniform(digits_px(DEFAULT_WIDTH), MAX_COLS as u32), resize_from: None, + width_from: None, } } @@ -633,16 +636,31 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { let field = whole(&units, tl!("Number of Decimals"), values.decimals.unwrap_or(DEFAULT_DECIMALS), MAX_DECIMALS) .enabled(values.decimals.is_some()) .show(ui); - if let Some(n) = digits(field.edit.value().copied().flatten(), MAX_DECIMALS) { + if let Some(n) = digits(field.edit.events.landed().copied().flatten(), MAX_DECIMALS) { values.decimals = Some(n); } Text::new(tl!("Column Width:")).show(ui); let field = whole(&units, tl!("Column Width"), width(values), MAX_WIDTH).show(ui); - // A value entered with Enter sets every column, also when it is the width shown. Leaving the - // field without a new value keeps the columns' own widths. - let typed = digits(field.edit.value().copied().flatten(), MAX_WIDTH); - if typed.is_some() || field.edit.submitted { - set_width(values, typed.unwrap_or_else(|| width(values))); + let events = &field.edit.events; + if events.began() { + lines.width_from = Some((values.width, values.widths.clone())); + } + if let Some(reason) = events.cancel_reason() { + // A user rollback restores Cell Style's width and the columns' own widths; other cancels keep the host's values. + if let Some((shown, own)) = lines.width_from.take().filter(|_| matches!(reason, CancelReason::Escape | CancelReason::Blur)) { + values.width = shown; + values.widths = own; + } + } else { + // A value entered with Enter sets every column, also when it is the width shown. Leaving the + // field without a new value keeps the columns' own widths. + let typed = digits(events.value().copied().flatten(), MAX_WIDTH); + if typed.is_some() || field.edit.submitted { + set_width(values, typed.unwrap_or_else(|| width(values))); + } + if events.ended().is_some() { + lines.width_from = None; + } } }); lines.sync(extent(values, active(state)), values); @@ -830,6 +848,9 @@ impl StackDialog for GraphDataDialog { load(&self.sheet, &self.state, &mut self.entry); } } + if matches!(field, "width" | "widths") { + self.lines.width_from = None; + } Ok(()) } } @@ -1399,4 +1420,82 @@ mod tests { edit(&app, |d| set_col_digits(&mut d.sheet, 1, 4)); assert_eq!(read(&app, |d| (col_digits(&d.sheet, 1), col_digits(&d.sheet, 3))), (4, 7), "a drag after it gives that column its own width"); } + + /// Leaving Number of Decimals or Column Width on text that is not a number cancels the typing: the decimals go back + /// to what they were, and so do Column Width and the widths columns were given of their own. + #[test] + fn a_canceled_cell_style_number_restores_the_decimals_and_the_widths() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + set_field(&panel.app(), "decimals", json!(2)).unwrap(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + let style = |panel: &Panel| read(&panel.app(), |d| (d.sheet.decimals, d.sheet.width, d.sheet.widths.clone())); + for name in ["Number of Decimals", "Column Width"] { + let before = style(&panel); + panel.click_role(name, Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + assert_ne!(style(&panel), before, "typing into {name} proposes a value"); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(style(&panel), before, "leaving {name} on text that is not a number restores Cell Style"); + } + } + + /// An outside Column Width replaces a running edit and keeps the columns at the assigned width. + #[test] + fn an_outside_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + edit(&panel.app(), |d| set_col_digits(&mut d.sheet, 1, 4)); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "width", json!(13)).unwrap(); + let assigned = read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())); + panel.frame(); + assert_eq!(read(&panel.app(), |d| (d.sheet.width, d.sheet.widths.clone())), assigned, "the host's column widths survive cancellation"); + } + + /// Outside per-column widths survive invalid Column Width text. + #[test] + fn an_outside_per_column_width_survives_a_running_edit() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let (app, _) = app_with(",a,b\nQ1,1,2", "column"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()).unwrap(); + panel.frame(); + panel.click_role("Column Width", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + set_field(&panel.app(), "widths", json!([null, 13, null])).unwrap(); + panel.type_text("x"); + panel.key(Key::Tab, Modifiers::NONE); + panel.frame(); + assert_eq!(read(&panel.app(), |d| d.sheet.widths.clone()), vec![None, Some(13), None], "invalid Column Width text preserves assigned widths"); + } } diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index fb0ad99911..d95f76c3ab 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -11,6 +11,7 @@ use std::cell::RefCell; +use craft::behavior::CancelReason; // PLAN: `craft::color_ui` and `craft::theme` need the `craft` facade (feature `color-ui`) in ui-egui's Cargo.toml, which has only `craft-ui`; the owner of the craft-libs pin adds it. use craft::color_ui::ui::{ChosenColor, ColorChoice, NamedColor}; use craft::theme::Srgba; @@ -72,6 +73,8 @@ pub(crate) struct LayerOptionsValue { ids: Vec, /// The fields set in the dialog, by its controls or `ui.dialog.set`. set: Vec<&'static str>, + /// While a typed percentage runs: whether the percentage was set in the dialog when the typing began. + dim_set_before_typing: Option, opened: Option, } @@ -93,6 +96,7 @@ impl Default for LayerOptionsValue { mode: "edit", ids: Vec::new(), set: Vec::new(), + dim_set_before_typing: None, opened: None, } } @@ -362,10 +366,22 @@ fn body(ui: &mut egui::Ui, v: &mut LayerOptionsValue, requested: &RefCell; x.async::b", &options).is_ok()); + let mut r = Realm::with_options(options, Limits::default()); + let src = "var async = new Namespace('u'); var x = 78; String(x.async::b)"; + assert_eq!(r.run(src), Ok(JsValue::String("7".into()))); } #[test] From 937817609d2347b5bead727b282004dbadca2d69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:33:34 -0800 Subject: [PATCH 347/533] Tests: the PDF 1.3 transparency check reads dictionaries only pdf_1_3_flattens_all_transparency_and_looks_the_same failed now and then because its transparency check searched the whole file for `/BM`. The file ID, written in the trailer and the XMP stream, is base64 that changes with the export time, so some exports had an ID that spells `/BM` and the check reported a blend mode in a flat file. The check now leaves out literal strings and stream data. A stream is found only by the whole `stream` keyword, not a name such as `/stream`, and its data is skipped by the stream dictionary's own `/Length`, read from the outermost dictionary and from its object when it is indirect. A length that does not end at `endstream`, or a stream with no `endstream`, fails the check. Every dictionary key it looked for is still checked. A new test covers an ID and an XMP packet that spell the keys, nested and escaped parentheses, `endstream` inside stream data, nested and indirect lengths, and wrong lengths. The helper comes from #10537. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 215 +++++++++++++++++++- 1 file changed, 213 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..f3493555c9 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,157 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()) } -/// The transparency `pdf` has, in its dictionaries. +/// Whether `b` ends a PDF token: white space or a delimiter. +fn ends_token(b: u8) -> bool { + b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b) +} + +/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the +/// `startxref` at `startxref` and following `/Prev`. +fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option { + let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::().ok()?; + let mut visited = vec![]; + loop { + if visited.contains(&offset) { + return None; + } + visited.push(offset); + let table = String::from_utf8_lossy(pdf.get(offset..)?); + let mut words = table.split_ascii_whitespace(); + if words.next()? != "xref" { + return None; + } + loop { + let first = words.next()?; + if first == "trailer" { + break; + } + let first = first.parse::().ok()?; + let count = words.next()?.parse::().ok()?; + for index in 0..count { + let at = words.next()?.parse::().ok()?; + let entry_generation = words.next()?.parse::().ok()?; + let status = words.next()?; + if first.checked_add(index)? == number { + return (status == "n" && entry_generation == generation).then_some(at); + } + } + } + let trailer = table.split_once("trailer")?.1.split_once(">>")?.0; + let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()); + words.find(|&w| w == "Prev")?; + offset = words.next()?.parse().ok()?; + } +} + +/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary +/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` +/// when it is missing or cannot be read. +fn stream_length(text: &[u8], pdf: &[u8]) -> Option { + let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let dict = &text[from..]; + let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; + let mut depth = 1usize; + let mut length = None; + while i < dict.len() && depth > 0 { + let rest = &dict[i..]; + if rest.starts_with(b"<<") { + depth += 1; + i += 2; + } else if rest.starts_with(b">>") { + depth -= 1; + i += 2; + } else if rest[0] == b'<' { + // A hex string. + i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1); + } else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) { + let value = String::from_utf8_lossy(&rest[7..]); + let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect(); + length = match words[..] { + // `n g R` is an indirect length: the integer in object `n g`. + [n, g, "R", ..] => { + let header = format!("{n} {g} obj"); + let read_length = |at: usize| { + let body = String::from_utf8_lossy(&pdf[at + header.len()..]); + match body.split_ascii_whitespace().take(2).collect::>()[..] { + [n, "endobj"] => n.parse::().ok(), + _ => None, + } + }; + if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") { + let at = + xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref"); + let object = pdf.get(at..).expect("stream /Length xref offset is outside the file"); + assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object"); + read_length(at) + } else { + pdf.windows(header.len()) + .enumerate() + // An object header starts a line, and the length object holds one integer. + .filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n'))) + .find_map(|(at, _)| read_length(at)) + } + } + [n, ..] => n.parse::().ok(), + [] => None, + }; + i += 7; + } else { + i += 1; + } + } + length +} + +/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out: +/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time +/// and can spell `/BM`. fn transparency(pdf: &[u8]) -> Vec<&'static str> { - let text = String::from_utf8_lossy(pdf); + let mut text = Vec::with_capacity(pdf.len()); + let mut i = 0; + while i < pdf.len() { + let rest = &pdf[i..]; + // A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name. + let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>'; + if keyword_start && rest.starts_with(b"endstream") { + text.extend_from_slice(b"endstream"); + i += b"endstream".len(); + } else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) { + // Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to + // `endstream`); its bytes are not PDF syntax. + let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 }; + i = match stream_length(&text, pdf) { + Some(n) => { + let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream"); + while matches!(pdf.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream"); + end + } + None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"), + }; + } else if rest[0] == b'(' { + // A literal string: balanced parentheses, with `\` escaping the next byte. + let mut depth = 0usize; + while i < pdf.len() { + match pdf[i] { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + i += 1; + if depth == 0 { + break; + } + } + } else { + text.push(rest[0]); + i += 1; + } + } + let text = String::from_utf8_lossy(&text); let mut found = vec![]; for (what, there) in [ ("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")), @@ -193,3 +341,66 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err() ); } + +/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check +/// reads the file's dictionaries only, not its strings or its XMP packet. +#[test] +fn the_transparency_check_skips_strings_and_metadata() { + let pdf = b"%PDF-1.3\n5 0 obj\n<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]); + // Stream data is skipped by its length, even when it holds `endstream` itself. + let pdf = b"1 0 obj\n<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // Only the stream dictionary's own `/Length` counts, not one in a nested dictionary. + let pdf = b"1 0 obj\n<>>>\nstream\n/BM \nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + // `stream` inside a name is not the keyword. + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // An indirect length is read from its object, so `endstream` in the data does not end it. + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let payload = b"2 0 obj\n13\nendobj\nendstream /BM"; + let mut pdf = b"%PDF-1.3\n".to_vec(); + let stream_at = pdf.len(); + pdf.extend_from_slice(b"1 0 obj\n<>\nstream\n"); + pdf.extend_from_slice(payload); + pdf.extend_from_slice(b"\nendstream\nendobj\n"); + let length_at = pdf.len(); + pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes()); + let catalog_at = pdf.len(); + pdf.extend_from_slice(b"3 0 obj\n<>\nendobj\n"); + let pages_at = pdf.len(); + pdf.extend_from_slice(b"4 0 obj\n<>\nendobj\n"); + let xref_at = pdf.len(); + pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n"); + for at in [stream_at, length_at, catalog_at, pages_at] { + pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes()); + assert_eq!(transparency(&pdf), Vec::<&str>::new()); + // A stream with no length and no `endstream` fails rather than hiding the rest of the file. + let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<>"; + assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err()); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic"); + let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +} From 420ec1503f6c7e93c56f59d653915f5fe993ab38 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:26:03 -0800 Subject: [PATCH 348/533] Scripts: automated Yes keeps the script warning on; a Copy note keeps the recording limit shown ScriptAnswer records whether automation gave the answer, so an automated Yes is refused even when a later frame without injected input takes it. After a script's Copy, the recording limit's message is set again so the Copy's format notes do not replace it; a write failure reported at once stays. --- crates/ui-egui/src/dialogs/script_run.rs | 17 +++++++++----- crates/ui-egui/src/script_runs.rs | 12 +++++++++- crates/ui-egui/src/tests/script_dialogs.rs | 12 +++++++++- crates/ui-egui/src/tests/sysclip.rs | 27 ++++++++++++++++++++++ 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index df0474e845..e7c9acffcc 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -66,6 +66,7 @@ use craft::ui::dialog::{ use craft::ui::display::Text; use craft::ui::layout_components::Stack; use craft::ui::runtime::keys; +use craft::ui::runtime::windows::WindowHost; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; @@ -183,6 +184,8 @@ pub(crate) struct ScriptAnswer { pub(crate) answer: &'static str, /// The text of a prompt. pub(crate) value: String, + /// Automation gave the answer: `ui.dialog.confirm`, or a click in a pass automation drove. + pub(crate) automated: bool, } /// What a script's file dialog answers with. @@ -319,12 +322,13 @@ impl StackDialog for ScriptNotice { self.value = cut_to(&self.value, MAX_PROMPT_BYTES).to_string(); } let answer = *answers.get(picked?)?; - Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() })) + let automated = WindowHost::of(ui.ctx()).injected_pass(); + Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated })) } fn confirm(&mut self, _: &egui::Context) -> Option { let answer = self.answer.unwrap_or_else(|| self.default_answer()); - Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() }) + Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated: true }) } fn json_fields(&self) -> Option { @@ -888,13 +892,14 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult "no", _ => "stop", }; - ScriptAnswer { kind, answer, value: String::new() } + ScriptAnswer { kind, answer, value: String::new(), automated: false } } }; - // Only the person at the keyboard turns off the external script warning: Yes from a pass - // automation drives is refused, the warning stays on, and the question opens again. + // Only the person at the keyboard turns off the external script warning: Yes that automation + // gave, or taken in a pass automation drives, is refused, the warning stays on, and the + // question opens again. let warning_off = app.session.script_dialog_turns_warning_off(); - if warning_off && answer.answer == "yes" && app.automation_is_acting() { + if warning_off && answer.answer == "yes" && (answer.automated || app.automation_is_acting()) { app.status(WARNING_BY_PERSON); if let Some(d) = app.session.script_dialog() { open_notice(app, &d); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 270ea6519c..1ca4fb5085 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -46,13 +46,23 @@ pub fn poll(app: &mut VectorcraftApp) { match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. Ok(report) => { - if !crate::panels::actions::after_journaled_edit(app) { + let limited = crate::panels::actions::after_journaled_edit(app); + if !limited { app.status(format!("Ran {name}")); } // What the script's Copy or Cut left on the clipboard is offered to other apps, as // Edit › Copy does. if report["copied"] == true { + let limit = limited.then(|| app.ui.status.clone()); app.publish_clipboard(false); + // The limit's message is set again, so the notes of the Copy's formats do not + // replace it. A write failure reported at once stays on the status bar. + if let Some(limit) = limit + && app.ui.status == limit + { + app.status(limit); + app.ui.status_notes = None; + } } // The jobs it prepared for a printer wait for the person's answer. script_run::ask_print(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index a2beedb51f..29b439050d 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -339,13 +339,23 @@ fn only_the_person_turns_off_the_external_script_warning() { script_run::forget::(&app); app.ui.answering_control = true; - let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new() }; + let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: false }; script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes)); app.ui.answering_control = false; assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON); assert!(is_open::(&app), "the question opens again"); assert!(app.session.script_dialog().is_some(), "the run still waits"); + // Yes that automation gave is refused in a later frame that automation does not drive. + script_run::forget::(&app); + app.ui.status = String::new(); + let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: true }; + script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes)); + assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON); + assert!(is_open::(&app), "the question opens again"); + assert!(app.session.script_dialog().is_some(), "the run still waits"); + assert!(app.session.prefs.show_external_script_warning, "the warning stays on"); + set(&app, NOTICE_KIND, "answer", json!("no")).unwrap(); assert!(confirm(&mut app, NOTICE_KIND), "No is taken from automation"); assert!(!until_dialog(&mut app)); diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 38efb55e1f..87ac38b1d1 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -628,6 +628,33 @@ fn copy_notes_are_counted_and_kept_in_order() { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None)); } +/// A script whose Copy leaves a note and whose commands take a recording past its limit keeps the +/// limit on the status bar once the Copy's formats are written. +#[test] +fn a_copy_note_does_not_replace_a_scripts_recording_limit() { + let (mut app, board) = app_with_worker(); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run(&mut app, crate::panels::actions::START_RECORDING, json!({})); + for _ in 0..vectorcraft_engine::script::actions::MAX_ACTION_STEPS - 1 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + app.session.script_frames = true; + let source = "vc.run('edit.copy', {}); vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + run(&mut app, "script.run", json!({"source": source, "name": "t.js"})); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the script ends"); + let limit = "the action already has 10,000 steps"; + assert_eq!(app.ui.status, limit, "the status bar names the limit as the run ends"); + background::wait_all(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG]); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); +} + /// A message shown while a Copy's formats are made on the worker stays: the formats are written /// once they are ready, and their note does not replace the newer message. #[test] From f382526eb9a86a38c69c48d6a80ad92757048612 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:32:46 -0800 Subject: [PATCH 349/533] Print: the IPP paper lookup uses IPP_PORT for a server named without a port ipp_queue_uri built ipp://host/printers/name from CUPS_SERVER or the client.conf ServerName, so a server named without a port was always asked on 631, while CUPS clients use IPP_PORT for it. The app now reads IPP_PORT and passes it in; a port in the server name keeps precedence, and a bracketed IPv6 host counts as having a port only after its ]. With no server named, the lookup uses localhost on IPP_PORT only when none of the CUPS domain sockets exists, since CUPS otherwise talks to its socket. docs/mcp.md describes the lookup's server and port. --- apps/vectorcraft/src/printing.rs | 8 +++++- crates/ui-egui/src/dialogs/tests_print.rs | 33 +++++++++++++++++++---- crates/ui-egui/src/print.rs | 27 ++++++++++++++++--- docs/mcp.md | 4 ++- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index d23195588d..5fa9535648 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -130,7 +130,13 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(cups_server().as_deref(), printer) else { return papers }; + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. + let server = cups_server().or_else(|| { + let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) + }); + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index fb122e1c67..bb5bb040a5 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -692,11 +692,34 @@ fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() { #[test] fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() { use crate::print::ipp_queue_uri; - assert_eq!(ipp_queue_uri(None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); - assert_eq!(ipp_queue_uri(Some(" "), "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), "Lab"), None, "a domain socket has no URI"); - assert_eq!(ipp_queue_uri(None, ""), None); + assert_eq!(ipp_queue_uri(None, None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); + assert_eq!(ipp_queue_uri(Some(" "), None, "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), None, "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), None, "Lab"), None, "a domain socket has no URI"); + assert_eq!(ipp_queue_uri(None, None, ""), None); +} + +#[test] +fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() { + use crate::print::{ipp_port, ipp_queue_uri}; + assert_eq!(ipp_queue_uri(Some("print.example.com"), Some(8631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab")); + assert_eq!( + ipp_queue_uri(None, Some(8631), "Lab").as_deref(), + Some("ipp://localhost/printers/Lab"), + "with no server named, CUPS uses its domain socket, not IPP_PORT" + ); + assert_eq!( + ipp_queue_uri(Some("print.example.com:631"), Some(8631), "Lab").as_deref(), + Some("ipp://print.example.com:631/printers/Lab"), + "a port in the server name wins" + ); + assert_eq!(ipp_queue_uri(Some("[::1]"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("[::1]:632"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:632/printers/Lab")); + assert_eq!(ipp_port(Some("8631")), Some(8631)); + for invalid in [None, Some(""), Some("0"), Some("70000"), Some("ipp")] { + assert_eq!(ipp_port(invalid), None, "{invalid:?}"); + } + assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab")); } /// What the paper-keyword service was asked to print on: each job's paper. diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 919b834d18..1f1cf1981f 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -191,9 +191,14 @@ pub fn lpoptions_papers(out: &str) -> Vec { /// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`, /// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path), -/// which `ipptool` can't reach by URI. The queue name is percent-encoded. -pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { - let server = server.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("localhost"); +/// which `ipptool` can't reach by URI. A server named without a port of its own gets `port` (from [`ipp_port`]) when +/// there is one; a bracketed IPv6 host (`[::1]`) has a port only after its `]`. With no server named, the URI is +/// `localhost` on the IPP default port, for a CUPS that reaches its own scheduler through its domain socket; a caller +/// whose CUPS has no socket names `localhost` to get `port`. The queue name is percent-encoded. +pub fn ipp_queue_uri(server: Option<&str>, port: Option, printer: &str) -> Option { + let named = server.map(str::trim).filter(|s| !s.is_empty()); + let port = if named.is_some() { port } else { None }; + let server = named.unwrap_or("localhost"); if server.starts_with('/') || printer.is_empty() { return None; } @@ -209,7 +214,21 @@ pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { name.push_str(&format!("%{b:02X}")); } } - Some(format!("ipp://{host}/printers/{name}")) + let has_port = match host.strip_prefix('[') { + Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')), + None => host.contains(':'), + }; + let port = match port { + Some(port) if !has_port => format!(":{port}"), + _ => String::new(), + }; + Some(format!("ipp://{host}{port}/printers/{name}")) +} + +/// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset, +/// empty or not a port number from 1 to 65535. +pub fn ipp_port(value: Option<&str>) -> Option { + value.and_then(|v| v.trim().parse::().ok()).filter(|p| *p != 0) } /// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO diff --git a/docs/mcp.md b/docs/mcp.md index 669e8dff94..8d0d9c3dff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13228,7 +13228,9 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes -of its IPP `media-supported` attribute. +of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, +`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From 5937e03543fab939e5744296bea468e8d0c9f216 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 00:17:06 +0530 Subject: [PATCH 350/533] Canvas context menu: common rows show an icon The canvas menu draws its rows through craft-libs' rows_with_icons with a table of 26 commands and icons already in assets/icons: edit, group, smooth and join, bullets and numbers, grid, rulers, lock guides, fit artboard, artboard and export rows. Rows without a fitting glyph stay text only. The icons show in this menu only. Part of #4602. --- crates/ui-egui/src/canvas/context_menu.rs | 60 ++++++++++++++++++++++- docs/ui-parity.md | 1 + 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index bfef665bb8..287a193132 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -1,3 +1,5 @@ +use craft::behavior::IconId; +use craft::menu::Item; use craft::ui::canvas::CanvasSpace; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; @@ -47,7 +49,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .opened_by(opener, Trigger::Manual) .anchor(Anchor::Point(at)) .open(Bind::bound(&mut open)) - .show(ui, |ui, _| craft::menu::context::rows(ui, &nodes)); + .show(ui, |ui, _| craft::menu::context::rows_with_icons(ui, &nodes, canvas_icon)); if shown.output.closed.is_some() || !open { app.ui.context_menu_at = None; app.ui.context_locked = None; @@ -57,6 +59,42 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } } +/// The icon each canvas menu command shows in this menu, so a row can be found by its shape (#4602). A command +/// left out has no glyph that says what it does here, and shows its catalog icon, if any, or none. +const ICONS: &[(&str, &str)] = &[ + ("edit.undo", "undo-2"), + ("edit.redo", "redo-2"), + ("edit.cut", "scissors"), + ("edit.copy", "copy"), + ("edit.paste", "clipboard-paste"), + ("edit.clear", "trash-2"), + ("object.group", "group"), + ("object.ungroup", "ungroup"), + ("object.path.smooth", "dc-smooth"), + ("object.objectsOnPath.attach", "dc-objects-on-path"), + ("path.join", "dc-join"), + ("type.applyBullets", "dc-para-bullets"), + ("type.applyNumbers", "dc-para-numbers"), + ("view.grid", "grid-3x3"), + ("view.rulers", "ruler"), + ("view.guides.lock", "lock"), + ("view.fitArtboard", "maximize-2"), + ("artboard.new", "file-plus"), + ("artboard.duplicate", "copy"), + ("artboard.copy", "copy"), + ("artboard.cut", "scissors"), + ("artboard.delete", "trash-2"), + ("artboard.rearrange", "dc-rearrange"), + ("artboard.setProps", "dc-artboard-options"), + ("file.exportSelection", "share-2"), + ("file.exportForScreens", "share-2"), +]; + +/// The canvas menu's icon for `item`: its command's entry in [`ICONS`]. +fn canvas_icon(item: &Item) -> Option { + ICONS.iter().find(|(id, _)| *id == item.command.id).map(|(_, icon)| IconId::new(icon)) +} + /// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection. fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let p = space.view.to_doc(at); @@ -114,3 +152,23 @@ fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { } at } + +#[cfg(test)] +mod tests { + use craft::behavior::IconId; + use craft::ui::primitives::has_icon; + + use super::ICONS; + + /// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot + /// empty, and a renamed command would quietly lose its icon. + #[test] + fn every_canvas_menu_icon_is_an_icon_of_a_command() { + crate::icons::register(); + for (id, icon) in ICONS { + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} isn't an icon"); + let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id); + assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command"); + } + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2bd6e1ff3..07decd256d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -81,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Canvas context menu: rows for edit, group, path, type, view and artboard commands show a leading icon from the app's icon set, so a row can be found by its shape; rows without a fitting glyph stay text only (#4602); scores and estimates unchanged | | 2026-12-02 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 365 unknown, with marking rules | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | From 74b3d5c5574d16431c62d24e988dc757f67f0a3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:47:29 -0800 Subject: [PATCH 351/533] Type Tools: Make Numbers Sequence rebuilds long text in one pass Make Numbers Sequence (#10448) built each object's new text with one String::replace_range per number and then replaced each number in the style runs with its own edit::replace_range call, so an object holding n numbers took n passes over its text and runs. The new text is now built once, and the style runs are rebuilt in one pass that gives the same runs, glyph choices and paragraphs as the one-at-a-time edits. Adjacent pieces with the same style are joined as they are written, so a style is copied once per change of style. Text with ruby or inline art, a change that adds or removes a paragraph, and a single change still go through the one-at-a-time edits. Tests: an object with 2,000 numbers is numbered in at most 4 passes (2,001 before), and the one-pass runs match the one-at-a-time result for runs that split numbers, glyph choices, empty runs and ruby. --- .../src/cmd/addons/typetools/numbers.rs | 117 ++++++++++++++++-- .../src/cmd/addons/typetools/numbers/tests.rs | 65 +++++++++- 2 files changed, 169 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index c83c306496..4059f1b8e2 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -9,7 +9,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun}; use vectorcraft_geom::Rect; use vectorcraft_render::effects; use vectorcraft_text::edit; @@ -273,6 +273,109 @@ pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect() } +thread_local! { + /// [`text_passes`] of this thread. + static TEXT_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times Make Numbers Sequence has gone over a type object's text or style runs on this +/// thread: once to build the text an object would read, and once for each part of the object it +/// changes, however many numbers the text holds. +#[cfg(test)] +pub(crate) fn text_passes() -> u64 { + TEXT_PASSES.get() +} + +/// Adds one to [`text_passes`]. +fn note_text_pass() { + TEXT_PASSES.set(TEXT_PASSES.get().saturating_add(1)); +} + +/// `text` with `changes` (from the last to the first, as [`edits`] gives them) made. +pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String { + note_text_pass(); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for (a, b, n) in changes.iter().rev() { + out.push_str(text.get(at..*a).unwrap_or_default()); + out.push_str(n); + at = *b; + } + out.push_str(text.get(at..).unwrap_or_default()); + out +} + +/// Makes `changes` (from the last to the first, as [`edits`] gives them) in `t`, with the +/// paragraphs, style runs and ruby that replacing each range by itself with +/// [`edit::replace_range`] would give, in one pass over each. +pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { + let text = t.plain_text(); + let newline = |(a, b, n): &Edit| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n')); + let annotated = !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()); + if changes.len() < 2 || annotated || changes.iter().any(newline) { + // One change (a whole text), one that adds or removes paragraphs, or text with ruby or + // inline art, whose spans each replacement moves or drops in turn. + for (a, b, n) in changes { + note_text_pass(); + t.splice_paras(*a, *b, n); + edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + return; + } + // Changes inside paragraphs leave every paragraph's style where it is: one splice sets the + // paragraph list as each of them would. + if let Some((a, b, n)) = changes.first() { + t.splice_paras(*a, *b, n); + } + replace_runs(&mut t.runs, changes); +} + +/// The runs with each range of `changes` replaced by its number in the style of the range's first +/// character, without a glyph choice, as [`edit::replace_range`] gives it. +fn replace_runs(runs: &mut Vec, changes: &[Edit]) { + note_text_pass(); + let old = std::mem::take(runs); + let mut out: Vec = Vec::with_capacity(old.len() + 2 * changes.len()); + let mut pending = changes.iter().rev().peekable(); + // Where the run starts and where the last replaced range ends. + let (mut off, mut cut) = (0, 0); + for r in old { + let (start, end) = (off, off + r.text.len()); + off = end; + // The run's style without a glyph choice, for pieces that start inside it and numbers. + let plain = CharStyle { glyph_alternate: None, ..r.style.clone() }; + // A piece of the run from `a` to `b`: one that starts inside it has no glyph choice. + let piece = |out: &mut Vec, a: usize, b: usize| { + let style = if a == start { &r.style } else { &plain }; + push(out, r.text.get(a - start..b - start).unwrap_or_default(), style); + }; + let mut pos = start.max(cut).min(end); + while let Some((a, b, n)) = pending.next_if(|(a, _, _)| *a < end) { + if pos < *a { + piece(&mut out, pos, *a); + } + push(&mut out, n, &plain); + cut = *b; + pos = cut.min(end); + } + if pos < end { + piece(&mut out, pos, end); + } + } + edit::normalize(&mut out); + *runs = out; +} + +/// Adds `text` in `style` to the end of `out`, onto the last run when it has the same style, so a +/// style is copied once for each change of style rather than once for each number. +fn push(out: &mut Vec, text: &str, style: &CharStyle) { + match out.last_mut() { + Some(last) if last.inline.is_none() && last.style == *style => last.text.push_str(text), + _ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }), + } +} + pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let o = Options::parse(p)?; @@ -345,11 +448,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { _ => vec![(0, text.len(), number.clone())], }; // The text it would have, to leave out objects that already read so. - let mut after = text.clone(); - for (a, b, n) in &changes { - after.replace_range(*a..*b, n); - } - if after != *text { + if replaced(text, &changes) != *text { plans.push((*id, changes)); } } @@ -367,11 +466,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { s.edit("Make Numbers Sequence", |d, sel| { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; - for (a, b, n) in changes { - t.splice_paras(*a, *b, n); - edit::replace_range(&mut t.runs, *a, *b, n); - t.ruby_after_replace(*a, *b, n.len()); - } + apply(t, changes); refresh_bounds(t); } d.remove_many(&removed)?; diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs index e7d51d47b4..b4dae1c81e 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -2,9 +2,9 @@ //! orders, removed objects, one undo step, and bad params refused without a change. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun}; -use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence}; +use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes}; use crate::Session; fn session() -> Session { @@ -335,3 +335,64 @@ fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { } assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n)); } + +#[test] +fn a_long_text_is_numbered_in_a_few_passes() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"9 ".repeat(2_000)); + let before = text_passes(); + s.execute(C, &json!({"ids": [a.0], "replace": "numbers", "start": 1})).unwrap(); + let passes = text_passes() - before; + assert_eq!(plain(&s, a), "1 ".repeat(2_000)); + assert!(passes <= 4, "2,000 numbers in one object took {passes} passes over its text"); +} + +/// `t` with `changes` made one at a time, as the command made them before it made them in one pass. +fn one_at_a_time(t: &TextObject, changes: &[(usize, usize, String)]) -> TextObject { + let mut t = t.clone(); + for (a, b, n) in changes { + t.splice_paras(*a, *b, n); + vectorcraft_text::edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + t +} + +#[test] +fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() { + let mut s = session(); + let id = text_at(&mut s, 40.0, 100.0, "x"); + let NodeKind::Text(base) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let base = base.clone(); + let style = |size: f64, glyph: Option| { + let mut st = base.first_style(); + st.size = size; + st.glyph_alternate = glyph.map(|ch| serde_json::from_value(json!({"ch": ch.to_string(), "gid": 7, "font": "F"})).unwrap()); + st + }; + let ruby = |start: usize, end: usize| serde_json::from_value(json!({"start": start, "end": end, "text": "r"})).unwrap(); + // Runs that split numbers, start at them and end inside them, with glyph choices and ruby + // over, across and between the numbers. + type Case<'a> = (Vec<(&'a str, f64, Option)>, Vec<(usize, usize)>); + let cases: Vec = vec![ + (vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]), + (vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]), + (vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]), + ]; + for (runs, spans) in cases { + let mut t = base.clone(); + t.runs = runs.iter().map(|(text, size, glyph)| TextRun { text: text.to_string(), style: style(*size, *glyph), inline: None }).collect(); + let text = t.plain_text(); + // Without ruby the runs are rebuilt in one pass; with it each change is made in turn. + for with_ruby in [false, true] { + t.ruby = if with_ruby { spans.iter().map(|(a, b)| ruby(*a, *b)).collect() } else { Vec::new() }; + for number in ["0", "123456", "5", "123"] { + let changes = edits(&text, number_spans(&text), number); + let mut fast = t.clone(); + apply(&mut fast, &changes); + let slow = one_at_a_time(&t, &changes); + assert_eq!((&fast.runs, &fast.ruby, &fast.paras), (&slow.runs, &slow.ruby, &slow.paras), "{text:?} numbered {number}"); + } + } + } +} From 2cf9f5619488729af2a1140227eb0ed46c702ff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:49:08 -0800 Subject: [PATCH 352/533] Scripts: palette events keep their file access, hide and enabled checks - update() takes a waiting palette event only when the run's file access roots reach the same files as the event's, so a handler never runs with less access than its palette was shown with. - A palette event is no longer delivered to a handler after its palette was hidden and shown again, or after a capturing listener disabled or hid the control or a group above it. - A limit that ends a handler update() took restores the run's own actions before the end-of-run refresh. - A palette refresh that fails reports no unhandled rejection. - A refused palette field text no longer replaces text typed after it. - The script.run, script.palette.event and docs texts describe update() delivery, list staleness after item edits, and repeating a click or close dropped with an oversized text. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/file_access.rs | 24 +++++++---- crates/engine/src/script/mod.rs | 6 +++ crates/engine/src/script/palettes.rs | 6 ++- crates/engine/src/tests/script_palettes.rs | 38 ++++++++++++++---- crates/js/src/realm.rs | 11 +++++- crates/js/src/scriptui.rs | 46 +++++++++++++++++----- crates/js/src/scriptui_tests.rs | 45 +++++++++++++++++++++ crates/ui-egui/src/script_palettes.rs | 3 +- docs/mcp.md | 10 ++--- docs/target-app-parity.md | 2 +- 11 files changed, 158 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index de6f6d251f..074417db20 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, unless a run of that engine takes it first with update(), which runs the handler during that run with no report or undo step of its own, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 93ef5ec983..2711938b78 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -290,11 +290,6 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } - /// Whether this scope allows everything the calling thread's scope allows ([`ScopeHandle::covers`]). - pub(crate) fn covers_current(&self) -> bool { - self.covers(&Self::capture()) - } - /// Whether this scope allows everything `other` allows: its roots are none, or each root of /// `other` lies inside one of its roots of the same kind, and its script gate is none or the /// same gate. @@ -304,12 +299,25 @@ impl ScopeHandle { (Some(a), Some(b)) => Arc::ptr_eq(a, b), (Some(_), None) => false, }; - let roots = match (self.roots(), other.roots()) { + gate && self.roots_cover(other) + } + + /// Whether this scope's roots are none, or each root of `other` lies inside one of its roots + /// of the same kind. + fn roots_cover(&self, other: &Self) -> bool { + match (self.roots(), other.roots()) { (None, _) => true, (Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b), (Some(_), None) => false, - }; - gate && roots + } + } + + /// Whether this scope allows everything the calling thread's scope allows + /// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so + /// work run in the calling thread's scope reaches the same files this scope reaches. + pub(crate) fn matches_current(&self) -> bool { + let current = Self::capture(); + self.covers(¤t) && current.roots_cover(self) } /// Whether this scope and `other` allow the same: each covers the other, and reads are exempt diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 4fb5cd8617..1fa34e050d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2988,6 +2988,12 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result Option { - self.waiting.iter().position(|q| q.scope.covers_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) } } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index a522a0468f..fa57cf5fc5 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -389,7 +389,7 @@ fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { } #[test] -fn update_takes_events_whose_roots_grant_all_the_run_s_roots_grant() { +fn update_takes_only_events_whose_roots_grant_what_the_run_s_roots_grant() { let mut s = one_doc(); run_in_app( &mut s, @@ -403,12 +403,20 @@ fn update_takes_events_whose_roots_grant_all_the_run_s_roots_grant() { let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); - for (run_roots, what) in [(same, "the same roots made again"), (narrow, "roots inside the event's roots")] { - assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); - let report = crate::file_access::confine(Some(&run_roots), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); - assert_eq!(report["log"], json!(["clicked", "after"]), "{what}: {report}"); - assert_eq!(s.script_palette_events_waiting(), 0, "{what}"); - } + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&same), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["clicked", "after"]), "the same roots made again: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0); + // A run whose roots lie inside the event's roots would run the handler with less access than + // the event was given: the event waits for a run of its own. + assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + let report = crate::file_access::confine(Some(&narrow), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); + assert_eq!(report["log"], json!(["after"]), "roots inside the event's roots: {report}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::confine(Some(&wide), || { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["clicked"])); + }); let _ = std::fs::remove_dir(inner); } @@ -718,6 +726,22 @@ fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { assert_eq!(objects(&s), before); } +#[test] +fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { + let mut s = one_doc(); + let (id, _) = acts_palette(&mut s, "for (;;) {}"); + run( + &mut s, + "#targetengine acts\nvar played = 'none'; Object.defineProperty(p, 'text', {get: function () { \ + try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } return 'P'; }});", + ) + .unwrap(); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(run(&mut s, "#targetengine acts\nplayed = 'none'; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(played);").unwrap()["log"].clone(); + assert_eq!(log, json!(["own"]), "the refresh after the limit plays the run's own actions, not the palette's"); +} + #[test] fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { let mut s = one_doc(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 19d9a1893b..c19acde433 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -751,8 +751,15 @@ impl Realm { self.rejections = self.interp.unhandled(); Ok(()) } - Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop), - Err(e) => self.outcome(Err(e)).map(drop), + // A refresh that fails reports no rejection, as after any failed run. + Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop) + } + Err(e) => { + self.rejections = (Vec::new(), 0); + self.outcome(Err(e)).map(drop) + } } } diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index ac30d225ca..9bfe267ec2 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -62,9 +62,10 @@ //! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps //! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the //! host's `paletteEvent` (`{palette, event, id, value, element}`, or `null`, with `element` the id -//! of the control), gives it to that palette as a -//! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown -//! palette does the same for that palette, so the host's list of its controls stays in step. +//! of the control), and gives it to that palette as a dialog takes one, without giving +//! `paletteUpdate` any description: the host gets the palettes' controls when the run ends +//! ([`crate::Realm::refresh_script_ui`]). `add()` on a shown palette gives `paletteUpdate` that +//! palette's description, so the host's list of its controls stays in step. //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or //! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving @@ -134,6 +135,9 @@ const LIST: &str = "__vcList"; const PALETTE_ID: &str = "__vcPaletteId"; const SHOWN: &str = "__vcShown"; const IN_CLOSE: &str = "__vcInClose"; +/// How many times a palette was hidden: an event it took before a hide is not its event after a +/// later `show()`. +const HIDES: &str = "__vcHides"; /// How many times a list's items were added or removed: a palette's waiting change of the list is /// for the items it had then. const REVISION: &str = "__vcRevision"; @@ -1263,15 +1267,33 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult /// always takes it. type Taker = Option<(ObjId, ObjId, ObjId)>; -/// Does the palette of `taker` still take its event and hold its control? Always true for a -/// dialog. +/// Does the palette of `taker` still take its event and hold its control, with the control and +/// every container above it enabled and visible as they are now, read without running a getter +/// ([`plain_state`])? Always true for a dialog. fn takes(i: &mut Interp, taker: Taker) -> JsResult { match taker { - Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)?), + Some((win, ev, c)) => Ok(still_takes(i, win, ev, None)? && holds(i, win, c)? && live_up(i, win, c)?), None => Ok(true), } } +/// Whether `c` and each container above it, up to and including `top`, are enabled and visible, +/// read without running a getter ([`plain_state`]). +fn live_up(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH + 1 { + if !plain_state(i, at, "enabled")? || !plain_state(i, at, "visible")? { + return Ok(false); + } + if at == top { + return Ok(true); + } + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + at = p; + } + Ok(false) +} + /// [`dispatch`] for the event a palette takes (`taker`): no handler or listener runs once a getter, /// a handler or a listener of the event closed the palette or took the event's control out of it. /// → `None` when that happened. @@ -1636,6 +1658,8 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; set_slot(i, o, SHOWN, Value::Bool(false))?; + let hides = number_slot(i, o, HIDES)? + 1.0; + set_slot(i, o, HIDES, Value::Number(hides))?; i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) @@ -1892,6 +1916,9 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult { } } let Some(win) = win else { return Ok(Value::Undefined) }; + // A hide from here on, even one a later show() follows, ends the palette's hold on the event. + let hides = number_slot(i, win, HIDES)?; + set_slot(i, ev, HIDES, Value::Number(hides))?; let event = match slot(i, ev, "event")? { Value::String(s) => s.to_rust_string(), _ => String::new(), @@ -2022,13 +2049,14 @@ fn holds_value(i: &mut Interp, win: ObjId, held: &[Value], at: usize) -> JsResul } /// Whether the window `win` still takes the event `ev`: a dialog (`keep` is `Some`) always does, -/// and a palette only while the host shows it under the id the event names. A getter or a handler -/// run for the event may have closed or hidden the palette. +/// and a palette only while the host shows it under the id the event names and it has not been +/// hidden since it took the event. A getter or a handler run for the event may have closed or +/// hidden the palette, and shown it again. fn still_takes(i: &mut Interp, win: ObjId, ev: ObjId, keep: Option<&[Value]>) -> JsResult { if keep.is_some() { return Ok(true); } - if !slot(i, win, SHOWN)?.truthy() { + if !slot(i, win, SHOWN)?.truthy() || number_slot(i, ev, HIDES)? != number_slot(i, win, HIDES)? { return Ok(false); } let id = slot(i, ev, "palette")?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7917d0241b..57e1917331 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1223,6 +1223,51 @@ fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() { assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run"); } +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run( + "var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!( + r.run("[heard, clicks, p.visible].join()").unwrap(), + JsValue::String("1,0,true".into()), + "a click the palette took before a hide is not its click after the palette shows again" + ); +} + +#[test] +fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]); + r.run( + "var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \ + g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \ + b.onClick = function () { clicks++; }; p.show();", + ) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click"); +} + +#[test] +fn a_palette_refresh_that_fails_reports_no_rejection() { + let (mut r, _) = palette_realm(Vec::new()); + r.add_es2015(); + r.run( + "var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \ + p.show(); Promise.reject(new Error('early')); armed = true;", + ) + .unwrap(); + assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled"); + assert!(r.refresh_script_ui().is_err()); + assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection"); +} + #[test] fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2cc1d81340..e35d277600 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -405,8 +405,9 @@ fn give( } Err(error) => { if let Some((i, text)) = change { + // A text typed after the refused one stays in the field. if let Some((n, text)) = p.dialog.nodes.get(i).zip(text) { - drafts.insert(n.id, text); + drafts.entry(n.id).or_insert(text); } *change_refused = true; } diff --git a/docs/mcp.md b/docs/mcp.md index 48e9c79a03..adbf8851f0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4135,8 +4135,8 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - `update()` takes eligible events oldest first. Events whose recorded file access scopes do not cover the run's - scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within + `update()` takes eligible events oldest first. Events whose recorded file access scopes do not reach the same + files as the run's scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within one scope keep their order. A desktop event keeps the scope in force when the widget records it, even if the app hands it to the engine under different automation roots. Each deferred event runs in its recorded scope within the scope in force when its run starts. Each one is checked against the palette as the script and the @@ -4174,9 +4174,9 @@ the same controls, handlers and limits: or `visible` state a getter gives is shown disabled or hidden, and its events are dropped. A list's change is dropped, with no error and no handler run, when a script added or removed the list's items after the person chose and before the app put the change in line. Once the change waits in line, it ends its run with an error when a script added or removed the list's - items, even if the list again holds the same texts, and when an item's text comes from a getter rather than a - plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and a click or close waits - until it is fixed. An error in a handler that ends its run fails that run like any failed run, puts the + items or changed an item's text, even if the list again holds the same texts, and when an item's text comes from a getter rather than a + plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and the click or close + given with it is dropped: correct the text, then click or close again. An error in a handler that ends its run fails that run like any failed run, puts the documents back, and leaves the palette open. A handler that a palette's `update()` runs throws its error from that `update()` call: when the script catches it, the run goes on and keeps the handler's changes. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fa5c7d28f6..939fa66612 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1178,7 +1178,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_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`. - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes cover the run's scope, so a Cancel button can stop a loop; an event given under narrower roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`. + - Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.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`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). From a0b0702a0598eb3ec800b214f88d488cecea90f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:00:39 -0800 Subject: [PATCH 353/533] Type Tools: Make Numbers Sequence keeps adjacent glyph choices in one-pass runs Pieces are joined only when edit::normalize would join them, so a second character with the same glyph alternate keeps it. The plain text is built only when the one-pass path is still possible. --- crates/engine/src/cmd/addons/typetools/numbers.rs | 10 +++++----- .../engine/src/cmd/addons/typetools/numbers/tests.rs | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index 4059f1b8e2..2db74afbfb 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -309,10 +309,10 @@ pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String { /// paragraphs, style runs and ruby that replacing each range by itself with /// [`edit::replace_range`] would give, in one pass over each. pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { - let text = t.plain_text(); - let newline = |(a, b, n): &Edit| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n')); - let annotated = !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()); - if changes.len() < 2 || annotated || changes.iter().any(newline) { + if changes.len() < 2 || !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()) || { + let text = t.plain_text(); + changes.iter().any(|(a, b, n)| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n'))) + } { // One change (a whole text), one that adds or removes paragraphs, or text with ruby or // inline art, whose spans each replacement moves or drops in turn. for (a, b, n) in changes { @@ -371,7 +371,7 @@ fn replace_runs(runs: &mut Vec, changes: &[Edit]) { /// style is copied once for each change of style rather than once for each number. fn push(out: &mut Vec, text: &str, style: &CharStyle) { match out.last_mut() { - Some(last) if last.inline.is_none() && last.style == *style => last.text.push_str(text), + Some(last) if last.style == *style && last.inline.is_none() && style.glyph_alternate.is_none() => last.text.push_str(text), _ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }), } } diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs index b4dae1c81e..862cffa28c 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -378,6 +378,7 @@ fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() { (vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]), (vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]), (vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]), + (vec![("a", 10.0, Some('a')), ("a", 10.0, Some('a')), (" 12 34", 10.0, None)], vec![(3, 5), (6, 8)]), ]; for (runs, spans) in cases { let mut t = base.clone(); From 2e1b575fdca0d620c1d9a379e3b855236a16ec3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:09:12 -0800 Subject: [PATCH 354/533] xtask: test-lint census rule reads loop labels, radix bounds and closure names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to #10585. The census rule now: - treats a labeled `for` (`'inner: for _ in 0..0`) like an unlabeled one when deciding whether its body runs; - reads hex, octal and binary range bounds (`0x0..0x1`) and borrowed or parenthesized array literals (`&[1]`, `(&[1])`) as loop sources; - does not count a path call (`other::run()`) as a call to a local closure; - counts an async closure's future as run by `block_on` only when it is the whole argument of `block_on` itself, not of `discard_block_on` or of a longer expression, and allows a space before the parenthesis; - finds the `let` keyword without splitting a name such as `inlet_fn`; - accepts a trailing comma after a closure stored in `Some(…)`. --- xtask/src/test_lint.rs | 103 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 12 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e517292e73..1c69802987 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2442,17 +2442,32 @@ fn numeric_literal(s: &str) -> bool { matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") } -/// The value of a decimal integer literal such as `3`, `-4`, `1_000` or `2u8`. +/// The value of an integer literal such as `3`, `-4`, `1_000`, `2u8` or `0x1F`. fn integer_literal(s: &str) -> Option { let (sign, digits) = s.strip_prefix('-').map_or((1, s), |rest| (-1, rest)); + let (radix, unprefixed) = [("0x", 16), ("0o", 8), ("0b", 2)] + .iter() + .find_map(|&(prefix, radix)| digits.strip_prefix(prefix).map(|rest| (radix, rest))) + .unwrap_or((10, digits)); let body = ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"] .iter() - .find_map(|suffix| digits.strip_suffix(suffix)) - .unwrap_or(digits); - if !numeric_literal(digits) || !body.bytes().all(|c| c.is_ascii_digit() || c == b'_') { + .find_map(|suffix| unprefixed.strip_suffix(suffix)) + .unwrap_or(unprefixed); + if !numeric_literal(digits) || body.is_empty() || !body.chars().all(|c| c.is_digit(radix) || c == '_') { return None; } - body.replace('_', "").parse::().ok().map(|n| sign * n) + i128::from_str_radix(&body.replace('_', ""), radix).ok().map(|n| sign * n) +} + +/// The text after the last `let` keyword in `head` that a binding follows (`let x`, not the `let` +/// inside a name such as `inlet_fn`). +fn after_let(head: &str) -> Option<&str> { + let b = head.as_bytes(); + head.match_indices("let") + .map(|(at, _)| at) + .filter(|&at| (at == 0 || !is_ident(b[at - 1])) && b.get(at + 3).is_some_and(u8::is_ascii_whitespace)) + .last() + .map(|at| &head[at + 3..]) } /// Whether the source of the `for … in ` head `head` yields at least one item, for an @@ -2461,8 +2476,15 @@ fn integer_literal(s: &str) -> Option { fn literal_source_yields(head: &[u8]) -> Option { let &kw = words(head, b"in", 3, head.len()).first()?; let mut source: String = String::from_utf8_lossy(&head[kw + 2..]).chars().filter(|c| !c.is_whitespace()).collect(); - while source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { - source = source[1..source.len() - 1].to_owned(); + // A borrowed array literal (`&[a, b]`, `&mut [x; 0]`) yields as many items as the array. + loop { + if let Some(rest) = source.strip_prefix('&') { + source = rest.strip_prefix("mut").filter(|r| r.starts_with(['[', '('])).unwrap_or(rest).to_owned(); + } else if source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + source = source[1..source.len() - 1].to_owned(); + } else { + break; + } } if source.starts_with('[') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { let items = &source[1..source.len() - 1]; @@ -2556,6 +2578,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); + // A loop label (`'outer: for …`) comes before the keyword. + let prefix = prefix + .strip_prefix(b"'") + .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c)).count())) + .and_then(|(label, rest)| rest.strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) + .map_or(prefix, <[u8]>::trim_ascii_start); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { @@ -2759,7 +2787,9 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as .into_iter() .filter(|&at| { let open = skip_ws(b, at + name.len()); - if b[..at].trim_ascii_end().last() == Some(&b'.') || b.get(open) != Some(&b'(') { + // A method (`other.run()`) or a path (`other::run()`) names something else. + let before = b[..at].trim_ascii_end(); + if before.last() == Some(&b'.') || before.ends_with(b"::") || b.get(open) != Some(&b'(') { return false; } if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { @@ -2771,7 +2801,14 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as let Some(close) = matching(b, open) else { return false }; let next = skip_ws(b, close + 1); let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); - awaited || b[..at].trim_ascii_end().ends_with(b"block_on(") + // The future is the whole argument of `block_on` itself, not of a name that ends with it + // (`discard_block_on`), and not part of a longer expression that may never poll it. + let paren = b[..at].trim_ascii_end().len().checked_sub(1).filter(|&p| b[p] == b'('); + let blocked = paren.is_some_and(|p| { + b[..p].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, p).is_some_and(|c| matches!(b[close + 1..c].trim_ascii(), b"" | b",")) + }); + awaited || blocked }) .collect() } @@ -2869,7 +2906,7 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); let close = matching(b, i).unwrap_or(to); - let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let binding = head.strip_suffix('=').and_then(after_let); let stored = binding.is_none() && stored_closure(b, head, close, to); let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); @@ -2899,8 +2936,10 @@ fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { let last = segments.next().unwrap_or_default(); let owner = segments.next().unwrap_or_default(); let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); - let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; - let paren = skip_ws(b, close + 1); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(after_let) else { return false }; + // A trailing comma may follow the closure (`Some(|| { … },)`). + let after = skip_ws(b, close + 1); + let paren = if b.get(after) == Some(&b',') { skip_ws(b, after + 1) } else { after }; let semi = skip_ws(b, paren + 1); constructor && binding.starts_with(char::is_whitespace) @@ -10311,6 +10350,46 @@ mod tests { ); } + #[test] + fn census_reads_labels_radixes_paths_and_let_names() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("for _ in 0x0..0x1 { app.run(c); } assert!(menu(c).is_some());"), [], "a hex range with one item runs its body"); + assert_eq!( + census("'inner: for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled empty loop does not run its body" + ); + assert_eq!( + census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a path call does not call the local closure" + ); + assert_eq!( + census("let run = async || app.run(c); discard_block_on(run()); assert!(menu(c).is_some());"), + [(2, "census")], + "a callee that only ends in block_on does not run the future" + ); + assert_eq!( + census("let run = async || app.run(c); block_on (run()); assert!(menu(c).is_some());"), + [], + "block_on with a space before its parenthesis runs the future" + ); + assert_eq!(census("for _ in &[1] { app.run(c); } assert!(menu(c).is_some());"), [], "a borrowed array literal with one item runs its body"); + assert_eq!(census("'inner: for _ in (&[1]) { app.run(c); } assert!(menu(c).is_some());"), [], "a parenthesized borrowed array runs its body"); + assert_eq!( + census("let run = async || app.run(c); block_on(run().into_stream().take(0).count()); assert!(menu(c).is_some());"), + [(2, "census")], + "a future that is only part of block_on's argument may never be polled" + ); + assert_eq!(census("let inlet_fn =|| { app.run(c); }; inlet_fn(); assert!(menu(c).is_some());"), [], "a closure name that contains let"); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); },); app.run(input); assert!(menu(c).is_some());"), + [], + "a stored closure with a trailing comma never runs" + ); + } + #[test] fn census_needs_evidence_that_the_call_runs_on_the_entry() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From 18445cbda357c46db25c07b83ea0585f37fbba0a Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 00:50:24 +0530 Subject: [PATCH 355/533] Keep SVG event menus with their artwork selection --- .../ui-egui/src/panels/svg_interactivity.rs | 50 ++++++++++++++----- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/panels/svg_interactivity.rs b/crates/ui-egui/src/panels/svg_interactivity.rs index 58fadc85a6..781cedc46e 100644 --- a/crates/ui-egui/src/panels/svg_interactivity.rs +++ b/crates/ui-egui/src/panels/svg_interactivity.rs @@ -61,8 +61,8 @@ pub(crate) struct Info { script_target: Option, } -/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selection size and ends. -pub(crate) type SelKey = ((u64, u64), u64, usize, Option, Option); +/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selected objects. +pub(crate) type SelKey = ((u64, u64), u64, Vec); /// A side label's text without its colon: the label draws the colon itself /// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here. @@ -71,16 +71,11 @@ pub(crate) fn caption(label: &'static str) -> &'static str { crate::i18n::t(label).trim_end_matches(':') } -fn sel_key(app: &VectorcraftApp) -> Option { - let st = app.session.active()?; - let sel = &st.selection.objects; - Some(((st.uid, st.reverts), st.revision, sel.len(), sel.first().copied(), sel.last().copied())) -} - /// The memoized [`Info`] when it was read for the current document and selection. fn cached(app: &VectorcraftApp) -> Option<&Info> { - let key = sel_key(app)?; - app.canvas.svg_info.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v) + let st = app.session.active()?; + let (((uid, reverts), revision, selection), info) = app.canvas.svg_info.as_ref()?; + (*uid == st.uid && *reverts == st.reverts && *revision == st.revision && selection == &st.selection.objects).then_some(info) } /// `svgInteractivity.info`, read again only when the document or the selection changes. @@ -88,7 +83,8 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info { if let Some(v) = cached(app) { return v.clone(); } - let Some(key) = sel_key(app) else { return Info::default() }; + let Some(st) = app.session.active() else { return Info::default() }; + let key = ((st.uid, st.reverts), st.revision, st.selection.objects.clone()); let r = app.session.execute("svgInteractivity.info", &json!({})).unwrap_or_default(); let events = r["events"] .as_array() @@ -168,8 +164,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } let selection = if listed { Selection::single(event.to_string()) } else { Default::default() }; let mut list = List::::new(tl!("Events")) - // Each document gets its own list, so a row menu left open closes with the old one. - .id(ui.scope_id().with(("svg-events", document))) + // Keep each row menu with the drawing and artwork it was opened for. + .id(ui.scope_id().with(("svg-events", document, info.script_target))) .select(SelectMode::Single) .arrows_select(true) .deletable(true) @@ -606,6 +602,34 @@ mod tests { assert!(panel.shows("onclick: 1;")); } + #[test] + fn row_menu_closes_when_artwork_selection_changes_in_the_same_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let ids = [0, 20, 40, 60].map(|x| run(&mut app, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].clone()); + run(&mut app, "svgInteractivity.setEvent", json!({"ids": ids, "event": "onclick", "script": "1;"})); + let first = json!({"ids": [ids[0], ids[1], ids[3]]}); + let second = json!({"ids": [ids[0], ids[2], ids[3]]}); + run(&mut app, "select.set", first.clone()); + let mut panel = Panel::new(app, show); + let item = tl!("Remove Event"); + let role = craft::ui::contract::Role::MENU_ITEM; + panel.secondary_click("onclick: 1;"); + assert!(panel.menu_item_enabled(item)); + + // Only the middle object changes, and both selections display the exact same row. + run(&mut panel.app(), "select.set", second); + panel.frame(); + assert!(panel.shows("onclick: 1;")); + assert!(!panel.shows_role(item, role)); + + run(&mut panel.app(), "select.set", first); + panel.frame(); + assert!(!panel.shows_role(item, role), "the old menu stays closed on return"); + panel.secondary_click("onclick: 1;"); + assert!(panel.menu_item_enabled(item), "the row can open a fresh menu"); + } + #[test] fn row_menu_closes_when_its_row_disappears_or_the_document_changes() { let mut panel = two_events(); From 4cf6c81e8b697ca03ca0006ca012314fc7e5bc85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:35:22 -0800 Subject: [PATCH 356/533] Scripts: a buffered palette click gives only the texts typed before it A click or close that waited in the palette's line gave the script every text typed in the palette by the time the app took it, including text typed after the click. Each batch of events now keeps the typed texts and their typing scopes as they were in its pass, and the click or close commits only those. A text typed later stays in its field. A text that batch commits keeps the scope it was typed in, a refused text keeps the clicks and closes of later batches out of line, a focus-loss change carrying a text the frame already gave is not given again, and a text the click took without a change leaves its field. --- crates/ui-egui/src/script_palettes.rs | 57 ++++++++++++++++++--- crates/ui-egui/src/tests/script_palettes.rs | 30 +++++++++++ 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index e35d277600..b07deea333 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -34,6 +34,10 @@ pub(crate) fn palette_id(id: u64) -> DialogId { dialog_id((KIND, id)) } +/// One batch of given events: its pass's scope, its own scope, the events, and the typed texts as +/// they were in its pass, each with its typing scope. +type Given = (ScopeHandle, ScopeHandle, Vec, BTreeMap); + /// A shown palette on the window's dialog host. pub(crate) struct PaletteWindow { /// The palette as the session has it, from the last frame. @@ -44,8 +48,9 @@ pub(crate) struct PaletteWindow { draft_scopes: BTreeMap, /// The events the person gave since the app last took them, each with its control by its id, /// and a list's change with the items the person saw, so a run that changes the palette before - /// the app takes them leaves each with its own control. - given: Vec<(ScopeHandle, ScopeHandle, Vec)>, + /// the app takes them leaves each with its own control. Each batch also keeps the typed texts as + /// they were in its pass, so a click or close gives only the texts typed before it. + given: Vec, /// The text each edit field gave the script, by the field's id, while its change waits: the /// field shows it until no change of that field waits, even while the palette's field holds the /// same text, since a run before the change may set the field to another one. @@ -187,7 +192,9 @@ impl PaletteWindow { _ => batches.push((scope, vec![q])), } } - self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events))); + let seen: BTreeMap = + self.drafts.iter().filter_map(|(id, text)| self.draft_scopes.get(id).map(|s| (*id, (text.clone(), s.clone())))).collect(); + self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events, seen.clone()))); } } @@ -292,9 +299,39 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Texts whose change went in line, typed ones a click or close gave included: the field // shows each until its change no longer waits. let mut accepted = BTreeMap::new(); - for (pass_scope, scope, given) in given { + for (pass_scope, scope, given, seen) in given { let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); - for (event_scope, event) in drafted(app, &p.dialog, &mut drafts, &mut events, &scope, &pass_scope, &draft_scopes) { + // Only the texts typed by this batch's pass are given with its click or close; a text + // typed in a later pass stays in its field. A text this frame already gave is not given + // again. + let seen: BTreeMap = + seen.into_iter().filter(|(field, (text, _))| accepted.get(field) != Some(text)).collect(); + let mut at_pass: BTreeMap = seen.iter().map(|(field, (text, _))| (*field, text.clone())).collect(); + // Each text keeps the scope it had when it was typed, even when a later pass gave it. + let at_scopes: BTreeMap = seen.into_iter().map(|(field, (_, s))| (field, s)).collect(); + script_window::keep_fields(&p.dialog, &mut at_pass); + // A field's change carrying a text this frame already gave is not given a second time. + events.retain(|e| match e { + UiEvent::Change(i, UiValue::Text(text)) => p.dialog.nodes.get(*i).is_none_or(|n| accepted.get(&n.id) != Some(text)), + _ => true, + }); + let before = at_pass.clone(); + let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); + // A refused text keeps every later click and close out of line too. + change_refused |= refused; + // A text the click or close took leaves its field unless a later one was typed there. + for (field, text) in &before { + if !at_pass.contains_key(field) && drafts.get(field) == Some(text) { + drafts.remove(field); + } + } + // A text refused in this batch goes back in its field unless a later one was typed there. + for (field, text) in at_pass { + if before.get(&field) != Some(&text) { + drafts.entry(field).or_insert(text); + } + } + for (event_scope, event) in batch { event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused, &mut accepted)); } // A text that went back in its field without a scope of its own takes this one. @@ -317,7 +354,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// Commits drafts in dialog order, each under its typing and committing scopes. Every draft is -/// validated before any is removed. A refused draft keeps the click or close out of line. +/// validated before any is removed. A refused draft keeps the click or close out of line. → the +/// events with their scopes, and whether a text was refused. fn drafted( app: &mut VectorcraftApp, w: &ScriptUiDialog, @@ -326,9 +364,11 @@ fn drafted( scope: &ScopeHandle, pass_scope: &ScopeHandle, draft_scopes: &BTreeMap, -) -> Vec<(ScopeHandle, UiEvent)> { +) -> (Vec<(ScopeHandle, UiEvent)>, bool) { + let mut refused = false; if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); + refused = true; } let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); let mut changes = Vec::new(); @@ -343,6 +383,7 @@ fn drafted( changes.clear(); events.retain(|e| !closing(e)); app.status(e); + refused = true; } } } @@ -364,7 +405,7 @@ fn drafted( let mut given: Vec<_> = events.drain(..at).map(|e| (scope.clone(), e)).collect(); given.extend(changes); given.extend(events.drain(..).map(|e| (closing_scope.clone(), e))); - given + (given, refused) } /// Puts the events the person gave the palette `p` in line, or shows why one was refused. A diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 4b72675b2e..ef816ce39e 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -455,6 +455,36 @@ fn buffered_passes_keep_a_click_or_close_before_a_later_text_commit() { } } +#[test] +fn a_buffered_click_or_close_does_not_give_a_text_typed_after_it() { + for closing in [UiEvent::Click(2), UiEvent::Close] { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine later\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed ' + t.text); }; \ + go.onClick = function () { vc.log('clicked ' + t.text); }; \ + p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();", + ); + let first = if matches!(closing, UiEvent::Close) { "closed" } else { "clicked" }; + with_palette(&app, id, |w| { + w.type_text(1, "early"); + w.pass(&[], vec![closing]); + w.type_text(1, "later"); + }) + .unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2); + for expected in ["changed early".to_string(), format!("{first} early")] { + script_runs::poll(&mut app); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([expected])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap().as_deref(), Some("later")); + } +} + #[test] fn a_click_or_close_commits_drafts_in_dialog_order_across_scopes() { use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; From 540d7d9673f08aede73a2327ee098880c78a7b50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:44:52 -0800 Subject: [PATCH 357/533] PDF/EPS/.ai import: store imported images with fast PNG compression Opening a PDF, EPS or .ai file with images re-encodes each image, and each image's opacity mask, as a PNG. Since the switch to the shared image codec these PNGs were written with the codec's default compression (deflate level 6) instead of fast compression. A PDF and an .ai file each holding one image opened about 50 ms and 105 ms slower than in 0.24.1. PDF import and the EPS and .ai readers now each encode through one helper that asks for PngCompression::Fast, the setting the SVG filter raster already uses. The pixels are unchanged. Tests check the zlib header of every PNG an import stores (RFC 1950 FLEVEL): PDF RGB, gray and image-mask images and a CMYK image's soft mask; a PostScript RGB image and a masked CMYK image's mask; and .ai RGB and Separation images with their masks, at full size and reduced. --- crates/eps/src/import.rs | 6 +++ crates/eps/src/import/ai/read/art.rs | 10 ++--- crates/eps/src/import/ai/tests.rs | 29 ++++++++++++++ crates/eps/src/import/data/ops.rs | 4 +- crates/eps/src/import/preview.rs | 2 +- crates/eps/src/import/tests.rs | 13 +++++++ crates/eps/src/import/tests_images.rs | 20 +++++++++- crates/pdf/src/import/builder.rs | 2 +- crates/pdf/src/import/state.rs | 12 ++++-- crates/pdf/src/tests/import_fidelity.rs | 52 ++++++++++++++++++++++++- 10 files changed, 136 insertions(+), 14 deletions(-) diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 6c85414463..db310e0f01 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -135,6 +135,12 @@ pub struct Imported { pub preview: bool, } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(crate) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + /// The DSC comments the reader uses. #[derive(Debug, Default, PartialEq)] struct Dsc { diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 95606c9ebb..e0a46fccb0 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -648,7 +648,7 @@ impl<'a> Reader<'a> { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&img) else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); }; @@ -678,7 +678,7 @@ impl<'a> Reader<'a> { } let written = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()); + .and_then(|img| crate::import::png(&img)); let Some(png) = written else { self.image_left_out("an image VectorCraft can't read was left out"); return Ok(()); @@ -778,7 +778,7 @@ impl<'a> Reader<'a> { }; craft_image_codecs::Image::from_raw(ow, oh, layout, craft_image_codecs::SampleType::U8, pixels) .ok() - .and_then(|img| craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()) + .and_then(|img| crate::import::png(&img)) .map(|png| ImageBlob::new("image/png", png)) }; // One that can't be encoded is left to the page's art, as one past the hard limits. @@ -870,7 +870,7 @@ impl<'a> Reader<'a> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.doc.images.entry(key.clone()).or_insert(blob); @@ -1224,7 +1224,7 @@ pub(super) fn preview_png(data: &[u8]) -> Option<(Vec, u32, u32)> { } let raw = craft_image_codecs::Image::from_raw(width, height, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; Some((png, width, height)) } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9ef4cbc840..fe425346d2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -3154,6 +3154,35 @@ fn a_reduced_separation_image_keeps_its_ink_and_its_alpha_as_a_mask() { assert!(r.doc.images[&im.key].gray_source().is_some_and(|g| !g.alpha), "no alpha in the pixels"); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with an alpha channel, and a Separation image with its opacity +/// mask, at full size and reduced to fit the limits. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let pngs = |doc: &Document| { + let fast = |n: &Node| { + let NodeKind::Image(im) = &n.kind else { panic!("{:?}", n.kind) }; + let blob = &doc.images[&im.key]; + assert_eq!(blob.mime, "image/png"); + crate::import::tests::fastest_png(&blob.bytes) + }; + let a = art(doc); + let mut out = vec![fast(&a[0])]; + out.extend(a[0].extras().mask.as_ref().map(|m| fast(&m.art))); + out + }; + let rgb = image("[ 10 0 0 10 50 90 ]", (2, 1), ("DeviceRGB", 3, 1), &[255, 0, 0, 0, 255, 0, 255, 128], 10); + assert_eq!(pngs(&read(&rgb).unwrap().doc), [true], "the RGB image"); + let black = "1 [0 0 0 1 /DeviceCMYK (Black Ink) /Separation]"; + let ink = ink_image(black, 8, 1, 2, &[0, 255, 255, 64]); + assert_eq!(pngs(&read(&ink).unwrap().doc), [true, true], "the Separation image and its mask"); + let samples = [255u8; 16].iter().chain([0u8; 16].iter()).copied().collect::>(); + let ink = ink_image(black, 8, 1, 16, &samples); + let r = super::with_image_limits(4, 1 << 31, 512 << 20, || read(&ink).unwrap()); + assert!(r.warnings.iter().any(|w| w.contains("was reduced")), "{:?}", r.warnings); + assert_eq!(pngs(&r.doc), [true, true], "the reduced Separation image and its mask"); +} + #[test] fn images_with_alpha_channels() { // RGB samples, then the alpha channel (not counted in the data's size). diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index e9bf596eb3..c27dc3c3c6 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -1157,7 +1157,7 @@ impl Interp<'_> { else { return Ok(()); }; - let Ok(png) = craft_image_codecs::encode(&rgba, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + let Some(png) = crate::import::png(&rgba) else { self.out.warn("an image that couldn't be read was left out"); return Ok(()); }; @@ -1184,7 +1184,7 @@ impl Interp<'_> { let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, alpha.to_vec()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = crate::import::png(&raw)?; let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); self.out.doc.images.entry(key.clone()).or_insert(blob); diff --git a/crates/eps/src/import/preview.rs b/crates/eps/src/import/preview.rs index 36c0e5662c..87037fcd1a 100644 --- a/crates/eps/src/import/preview.rs +++ b/crates/eps/src/import/preview.rs @@ -46,7 +46,7 @@ fn image_doc(img: image::RgbaImage, frame: Rect) -> Option { } let raw = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, img.into_raw()) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::png(&raw)?; let mut doc = Document::new(frame.width(), frame.height()); let blob = ImageBlob::new("image/png", png); let key = blob.content_key(); diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index 011cb86ce3..f920a1c364 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -208,6 +208,19 @@ fn arrays_and_dictionaries_holding_themselves_are_freed() { } } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +pub(super) fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + /// The objects of the document's layer. pub(super) fn objects(d: &Document) -> Vec> { d.layers[0].children().unwrap().clone() diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index e7fd734240..87a7560bfd 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ImageBlob, Node, NodeKind}; use super::import; -use super::tests::{all, eps, read}; +use super::tests::{all, eps, fastest_png, read}; use super::tests_generators::pixel; /// Each pixel of the first image, row by row. @@ -223,6 +223,24 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(first_image(&r).extras().mask.is_none()); } +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image, and the opacity mask of a masked CMYK image. +#[test] +fn images_and_their_masks_are_stored_with_fast_compression() { + let r = read("30 20 scale 3 2 8 [3 0 0 -2 0 2] <00ff00405060> <0000ff708090> true 3 colorimage"); + let b = blob(&r, &first_image(&r)); + assert_eq!(b.mime, "image/png"); + assert!(fastest_png(&b.bytes), "the RGB image"); + let r = read( + "/DeviceCMYK setcolorspace 30 20 scale << /ImageType 4 /Width 2 /Height 1 /BitsPerComponent 8 /Decode [0 1 0 1 0 1 0 1] \ + /ImageMatrix [2 0 0 -1 0 1] /DataSource <0a141e28 00667f08> /MaskColor [10 20 30 40] >> image", + ); + let n = first_image(&r); + let mask = blob(&r, &n.extras().mask.as_ref().expect("an opacity mask").art); + assert_eq!(mask.mime, "image/png"); + assert!(fastest_png(&mask.bytes), "the opacity mask"); +} + /// A CMYK JPEG gives its samples as stored, for the Decode array to read: Adobe's inverted /// samples with `[1 0 1 0 1 0 1 0]`, the ink amounts themselves with `[0 1 0 1 0 1 0 1]`. #[test] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index 0cfb8ea805..64da7fb8d5 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -1098,7 +1098,7 @@ impl<'p> Builder<'p> { a.data, ) .ok()?; - let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?; + let png = super::state::png(&raw)?; let blob = ImageBlob::new("image/png", png); let k = blob.content_key(); self.images.insert(k.clone(), blob); diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 629113680c..c85f36bd7f 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -378,19 +378,25 @@ pub(super) fn bounds(nodes: &[Arc]) -> Option { nodes.iter().try_fold(None, |acc, n| n.visual_bounds().map(|b| Some(acc.map_or(b, |a: Rect| a.union(b)))))? } +/// `img` as a PNG with fast compression, which keeps opening a file with large images quick. +pub(super) fn png(img: &craft_image_codecs::Image) -> Option> { + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + craft_image_codecs::encode(img, craft_image_codecs::Format::Png, &opts).ok() +} + pub(super) fn rgba_png(rgba: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn rgb_png(rgb: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn gray_png(gray: Vec, w: u32, h: u32) -> Option> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; - craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() + png(&img) } pub(super) fn resize_alpha(a: &LumaData, w: u32, h: u32) -> Vec { diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 5fdafeb5fc..731f18ff06 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, Knockout, LineCap, LineJoin, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{Rect, shapes}; use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; @@ -147,6 +147,56 @@ fn a_luminosity_soft_mask_of_an_image_keeps_the_images_colour() { assert_eq!(mask_image_pixels("Luminosity"), [[0, 0, 0, 255], [0, 0, 0, 0]]); } +/// Whether PNG `png` stores its pixels at the fastest level a zlib header names (RFC 1950 §2.2, +/// FLEVEL 0). +fn fastest_png(png: &[u8]) -> bool { + let mut at = 8; + while let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) { + if kind == b"IDAT" { + return png.get(at + 9).is_some_and(|flg| flg >> 6 == 0); + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + } + panic!("a PNG with image data: {png:?}"); +} + +/// Images come in as PNGs written with fast compression, which keeps a file with large images +/// quick to open: an RGB image with a soft mask, the soft mask of a CMYK image as its opacity +/// mask, a gray image and an image mask painted in a color. +#[test] +fn imported_images_are_stored_with_fast_compression() { + let g = first_extra(1); + let image = |space: &str, data: &str| { + stream( + &format!( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /{space} /BitsPerComponent 8 /Filter /ASCIIHexDecode /SMask {} 0 R", + g + 4 + ), + data, + ) + }; + let rgb = image("DeviceRGB", "FF000000FF00>"); + let cmyk = image("DeviceCMYK", "0A141E28 00667F08>"); + let gray = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "2080>"); + let stencil = stream("/Type /XObject /Subtype /Image /Width 8 /Height 1 /ImageMask true /BitsPerComponent 1 /Filter /ASCIIHexDecode", "F0>"); + let smask = + stream("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /ASCIIHexDecode", "FF40>"); + let bytes = one_page( + "q 40 0 0 40 0 0 cm /Im0 Do Q q 40 0 0 40 50 0 cm /Im1 Do Q q 40 0 0 40 0 50 cm /Im2 Do Q 0 0 1 rg q 40 0 0 40 50 50 cm /Im3 Do Q", + &format!("/XObject << /Im0 {g} 0 R /Im1 {} 0 R /Im2 {} 0 R /Im3 {} 0 R >>", g + 1, g + 2, g + 3), + &[&rgb, &cmyk, &gray, &stencil, &smask], + ); + let d = open(&bytes); + let masks = all(&d).iter().filter(|n| n.extras().mask.is_some()).count(); + assert_eq!(masks, 1, "the CMYK image's soft mask as an opacity mask"); + let pngs: Vec<&ImageBlob> = d.images.values().filter(|b| b.mime == "image/png").collect(); + assert_eq!(pngs.len(), 4, "the RGB image, the CMYK image's mask, the gray image and the image mask: {:?}", d.images.keys()); + for b in pngs { + assert!(fastest_png(&b.bytes), "{:?}", &b.bytes[..b.bytes.len().min(48)]); + } +} + #[test] fn a_luminosity_soft_mask_becomes_an_opacity_mask() { let d = open(&masked("/S /Luminosity", "1 1 1 rg 0 0 50 100 re f")); From a65d251c87f33a46b80d3e979981766a9887136a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:52:55 -0800 Subject: [PATCH 358/533] Scripts: DXF scale tests fail on a drawing with no polyline vertices dxf_widest and dxf_leftmost folded from f64::MIN and f64::MAX, so a DXF that kept its header but lost every vertex gave an infinite product and the unitScaleRatio and pica assertions still passed. Both now reduce the coordinates and fail when there are none. docs/mcp.md: a relative save or open path is resolved against the working folder of the process that wrote or read the file. --- crates/engine/src/tests/script_save_open.rs | 4 ++-- docs/mcp.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 7fd60b9f94..b3dd0d2ded 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -423,12 +423,12 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) + dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices") } /// The smallest x coordinate (group code 10) in the entities of a DXF. fn dxf_leftmost(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) + dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices") } /// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its diff --git a/docs/mcp.md b/docs/mcp.md index ca6d350642..8a2928c0a8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3301,7 +3301,7 @@ through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + file. A relative path that a file is saved or opened under is resolved against the working folder of the process that wrote or read it, for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved From 8cea13d8a4474519be0ad2cf181f3d442fa52bd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:57:17 -0800 Subject: [PATCH 359/533] xtask: test-lint census rule reads a loop label with a space before its colon Rust allows whitespace between a loop label and its colon ('inner : for), so the label is stripped from the loop head in that form too. --- xtask/src/test_lint.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1c69802987..423b919d88 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2582,7 +2582,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let prefix = prefix .strip_prefix(b"'") .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c)).count())) - .and_then(|(label, rest)| rest.strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) + .and_then(|(label, rest)| rest.trim_ascii_start().strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) .map_or(prefix, <[u8]>::trim_ascii_start); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { @@ -10360,6 +10360,11 @@ mod tests { [(2, "census")], "a labeled empty loop does not run its body" ); + assert_eq!( + census("'inner : for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a label with a space before its colon" + ); assert_eq!( census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), [(2, "census")], From 22c910080cf1ae68a17c7a5a739444956b7328b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:31:29 -0800 Subject: [PATCH 360/533] Docs: say threaded type is skipped by its whole story in Make Numbers Sequence The parity line now says that an unthreaded object is skipped when it holds no number or placeholder, and that a threaded frame is checked once per thread against its whole story. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e6297ea11a..bfcfcbb6a0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3195,7 +3195,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Make Numbers Sequence (2026-12-01) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, objects that hold none are skipped before the ordering, so they take no number and are never deleted. Locked and hidden type is left alone, a clipping mask is not deleted, and bad parameters are refused. Threaded type is refused unless numbers or placeholder replacement skips the frame because its story holds none. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, an unthreaded object that holds none, and a threaded frame whose whole story holds none, are skipped before the ordering, so they take no number and are never deleted. A threaded frame is checked once per thread, against its whole story. Locked and hidden type is left alone, a clipping mask is not deleted, and bad parameters are refused. Any other threaded type is refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. ## Unit Converter add-on (2026-11-14) From af28b5380cd8666872de165e6b2f261e9da2248c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:51:04 -0800 Subject: [PATCH 361/533] Print: a remote CUPS scheduler supplies its own paper sizes When CUPS_SERVER or client.conf's ServerName names a remote scheduler, the Print dialog no longer reads a same-named PPD under /etc/cups/ppd. The job goes to the remote queue, so the sizes now come from that server through lpoptions and IPP. A domain socket, localhost, 127.0.0.1 and ::1, with an optional port and /version= suffix, still count as local and keep the PPD lookup. --- apps/vectorcraft/src/printing.rs | 67 ++++++++++++++++++++++++++++---- docs/mcp.md | 3 +- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f81ca95306..7bfb550876 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -169,12 +169,17 @@ mod system { if printer.contains(['/', '\\']) || printer.starts_with('.') { return Vec::new(); } - const PPD_CAP: u64 = 16 << 20; - let mut bytes = Vec::new(); - let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; - if !papers.is_empty() { - return papers; + let named = cups_server(); + // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, + // so its sizes come from the server. + if scheduler_is_local(named.as_deref()) { + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; + } } // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. let mut command = Command::new("lpoptions"); @@ -188,7 +193,7 @@ mod system { // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = cups_server().or_else(|| { + let server = named.or_else(|| { let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) }); @@ -242,6 +247,25 @@ mod system { client_conf_server_name(&text) }) } + /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, + /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + #[cfg(not(windows))] + pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + let Some(server) = server.map(str::trim) else { return true }; + if server.starts_with('/') { + return true; + } + // A network name may end in `/version=1.1`. + let server = server.split_once('/').map_or(server, |(server, _)| server); + let host = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or(rest, |(host, _)| host) + } else if server.matches(':').count() == 1 { + server.split_once(':').map_or(server, |(host, _)| host) + } else { + server + }; + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. @@ -557,7 +581,34 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::client_conf_server_name; + use super::system::{client_conf_server_name, scheduler_is_local}; + + #[test] + fn only_a_scheduler_on_this_machine_counts_as_local() { + for local in [ + None, + Some("/run/cups/cups.sock"), + Some("localhost"), + Some("LocalHost:631"), + Some("127.0.0.1:8631"), + Some("::1"), + Some("[::1]:631"), + Some("localhost/version=1.1"), + ] { + assert!(scheduler_is_local(local), "{local:?}"); + } + for remote in [ + "print.example.com", + "print.example.com:631", + "192.0.2.7", + "[2001:db8::1]:631", + "2001:db8::1", + "localhost.example.com", + "print.example.com:631/version=1.1", + ] { + assert!(!scheduler_is_local(Some(remote)), "{remote}"); + } + } #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { diff --git a/docs/mcp.md b/docs/mcp.md index bf0f467ea4..fb72b22769 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13252,7 +13252,8 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or -remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, +`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. From 38f198bb22395544cd105b1e3fed1a17ffc5c28c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:55:32 -0800 Subject: [PATCH 362/533] xtask: test-lint census rule reads let( bindings, non-ASCII labels and grouped block_on futures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A `let` followed directly by `(`, `[` or `&` (`let(_run) = || { ... };`) now binds the closure, and Unicode whitespace after `let` separates the pattern. - A loop label with non-ASCII letters (`'été: for _ in 0..0`) is stripped, so an empty range still skips the body. - `block_on((run()))` counts the future as run: grouping parentheses around it are skipped. A callee whose name only ends in `block_on` (`déblock_on`) still does not count, and Unicode whitespace before `block_on` does not join it to the name before. --- xtask/src/test_lint.rs | 81 +++++++++++++++++++++++++++++++++--------- 1 file changed, 65 insertions(+), 16 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 423b919d88..f05605aabd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2459,17 +2459,31 @@ fn integer_literal(s: &str) -> Option { i128::from_str_radix(&body.replace('_', ""), radix).ok().map(|n| sign * n) } -/// The text after the last `let` keyword in `head` that a binding follows (`let x`, not the `let` -/// inside a name such as `inlet_fn`). +/// The text after the last `let` keyword in `head` that a binding follows (`let x`, `let(x)`, +/// `let[x]`, `let&x`, not the `let` inside a name such as `inlet_fn`). fn after_let(head: &str) -> Option<&str> { let b = head.as_bytes(); head.match_indices("let") .map(|(at, _)| at) - .filter(|&at| (at == 0 || !is_ident(b[at - 1])) && b.get(at + 3).is_some_and(u8::is_ascii_whitespace)) + .filter(|&at| (at == 0 || !is_ident(b[at - 1])) && opens_let_pattern(&head[at + 3..])) .last() .map(|at| &head[at + 3..]) } +/// Whether `rest`, the text right after a `let` keyword, starts its pattern: whitespace, or a +/// tuple, slice or reference pattern written without a space (`let(x)`, `let[x]`, `let&x`). +fn opens_let_pattern(rest: &str) -> bool { + rest.starts_with(|c: char| c.is_whitespace() || matches!(c, '(' | '[' | '&')) +} + +/// Whether `head`, the text before a call's opening parenthesis, ends with the name `block_on` +/// itself, not a longer name that ends with it (`discard_block_on`, `déblock_on`). +fn ends_with_block_on(head: &[u8]) -> bool { + head.trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| { + !String::from_utf8_lossy(h).chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_' || !(c.is_ascii() || c.is_whitespace())) + }) +} + /// Whether the source of the `for … in ` head `head` yields at least one item, for an /// integer range with literal bounds (`0..3` and `0..=0` do, `0..0` and `5..=4` do not) or an array /// literal (`[a, b]` and `[x; 2]` do, `[]` and `[x; 0]` do not). `None` for any other source. @@ -2578,10 +2592,10 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); - // A loop label (`'outer: for …`) comes before the keyword. + // A loop label (`'outer: for …`, `'été: for …`) comes before the keyword. let prefix = prefix .strip_prefix(b"'") - .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c)).count())) + .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count())) .and_then(|(label, rest)| rest.trim_ascii_start().strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) .map_or(prefix, <[u8]>::trim_ascii_start); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); @@ -2655,7 +2669,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); let head = strip_closure_keywords(&head).0.as_bytes(); - if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { + if !head.ends_with(b"=") || !head.starts_with(b"let") || !std::str::from_utf8(&head[3..]).is_ok_and(opens_let_pattern) { return None; } (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) @@ -2725,9 +2739,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) })(); let binding_head = unwrapped.unwrap_or(bare); - let Some(binding) = - binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) - else { + let Some(binding) = binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| opens_let_pattern(h)) else { // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; @@ -2743,7 +2755,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac outer.is_some_and(|o| { b[o] == b'(' && !b[stmt..o].contains(&b'|') - && b[..o].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && ends_with_block_on(&b[..o]) && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) }) }); @@ -2803,11 +2815,22 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); // The future is the whole argument of `block_on` itself, not of a name that ends with it // (`discard_block_on`), and not part of a longer expression that may never poll it. - let paren = b[..at].trim_ascii_end().len().checked_sub(1).filter(|&p| b[p] == b'('); - let blocked = paren.is_some_and(|p| { - b[..p].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) - && matching(b, p).is_some_and(|c| matches!(b[close + 1..c].trim_ascii(), b"" | b",")) - }); + // Grouping parentheses around the future (`block_on((run()))`) are skipped. + let opening = |end: usize| b[..end].trim_ascii_end().len().checked_sub(1).filter(|&p| b[p] == b'('); + let mut paren = opening(at); + let mut inner = close; + let blocked = loop { + let Some((p, c)) = paren.and_then(|p| matching(b, p).map(|c| (p, c))) else { break false }; + let rest = b[inner + 1..c].trim_ascii(); + if ends_with_block_on(&b[..p]) { + break matches!(rest, b"" | b","); + } + if !rest.is_empty() { + break false; + } + paren = opening(p); + inner = c; + }; awaited || blocked }) .collect() @@ -2942,7 +2965,7 @@ fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { let paren = if b.get(after) == Some(&b',') { skip_ws(b, after + 1) } else { after }; let semi = skip_ws(b, paren + 1); constructor - && binding.starts_with(char::is_whitespace) + && opens_let_pattern(binding) && b.get(paren) == Some(&b')') && b.get(semi) == Some(&b';') && pattern_names(binding).all(|n| words(b, n.as_bytes(), semi, to).is_empty()) @@ -10365,6 +10388,32 @@ mod tests { [(2, "census")], "a label with a space before its colon" ); + assert_eq!(census("'été: for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a label with non-ASCII letters"); + assert_eq!( + census("let(_run) = || { app.run(c); }; _run(); assert!(menu(c).is_some());"), + [], + "a let with no space before its pattern binds a closure that is called" + ); + assert_eq!( + census("let run = async || app.run(c); block_on((run())); assert!(menu(c).is_some());"), + [], + "a future in grouping parentheses passed to block_on runs" + ); + assert_eq!( + census("let run = async || app.run(c); déblock_on((run())); discard‿block_on((run())); assert!(menu(c).is_some());"), + [(2, "census")], + "a callee whose non-ASCII name ends in block_on does not run the future" + ); + assert_eq!( + census("let\u{85}run = || app.run(c); run(); assert!(menu(c).is_some());"), + [], + "Unicode whitespace after let separates the pattern" + ); + assert_eq!( + census("let run = async || app.run(c);\u{85}block_on(run()); assert!(menu(c).is_some());"), + [], + "Unicode whitespace before block_on" + ); assert_eq!( census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), [(2, "census")], From 1576aac89ff4e568573906cd9ecddbf720909793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:56:24 -0800 Subject: [PATCH 363/533] Scripts: compound path pathItems.index(n) reads the members `PathItems.index()` with a number went straight to `items_doc`, which refuses every compound-path-scoped `PathItems` so that creating paths there stays unavailable. Its siblings (`[n]`, `getByName`, `length`, `removeAll`) already dispatch scoped collections to the layer handlers first, but `index` did not, so `compoundPathItems[0].pathItems.index(0)` threw "creating paths in a compound path is not available yet". Route a scoped `index` to `scoped_index` like the other lookups; the guard now only stops real creation. --- crates/engine/src/script/dom/paths.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ae2fcda50a..4ac860ebee 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -477,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { From 30ff8bef31b45acbcbb9987b385ed1666bfe9389 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:08:30 -0800 Subject: [PATCH 364/533] Marquee: skip paths whose control box lies apart from the marquee hit::intersects_rect measured every path's exact bounds before deciding it missed the marquee. Since the anchors became chunked (#7814), that walk costs about three times as much, and a marquee over many paths became about 1.8x slower than in 0.24.1. It now first compares the path's cached control box with the rect and returns false when the two lie strictly apart. A control box that only touches the rect, or has no area, still goes to the exact checks. On a 50,000-path document a 400x300 marquee takes 8.2 to 10.6 ms instead of 46 to 64 ms, and selects the same 3,675 paths. --- crates/geom/src/hit.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index 0358acac90..fea760b548 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -118,6 +118,14 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { /// filled shape doesn't touch it, so a marquee drawn over a background picks only what is on it /// (#1103). pub fn intersects_rect(path: &PathData, r: Rect) -> bool { + // The control box holds every anchor and segment, and the path keeps it measured, so a path + // whose control box lies wholly apart from the rect misses it without measuring its segments. + // The test is strict: a control box that only touches the rect, or has no area, goes on to the + // exact checks below. + let (Some(c), n) = (path.control_bounds(), r.abs()) else { return false }; + if c.x1 < n.x0 || n.x1 < c.x0 || c.y1 < n.y0 || n.y1 < c.y0 { + return false; + } let Some(b) = path.bounds() else { return false }; let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) { @@ -238,6 +246,30 @@ mod tests { // zero-height marquee missing it assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0))); } + + /// A marquee that lies apart from a path's control box misses it without measuring the path's + /// segments. One that reaches the control box but not the curve is still judged on the curve. + #[test] + fn marquee_apart_from_the_control_box_measures_no_segment() { + let p = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)); + let measured = crate::path::measured_segments; + let before = measured(); + assert!(!intersects_rect(&p, Rect::new(20.0, 20.0, 30.0, 30.0))); + assert!(!intersects_rect(&p, Rect::new(-30.0, 4.0, -20.0, 6.0))); + assert_eq!(measured(), before, "a marquee apart from the control box measures nothing"); + // A curve whose handle reaches into the marquee while the curve stays below it. + use crate::path::{Anchor, SubPath}; + let arch = PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 40.0)), + Anchor::with_handles(Point::new(10.0, 0.0), Point::new(10.0, 40.0), Point::new(10.0, 0.0)), + ], + false, + )]); + assert!(!intersects_rect(&arch, Rect::new(-1.0, 35.0, 11.0, 39.0)), "the curve peaks at y 30"); + assert!(measured() > before, "a marquee inside the control box measures the curve"); + assert!(intersects_rect(&arch, Rect::new(4.0, 25.0, 6.0, 35.0)), "a marquee across the peak"); + } } #[cfg(test)] From 4ff245a13f1174160a1a018def2738ef25198918 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:15:07 -0800 Subject: [PATCH 365/533] Stroke: Caps stay enabled on closed paths without dashes The Stroke panel's Caps row was disabled whenever the selection was a closed path with a solid stroke, so the current cap was not shown and a new cap could not be set until dashes were turned on. The panel now builds the stroke editor with caps_on_closed(true), which keeps the row enabled for closed paths. Adds a test that selects a closed rectangle with a solid stroke, checks that the Caps buttons are enabled with the current cap lit, and that a click sets the cap as one undo step. --- crates/ui-egui/src/panels/stroke.rs | 1 + crates/ui-egui/src/panels/tests_strokeux.rs | 22 +++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 0a8ce3b8da..b9df0a12ec 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -411,6 +411,7 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) { let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone())) .sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN) .closed(mixed.can_align) + .caps_on_closed(true) .mixed(&mixed_of(&mixed)) .host_labels(true); let output = editor.show(ui); diff --git a/crates/ui-egui/src/panels/tests_strokeux.rs b/crates/ui-egui/src/panels/tests_strokeux.rs index 12839f283c..11dd24ebd5 100644 --- a/crates/ui-egui/src/panels/tests_strokeux.rs +++ b/crates/ui-egui/src/panels/tests_strokeux.rs @@ -157,6 +157,28 @@ fn inside_and_outside_are_off_for_open_paths_and_on_for_type() { assert_eq!(align(&panel), vectorcraft_doc::StrokeAlign::Inside, "type's characters do, around their glyphs"); } +/// A closed path without dashes still shows its cap and takes a new one, ready for when dashes are turned on. +#[test] +fn caps_stay_on_for_a_solid_closed_path() { + use craft::behavior::Mixed; + use vectorcraft_doc::LineCap; + + let mut app = app_with_rect(); + run(&mut app, "paint.setStroke", json!({"color": "#222222"})); + run(&mut app, "stroke.set", json!({"cap": "square"})); + let mut panel = Panel::new(app, stroke::show); + panel.frame(); + let stroke = |p: &Panel| current_stroke(&p.app()).unwrap(); + assert!(stroke(&panel).dash.is_none(), "the rectangle's stroke is solid"); + assert!(panel.enabled("Butt / Flat")); + assert!(panel.enabled("Square")); + assert_eq!(panel.toggled("Square"), Some(Mixed::Same(true)), "the current cap is lit"); + let baseline = panel.app().session.active().unwrap().history.undo.len(); + panel.click("Butt / Flat"); + assert_eq!(stroke(&panel).cap, LineCap::Butt); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), baseline + 1); +} + /// While the Type tool edits text, Align Stroke styles the selected characters' stroke. #[test] fn align_stroke_styles_the_characters_the_type_tool_selects() { From 499055bbbdbeced54007b481b9b60c8af93f35ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:16:38 -0800 Subject: [PATCH 366/533] Tools: show Edit Toolbar alone in the one-column rail The one-column Tools rail stacked Search above Edit Toolbar in its footer. The extra row made the default rail taller than a 1000 pt window holds, so the rail scrolled and Edit Toolbar was out of view. A one-column rail now shows Edit Toolbar alone. Search Commands stays in the title bar, Help > Search Commands... and its shortcut. The two-column rail keeps Search beside Edit Toolbar. Tests: one_column_rail_shows_edit_toolbar_in_a_1000_point_window; the #8758 layout test checks the one-column footer, and the search query test runs on the two-column rail. --- crates/ui-egui/src/toolbar.rs | 26 +++++++-------- crates/ui-egui/src/toolbar/tests.rs | 50 +++++++++++++++++++++++------ docs/gaps.md | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 4 +-- 6 files changed, 59 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 34a7829ba9..217c08bf42 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC use craft::ui::display::Divider; use craft::ui::docking::{DockGrid, GroupAt}; use craft::ui::form::Field; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::layout_components::Row; use craft::ui::pickers::{Anchor9, ReferencePointLook, Select}; use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot}; use craft::ui::runtime::commands::{self, CommandRef}; @@ -893,17 +893,21 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod card; -/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last. +/// Search and Edit Toolbar share a row in a wide rail. A one-column rail shows Edit Toolbar alone, so the default +/// rail still fits a 1000 pt window; Search Commands stays in the title bar, the Help menu and on its shortcut. fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option { let enabled = !crate::panel_docking::modal_window_up(app); + let wide = footer.columns > 1; let mut edit = None; let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| { - IconButton::command(IconId::new("search"), "help.commandPalette") - .label(tl!("Search commands")) - .tooltip(tl!("Search commands, tools, panels and effects")) - .selected(app.ui.palette_open) - .enabled(enabled) - .show(ui); + if wide { + IconButton::command(IconId::new("search"), "help.commandPalette") + .label(tl!("Search commands")) + .tooltip(tl!("Search commands, tools, panels and effects")) + .selected(app.ui.palette_open) + .enabled(enabled) + .show(ui); + } edit = Some( IconButton::new(IconId::new("more")) .label(tl!("Edit Toolbar")) @@ -913,11 +917,7 @@ fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter .response, ); }; - if footer.columns > 1 { - Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); - } else { - Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); - } + Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); edit } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 91becce66b..bd52339ac2 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -703,19 +703,22 @@ fn review_8758_layout(double: bool) { let nodes = settled(&mut app, &ctx, 0.0, 1400.0); review_8758_edit_control(&mut app, &ctx, &nodes); let nodes = settled(&mut app, &ctx, 3.0, 1400.0); - let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); let panel = review_8758_panel(&app, &ctx); + if !double { + assert!(panel.contains_rect(edit) && edit.bottom() <= 1400.0, "Edit Toolbar fits the actual Tools panel"); + assert!( + !nodes + .iter() + .any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| panel.contains_rect(r))), + "a one-column rail shows Edit Toolbar alone" + ); + return; + } + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel"); assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window"); - if double { - assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); - } else { - assert!( - search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01, - "one column keeps both controls in a fitted stack" - ); - } + assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut"); let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform()); let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center()); @@ -744,10 +747,39 @@ fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette() } } +/// The default one-column rail in a window 1000 points tall: its footer ends with Edit Toolbar inside the rail's +/// visible area, so the button shows without scrolling the rail. +#[test] +fn one_column_rail_shows_edit_toolbar_in_a_1000_point_window() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1000.0); + let panel = review_8758_panel(&app, &ctx); + let rail = nodes + .iter() + .find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools") && bounds(n).is_some_and(|r| panel.contains_rect(r))) + .and_then(bounds) + .expect("the Tools rail is drawn"); + let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); + let screen_mode = named_rect(&nodes, "Change Screen Mode (F)"); + assert!(rail.contains_rect(edit), "Edit Toolbar shows inside the rail without scrolling: {edit:?} in {rail:?}"); + assert!(screen_mode.bottom() <= edit.top(), "Edit Toolbar stays the last control of the footer"); + assert!( + !nodes.iter().any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| rail.intersects(r))), + "one column leaves Search Commands to the title bar, the Help menu and its shortcut" + ); + // Edit Toolbar still opens the Tools customization drawer. + click(&mut app, &ctx, 1.0, edit.center(), 1000.0); + assert!(app.ui.tools_drawer, "the footer's Edit Toolbar opens the customization drawer"); +} + #[test] fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() { crate::i18n::set_current(crate::i18n::Lang::EN); let mut app = app_with(300, 300); + // The two-column rail, whose footer has Search. + app.run("window.toolbarColumns", json!({"double": true})).unwrap(); let ctx = reader(); let nodes = settled(&mut app, &ctx, 0.0, 1400.0); let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); diff --git a/docs/gaps.md b/docs/gaps.md index f17b874b92..b7a50c6cdf 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -27,7 +27,7 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. - **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. diff --git a/docs/roadmap.md b/docs/roadmap.md index f2e6058229..16a01a5ac1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,7 +33,7 @@ ## Feature submission evidence Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..41f90515cf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2bd6e1ff3..611ae42c25 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -29,7 +29,7 @@ **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. @@ -497,7 +497,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | unknown | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | unknown | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | unknown | -| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown | +| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and Edit Toolbar alone in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | unknown | | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | unknown | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | unknown | From 1c9efecfb65e322518910ca6243841193d65e966 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:20:56 -0800 Subject: [PATCH 367/533] Workspaces: built-in workspaces open their panel again Switching to Essentials Classic, Automation, Layout, Painting, Printing and Proofing, Typography, Web or Touch, or resetting one, brought its panel to the front of its group but no longer opened it from a column collapsed to icons, so the panel stayed hidden. A workspace record keeps the panel open from the icons again: each built-in names its panel, a workspace left or saved keeps the one open then, and switching or Reset opens it. A recorded panel the new layout does not show from icons stays closed. Workspaces saved without the field open none. The Essentials Classic test checks the open panel again, and new tests cover Painting, Automation, switching back as left, Reset, saved workspaces and the preferences' JSON. --- crates/ui-egui/src/workspaces.rs | 77 ++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 683c087332..5b04aa50f2 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -64,6 +64,10 @@ pub struct WorkspaceRecord { /// Tabs closed together by a panel shortcut. #[serde(skip_serializing_if = "Vec::is_empty")] pub docking_hidden_groups: Vec>, + /// The panel open from a column collapsed to icons (built-in workspaces: the panel the + /// workspace is for; workspaces saved without this field: none). + #[serde(skip_serializing_if = "Option::is_none")] + pub open_panel: Option, /// The tool each flyout group of the main Tools shows (built-in workspaces: the first). pub tools_last_used: LastUsed, /// The toolbars made with New Toolbar in this workspace (built-in workspaces: none). @@ -87,6 +91,7 @@ impl Default for WorkspaceRecord { status_bar: true, help_bar: true, docking_hidden_groups: Vec::new(), + open_panel: None, tools_last_used: LastUsed::default(), toolbars: Vec::new(), } @@ -245,25 +250,30 @@ pub fn builtins() -> Vec { x.rulers = true; x.toolbar_advanced = true; x.task_bar = false; + x.open_panel = Some("color".into()); }), w("Automation", &["layers", "actions"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("actions".into()); }), w("Layout", &["layers", "align"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("align".into()); }), w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("brushes".into()); }) .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("info".into()); }), w("Tracing", &["layers"], &|x| { x.control_bar = true; @@ -274,16 +284,19 @@ pub fn builtins() -> Vec { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("character".into()); }), w("Web", &["symbols"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("symbols".into()); }), w(TOUCH, &["align"], &|x| { x.control_bar = true; x.toolbar_advanced = true; x.task_bar = true; + x.open_panel = Some("align".into()); }), ] } @@ -387,6 +400,7 @@ pub fn record(ui: &UiState) -> WorkspaceRecord { status_bar: ui.status_bar, help_bar: ui.help_bar, docking_hidden_groups: ui.docking_hidden_groups.clone(), + open_panel: ui.open_panel.clone(), tools_last_used: ui.tools_last_used.clone(), toolbars: ui.custom_toolbars.clone(), } @@ -412,6 +426,7 @@ fn apply_record(ui: &mut UiState, w: &WorkspaceRecord) { ui.status_bar = w.status_bar; ui.help_bar = w.help_bar; ui.docking_hidden_groups = w.docking_hidden_groups.clone(); + ui.open_panel = w.open_panel.clone(); ui.tools_last_used = w.tools_last_used.clone(); ui.custom_toolbars = w.toolbars.clone(); crate::custom_toolbars::sanitize(&mut ui.custom_toolbars); @@ -450,10 +465,19 @@ pub fn switch(app: &mut VectorcraftApp, key: &str) -> Result { let w = ui.workspaces.edited.get(&id).cloned().unwrap_or_else(|| saved_record(&ui.workspaces, &id)); apply_record(ui, &w); crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); Ok(name) } +/// Close the open panel when the layout now in use does not show it from a column collapsed to +/// icons (it was moved, expanded or closed). +fn close_stale_flyout(ui: &mut UiState) { + if ui.open_panel.as_ref().is_some_and(|panel| !crate::panel_docking::layout_of(ui).opens_in_flyout(panel)) { + ui.open_panel = None; + } +} + /// Reset the current workspace to the way it was saved, dropping its changes. pub fn reset(app: &mut VectorcraftApp) -> String { let ui = &mut app.ui; @@ -467,6 +491,7 @@ pub fn reset(app: &mut VectorcraftApp) -> String { apply_record(ui, &w); ui.custom_toolbars = toolbars; crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); current_name(&app.ui).to_string() } @@ -715,12 +740,64 @@ mod tests { switch(&mut app, "Essentials Classic").unwrap(); assert!(app.ui.control_bar && app.ui.view.rulers && app.ui.toolbar_advanced); assert!(front(&app.ui, "color")); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); assert_eq!(current_name(&app.ui), "Essentials Classic"); switch(&mut app, "essentials").unwrap(); assert!(!app.ui.control_bar && !app.ui.view.rulers); + assert_eq!(app.ui.open_panel, None); assert_eq!(app.ui.brightness, crate::theme::Brightness::Light); } + /// A built-in workspace shows the panel it is for, from its collapsed column too: the second + /// panel it brings forward (Automation's Actions) as well as the only one (Painting's + /// Brushes). A panel closed there stays closed when the workspace is left and switched back + /// to, and Reset opens it again. + #[test] + fn builtin_workspaces_show_their_panel_after_switch_and_reset() { + let showing = crate::panel_docking::showing; + let mut app = app(); + for (name, panel) in [("Painting", "brushes"), ("Automation", "actions"), ("Essentials Classic", "color")] { + switch(&mut app, name).unwrap(); + assert!(showing(&app.ui, panel), "{name} shows {panel}"); + } + assert!(crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&"color".to_string()), "Classic's Color opens from its icon"); + app.ui.open_panel = None; + switch(&mut app, ESSENTIALS).unwrap(); + assert!(!showing(&app.ui, "color"), "Essentials opens no panel"); + switch(&mut app, "Essentials Classic").unwrap(); + assert!(!showing(&app.ui, "color"), "Classic comes back as it was left"); + reset(&mut app); + assert!(showing(&app.ui, "color"), "Reset Essentials Classic shows Color again"); + } + + /// A saved workspace keeps the panel open from its icons, through the preferences' JSON too; a + /// workspace saved without that field opens none, and one naming a panel its layout does not + /// show from icons opens none either. + #[test] + fn saved_workspaces_restore_the_open_panel() { + let mut app = app(); + switch(&mut app, "Essentials Classic").unwrap(); + save_as(&mut app.ui, "Colors").unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(app.ui.open_panel, None); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); + let id = id_of(&app.ui, "Colors"); + let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert_eq!(back.workspaces.records[&id].open_panel.as_deref(), Some("color")); + let mut old = serde_json::to_value(&back.workspaces.records[&id]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("openPanel").is_some()); + let old: WorkspaceRecord = serde_json::from_value(old).unwrap(); + assert_eq!(old.open_panel, None); + switch(&mut app, ESSENTIALS).unwrap(); + app.ui.workspaces.edited.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel, None, "switching opens no panel the layout's icons lack"); + app.ui.workspaces.records.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + reset(&mut app); + assert_eq!(app.ui.open_panel, None, "Reset opens no panel the layout's icons lack"); + } + #[test] fn save_apply_round_trip() { let mut app = app(); From 5ce02bb64bd7aae18ea65c6b90f2bb8c82bdd6a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:26:00 -0800 Subject: [PATCH 368/533] Flatten Transparency: write rasterized areas as fast-compressed PNGs Since #7669 the flattener's rasters have been encoded through the shared image codec with its default compression (zlib level 6). EPS export, and any other export that flattens, encodes every rasterized area this way and then decodes it again right away, so a document with many live effects exported about 170 ms slower to EPS. The rasters are now written with PngCompression::Fast, as the SVG filter raster already is (crates/effects/src/svg_filter.rs). The pixels and the EPS output bytes do not change. --- crates/engine/src/cmd/flatten/apply.rs | 14 ++++++++++- crates/engine/src/tests/flatten.rs | 35 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index fe1e183d16..8a884b67ea 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio } } } - let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + // The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it + // again right away. + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 042f741e0e..959c58e9f3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950) +/// gives compression level 0, the fastest. +#[test] +fn rasterized_areas_are_png_with_fast_compression() { + let _settings = settings_lock(); + let mut s = session(); + let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"})); + assert_eq!(rasterized, 1); + let mut keys = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + let [key] = &keys[..] else { panic!("one image: {keys:?}") }; + let png = &s.doc().unwrap().doc.images[key].bytes; + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG"); + let mut at = 8; + let level = loop { + let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") }; + if kind == b"IDAT" { + break png[at + 9] >> 6; + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + }; + assert_eq!(level, 0, "zlib FLEVEL of the stored PNG"); +} + #[test] fn a_long_rasterized_area_is_placed_whole() { let _settings = settings_lock(); From c679af091d734686f96eece544b7fd7174fe986f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:31:19 -0800 Subject: [PATCH 369/533] Vector Halftone: write each round dot with four curves again The cell-clipped dots split every elliptical arc at 45 degrees, and the quadrants were joined with a zero-length line where they met on an axis. A round dot that stays inside its cell had 8 curves and 3 extra anchors instead of 4 curves, and the halftone's SVG export grew to about twice its size. - Arcs are split at 90 degrees, one curve per quarter turn. - Quadrants and spot corners that meet at the same point are joined without a line, so the join adds no anchor. Tests: an unclipped Circle and Ellipse dot is 4 curves and no line, and no dot shape repeats an anchor where its quadrants or corners meet. --- crates/effects/src/addons/halftone.rs | 71 +++++++++++++++++++++------ 1 file changed, 56 insertions(+), 15 deletions(-) diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index d371bfb363..4f19f09a5a 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -173,13 +173,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 { curves.iter().map(|c| c.signed_area()).sum() } -/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each +/// quarter turn or part of one. fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { if t1 <= t0 { return; } let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); - let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0); let d = (t1 - t0) / n; let k = 4.0 / 3.0 * (d / 4.0).tan(); for i in 0..n as usize { @@ -294,20 +295,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { return four_quadrants(&spot_quadrant(t, h, kind)); } let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { + let mut end: Option = None; + // Corners that meet at a point on the cell's side are joined without an anchor of their own. + let mut add = |curves: Vec| { for (k, c) in curves.iter().enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; // Round the corners counterclockwise, each one's hole the dot of the opposite tone. let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); - add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); - add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); - add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); - add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y)))); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y))); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h)))); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h))); bp.close_path(); bp } @@ -410,21 +418,28 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { } /// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other -/// three quadrants, counterclockwise. +/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor +/// of their own at the join. fn four_quadrants(q1: &[CubicBez]) -> BezPath { let mut bp = BezPath::new(); - let mut add = |curves: Vec, first: bool| { + let mut end: Option = None; + let mut add = |curves: Vec| { for (k, c) in curves.iter().enumerate() { if k == 0 { - if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + match end { + None => bp.move_to(c.p0), + Some(e) if e.distance(c.p0) < 1e-9 => {} + Some(_) => bp.line_to(c.p0), + } } bp.curve_to(c.p1, c.p2, c.p3); + end = Some(c.p3); } }; - add(q1.to_vec(), true); - add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false); - add(mapped(q1, |p| Point::new(-p.x, -p.y)), false); - add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false); + add(q1.to_vec()); + add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y)))); + add(mapped(q1, |p| Point::new(-p.x, -p.y))); + add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y)))); bp.close_path(); bp } @@ -731,6 +746,7 @@ mod tests { use super::*; use vectorcraft_doc::Effect; use vectorcraft_geom::Shape; + use vectorcraft_geom::kurbo::PathEl; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -833,6 +849,31 @@ mod tests { } } + #[test] + fn a_dot_inside_its_cell_is_four_curves() { + for shape in [DotShape::Circle, DotShape::Ellipse] { + let bp = shape.path(0.2, 10.0).to_bezpath(); + let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count(); + let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count(); + assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements()); + } + } + + #[test] + fn dot_quadrants_join_without_a_repeated_anchor() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.45, 0.55, 0.6, 0.85] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + #[test] fn euclidean_dots_meet_corner_to_corner_at_half() { let s = DotShape::Euclidean; From f5111b293dd78df3e68c26b84b2696aff04eb234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:51:35 -0800 Subject: [PATCH 370/533] Home: the title is drawn at 24 points again The compact type was set to 92% of its nominal sizes (body 13 to 12, labels 12.5 to 11.5, captions 11.5 to 10.5), but the display type that draws the Home title stayed at 26 points on a 32-point line, so the title drew about 8.7% larger than in 0.24.1. The display type is now 24 points on a 29-point line, its nominal 26 on 32 at the same scale. A test checks that the title keeps the nominal title-to-body proportion against the compact body type, and that its line keeps the framework's display line proportion. --- crates/ui-egui/src/theme.rs | 38 ++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 09b5eec0b0..b47ef8e91e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -146,7 +146,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { } /// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners -/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16 +/// where the sets give pills, the Home title is 24-point on a 29-point line (its nominal 26 points on 32 at the 92% +/// the body type below is set at) with a 36-point call to action, 28-point New and Open with 16 /// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections, /// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set /// takes the reference app's metrics: @@ -159,8 +160,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { const SIZES: &[u8] = br#"{ "all": { "radius.button": 4, - "typography.display.size": 26, - "typography.display.line_height": 32, + "typography.display.size": 24, + "typography.display.line_height": 29, "size.page.action": 36, "size.page.button": 28, "size.page.button_side": 16, @@ -236,6 +237,37 @@ mod tests { assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty())); } + /// The Home title (the display type) is set at the same scale as the compact body type, so it keeps the nominal + /// 26-point title over a 13-point body proportion, and its line keeps the framework's display line proportion. + #[test] + fn the_home_title_is_scaled_with_the_body_type() { + use craft::theme::Size; + use craft::ui::runtime::env::{Env, RootEnv}; + use craft::ui::testing::Fixture; + use std::cell::Cell; + use std::rc::Rc; + const NOMINAL_TITLE_OVER_BODY: f32 = 26.0 / 13.0; + let typography = |sizes: Arc| { + let seen = Rc::new(Cell::new(None)); + let seen_in = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let t = Env::of(ui).tokens.tokens().typography; + seen_in.set(Some((t.display, t.body))); + }); + let mut root = RootEnv::new().density(Size::Compact); + root.sizes = sizes; + fixture.root(root); + fixture.frame(vec![]); + seen.get().expect("the fixture drew a frame") + }; + let (display, body) = typography(app_sizes()); + let ratio = display.size / body.size; + assert!((ratio - NOMINAL_TITLE_OVER_BODY).abs() < 0.05, "a {}-point title over a {}-point body", display.size, body.size); + let (framework, _) = typography(Arc::new(AppSizes::default())); + let (line, framework_line) = (display.line_height / display.size, framework.line_height / framework.size); + assert!((line - framework_line).abs() < 0.05, "a {}-point line for a {}-point title", display.line_height, display.size); + } + /// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow /// the framework's spacing scale. #[test] From b7bc86522cbd0a2fc25d417a2b81441367562925 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:52:39 -0800 Subject: [PATCH 371/533] Tools: a strip floated before the canvas is laid out opens beside the rail window.floatTools placed a new strip at the canvas's top left, and fell back to (0,0) when no view had been laid out yet: right after a document opened, or with no document open. The strip then covered the top of the docked Tools rail. Without a laid-out view, the strip now opens beside the docked rail it came from (else the Tools panel's), level with the rail's top and the float space's cascade inset away from it, on the side toward the middle of the window. A dragged tear-off still opens at the pointer. --- crates/ui-egui/src/panel_docking.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 12 +++++++++--- crates/ui-egui/src/toolbar/tests.rs | 24 ++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0fd8936a45..1a47d5a7d2 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -301,6 +301,28 @@ pub(crate) fn column_of<'a>(layout: &'a Layout, panel: &str) -> Option<( Some((edge, column)) } +/// Where the dock last drew the docked column holding `panel`; none until the dock has drawn it, and while `panel` +/// floats or is closed. +pub(crate) fn column_rect(app: &VectorcraftApp, panel: &str) -> Option { + let (Some(_), column) = column_of(layout_of(&app.ui), panel)? else { return None }; + app.dock_rt.columns.iter().find(|(first, _)| column.panels().any(|p| p == first)).map(|(_, rect)| *rect) +} + +/// The top left a new floating window of `panel` takes beside the docked column holding `beside`: level with the +/// column's top, the cascade inset away from it on the side toward the middle of the float space. None until the dock +/// has drawn that column. +pub(crate) fn float_origin_beside(app: &VectorcraftApp, panel: &str, beside: &str) -> Option { + let column = column_rect(app, beside)?; + let space = command_space(app); + let x = if column.center().x <= space.area.center().x { + column.right() + space.inset + } else { + let width = space.size_of(&DragUnit::Panel(panel.to_owned()), None).x; + column.left() - space.inset - width + }; + Some(egui::pos2(x, column.top())) +} + /// Is the dock's outer column of panels (Properties · Layers · Libraries) collapsed to icons? pub(crate) fn dock_collapsed(ui: &UiState) -> bool { dock_columns(layout_of(ui)).first().is_some_and(|c| c.iconic) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 34a7829ba9..49da6d5a44 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -294,11 +294,17 @@ pub(crate) fn is_floating(app: &VectorcraftApp, toolbar: Option<&str>, key: &str strips(app, toolbar).iter().any(|g| g.first() == Some(&key)) } -/// Float the group `first` of `owner` as a strip at `at` (none: the canvas's corner). +/// Float the group `first` of `owner` as a strip at `at`. Without `at` the strip opens at the canvas's corner, or, +/// before a view has been laid out, beside `owner`'s docked rail, else beside the Tools panel's. fn place_strip(app: &mut VectorcraftApp, owner: &Owner, first: &str, at: Option) -> Result<(), String> { - let at = at.unwrap_or_else(|| app.canvas_view().map_or(Pos2::ZERO, |v| v.rect.min)); + let id = strip_id(owner, first); + let at = at + .or_else(|| app.canvas_view().map(|v| v.rect.min)) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, &owner.panel())) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, TOOLS)) + .unwrap_or(Pos2::ZERO); // A width of 0 leaves the window's width to the panel's grid. - crate::panel_docking::place_floating(app, &strip_id(owner, first), at, 0.0) + crate::panel_docking::place_floating(app, &id, at, 0.0) } /// Float the toolbar group (of the current layout) holding `tool` as a strip of tool buttons, put diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 91becce66b..2abb2f3cc1 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -483,6 +483,30 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(strip_rect(&app, "rectangle").is_none() && !is_floating(&app, None, "pen")); } +/// `window.floatTools` run before a view has been laid out (right after a document opens, or with none open) floats the +/// strip beside the docked Tools rail, not over it, and the strip stays clear of the rail once the frames are drawn. +#[test] +fn a_strip_floated_before_a_view_is_laid_out_opens_beside_the_tools_rail() { + for (case, document) in [("document just opened", true), ("no document", false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + settled(&mut app, &ctx, 0.0, 900.0); + if document { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + } + assert!(app.canvas_view().is_none(), "{case}: no view has been laid out yet"); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail is docked")); + app.run("window.floatTools", json!({"tool": "pen"})).unwrap(); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip floats")); + assert!(strip.left() >= rail.right(), "{case}: the strip {strip:?} opens right of the rail {rail:?}"); + assert!((strip.top() - rail.top()).abs() <= f32::EPSILON, "{case}: the strip {strip:?} is level with the rail {rail:?}"); + settled(&mut app, &ctx, 1.0, 900.0); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail stays docked")); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip still floats")); + assert!(!strip.intersects(rail), "{case}: the strip {strip:?} is clear of the rail {rail:?}"); + } +} + /// A floated group is a panel of the workspace's layout: a saved workspace brings it back, the built-in ones have none. #[test] fn workspaces_keep_floating_flyouts_and_reset_puts_them_back() { From b91beb68fd92bb39d757f7162e9e928e572d2f34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:56:42 -0800 Subject: [PATCH 372/533] Scripts: refuse read-only export files, hidden rasterize sources and capture over write-only documents - A multi-file export checks every destination before writing and refuses an existing read-only file, as save does, so no file is written. - object.rasterize and Document.rasterize refuse an id that is hidden or in a hidden layer or group, as they refuse locked ones. - imageCapture compares open documents and linked files that only a write root covers, so it no longer replaces such a document's file. - The blank-capture test also checks the pixel count, as test-lint asks. --- crates/engine/src/cmd/fileio/export_names.rs | 6 +++- .../engine/src/cmd/fileio/tests_readonly.rs | 27 +++++++++++++++ crates/engine/src/cmd/menucmds.rs | 5 ++- .../engine/src/script/dom/raster_capture.rs | 33 ++++++++++++++----- .../engine/src/tests/script_raster_capture.rs | 20 +++++++++++ docs/mcp.md | 15 +++++---- 6 files changed, 89 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 6c49622553..b38da6bb84 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -88,9 +88,13 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do if files.len() > 1 { for (p, _) in &files { super::may_write(p)?; - if std::path::Path::new(p.as_str()).is_dir() { + let Ok(meta) = std::fs::metadata(p) else { continue }; + if meta.is_dir() { return Err(EngineError::Other(format!("{p}: is a folder, not a file"))); } + if meta.is_file() && meta.permissions().readonly() { + return Err(super::access::save_write_error(p, std::io::Error::from(std::io::ErrorKind::PermissionDenied))); + } } } for (p, bytes) in &files { diff --git a/crates/engine/src/cmd/fileio/tests_readonly.rs b/crates/engine/src/cmd/fileio/tests_readonly.rs index bee4258f8b..a60e9841b2 100644 --- a/crates/engine/src/cmd/fileio/tests_readonly.rs +++ b/crates/engine/src/cmd/fileio/tests_readonly.rs @@ -59,6 +59,33 @@ fn readonly_sidecar_leaves_every_save_destination_unchanged() { } } +#[test] +fn readonly_export_file_leaves_every_export_destination_unchanged() { + let dir = vectorcraft_testkit::TempDir::new("export-readonly-sidecar"); + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 40, "height": 40, "artboards": 2})).unwrap(); + let doc = session.doc().unwrap().doc.clone(); + let enc = super::Encoded { files: vec![(None, b"new main".to_vec()), (Some(1), b"new board".to_vec())], ..Default::default() }; + let path = dir.join("Poster.svg").to_string_lossy().into_owned(); + let files: Vec = enc.named(&doc, &path).into_iter().map(|(p, _)| p).collect(); + assert_eq!(files.len(), 2); + for file in &files { + std::fs::write(file, b"old").unwrap(); + } + let sidecar = &files[1]; + let original = std::fs::metadata(sidecar).unwrap().permissions(); + let mut readonly = original.clone(); + readonly.set_readonly(true); + std::fs::set_permissions(sidecar, readonly).unwrap(); + let result = super::write_encoded(Some(&path), "Poster.svg", &doc, &enc, json!({})); + std::fs::set_permissions(sidecar, original).unwrap(); + let error = result.unwrap_err(); + assert!(matches!(error, EngineError::ReadOnlyLocation(_)), "{error}"); + for file in &files { + assert_eq!(std::fs::read(file).unwrap(), b"old", "{file}"); + } +} + #[test] fn readonly_failed_save_keeps_document_and_options() { let mut session = Session::new(); diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 0556fe7e20..4eba8c7235 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, and off locked artboards; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -1014,6 +1014,9 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { if locks.holds_id(*id) { return Err(bad(cmd, format!("id {} is on a locked artboard", id.0))); } + if up.iter().any(|a| d.node(*a).is_some_and(|n| !n.visible)) { + return Err(bad(cmd, format!("id {} is hidden or in a hidden layer or group", id.0))); + } roots.push(*id); } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index dfa77fc1f2..1eb66216a1 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -299,8 +299,13 @@ fn sources_on_disk(h: &Host) -> Vec { paths.iter().filter_map(|p| source_place(p)).collect() } +/// An open document or linked file inside the automation read or write roots: one that only a write +/// root covers is compared too, since a capture may write there. A path outside both is left out +/// before it is looked up, as no capture can write it; the refusal names only the requested path. fn source_place(path: &str) -> Option { - crate::file_access::check_read(path).ok()?; + if crate::file_access::check_read(path).is_err() && crate::file_access::check_write_unrecorded(path).is_err() { + return None; + } placed(std::path::Path::new(path)) } @@ -507,18 +512,28 @@ mod source_tests { use super::*; #[test] - fn capture_sources_exclude_files_outside_automation_roots() { + fn capture_sources_keep_files_outside_automation_read_roots() { let dir = vectorcraft_testkit::TempDir::new("capture-source-roots"); - let allowed = dir.join("allowed"); - std::fs::create_dir(&allowed).unwrap(); - let inside = allowed.join("doc.vectorcraft"); - let outside = dir.join("linked.png"); + let readable = dir.join("readable"); + let writable = dir.join("writable"); + std::fs::create_dir(&readable).unwrap(); + std::fs::create_dir(&writable).unwrap(); + let inside = readable.join("doc.vectorcraft"); + // An open document that only a write root covers: a capture to its path must still be + // refused. + let outside = writable.join("other.vectorcraft"); + // Outside every root: no capture can write it, so it is not looked up. + let elsewhere = dir.join("linked.png"); std::fs::write(&inside, b"document").unwrap(); - std::fs::write(&outside, b"linked").unwrap(); - let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap(); + std::fs::write(&outside, b"document").unwrap(); + std::fs::write(&elsewhere, b"linked").unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&readable], &[&writable]).unwrap(); crate::file_access::confine(roots.as_ref(), || { assert!(source_place(&inside.to_string_lossy()).is_some()); - assert!(source_place(&outside.to_string_lossy()).is_none()); + assert!(source_place(&elsewhere.to_string_lossy()).is_none()); + let source = source_place(&outside.to_string_lossy()).expect("a source outside the read roots is still compared"); + let target = placed(&outside).unwrap(); + assert!(same_file(&target, &source)); }); } } diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index bd4fe83f92..057c022dea 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -267,6 +267,25 @@ fn script_rasterize_rejects_groups_with_locked_descendants() { s.execute("object.rasterize", &json!({"ids": [outer], "ppi": 72})).unwrap(); } +#[test] +fn rasterize_rejects_explicit_hidden_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + s.execute("object.setProps", &json!({"id": group, "visible": false})).unwrap(); + for id in [a.0, b.0] { + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [id]})).unwrap_err().to_string(); + assert!(e.contains("hidden"), "{e}"); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(undo_steps(&s), undo); + } + s.execute("object.setProps", &json!({"id": a.0, "visible": true})).unwrap(); + s.execute("object.rasterize", &json!({"ids": [a.0], "ppi": 72})).unwrap(); +} + #[test] fn rasterize_rejects_explicit_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); @@ -527,6 +546,7 @@ fn image_capture_of_bounds_without_art_is_blank() { for (name, blank) in [("blank.png", [255, 255, 255, 255]), ("clear.png", [0, 0, 0, 0])] { let img = png(&dir.join(name)); assert_eq!((img.width(), img.height()), (50, 50), "{name}"); + assert_eq!(img.pixels().len(), 2500, "{name}"); assert!(img.pixels().all(|p| p.0 == blank), "{name}: every pixel is {blank:?}"); } assert_eq!(undo_steps(&s), undo, "a capture changes nothing in the document"); diff --git a/docs/mcp.md b/docs/mcp.md index ad8d7dea5b..e0356af3d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3273,7 +3273,8 @@ through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when the script's folders refuse one of those files, none of them is written; a write that fails once the + when the script's folders refuse one of those files, or one is a folder or an existing read-only file, none of + them is written; a write that fails once the first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and @@ -3671,8 +3672,8 @@ through `$`: below the top one, throw an error. For bounds that miss all the art, `rasterize` throws an error and `imageCapture` writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in - a locked layer or group or on a locked artboard throw an error, and nothing changes. An object containing - locked descendants also throws an error. + a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an + error, and nothing changes. An object containing locked descendants also throws an error. Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -3684,8 +3685,9 @@ through `$`: opened for writing is checked, and a path that is an open document's file or a file one of them links throws an error, also when that file is missing. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS - image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem - probes. The documents count whether they were open when the run started or were + image's plate files beside each. Paths rejected by the document's path restrictions, and paths outside both the + automation read and write roots, are left out of the comparison. Open documents and linked files that only + a write root covers are still compared, and the error names only the requested path. The documents count whether they were open when the run started or were opened while it was paused. A name that differs from it only in letter case throws the same error in a folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is drawn or written, and the resolution is never lowered to @@ -11667,7 +11669,8 @@ With `ids`, `object.rasterize` rasterizes those objects instead of the selection without the objects it replaced. An object inside another listed one is left out, as it is from a selection. An id listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or -in a locked layer or group or on a locked artboard are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +in a locked layer or group or on a locked artboard, and an object that is hidden or in a hidden layer or group, are +refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. The result's From 6a3c6cc7a6773639f0e4dbb739941ed58e7c951f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:05 -0800 Subject: [PATCH 373/533] JavaScript: eval in a default parameter leaves a parameter of a block function's name alone A block function in eval code run from a default parameter's value no longer replaces a parameter of the same name with its variable. The parameters are bindings between the eval code and the function's variable environment, so the function gets no variable (Annex B.3.2.3) and stays in its block. A name that no parameter has still gets the variable. The fault came with b900ea23080, which checks the environments out to the variable environment but not the parameters' environment that a default parameter's eval declares into. --- crates/js/src/es2015_tests.rs | 11 +++++++++++ crates/js/src/interp.rs | 12 ++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1a076c43c1..ec43bfe327 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,17 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { + // A parameter between the eval code and its variable environment has the name, so the block + // function gets no variable (Annex B.3.2.3) and the parameter keeps its value. + truth("function f(a = eval('{ function a() {} }'), b = a) { return typeof b; } f() === 'undefined'"); + truth("function f(a = 1, b = eval('{ function a() {} }'), c = a) { return c + typeof a; } f() === '1number'"); + truth("function f(a = 2, b = eval('{ function a() {} }')) { return a; } f() === 2"); + // A name that no parameter has still gets the variable. + truth("function f(x = eval('{ function a() { return 3; } }'), b = a) { return b(); } f() === 3"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0639d52d25..3784b3a515 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4813,7 +4813,8 @@ impl Interp { /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and /// B.3.3.3, ): no /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` - /// parameter does not count, and on the global object the name is its own property or the + /// parameter does not count, no parameter has the name when the code is in a default + /// parameter's value (B.3.2.3), and on the global object the name is its own property or the /// object is extensible. Each environment passed takes a unit of fuel. fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { let mut cur = Some(env).filter(|&e| e != var_env); @@ -4832,7 +4833,14 @@ impl Interp { .filter(|&o| o != var_env); } if var_env != self.global_env { - return Ok(true); + // Eval code in a default parameter's value declares into the parameters' environment, + // where the parameters are lexical bindings. + self.use_fuel()?; + return match self.heap.env(var_env) { + Some(Env::Decl { bindings, .. }) => Ok(!bindings.get(name).is_some_and(|b| b.lexical)), + Some(Env::Obj { .. }) => Ok(true), + None => internal("environment out of range"), + }; } let global = self.global; Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) From cb98b72a58ba37758dc4896a2b7950e87e477df9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:57 -0800 Subject: [PATCH 374/533] Scripts: fix a run's linked files at its first step A run whose first step is an exact document.open still reads the open documents' linked files then, so a link retargeted while the run is paused gives a later command no read access to the new target. The open itself still gets no linked-file access. --- crates/engine/src/script/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 250fbfe744..db7cddce49 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1349,7 +1349,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value // the open documents; it also reads the files the documents open when the run began link to, as the // person left them. A document a script's command opened gives it no file. let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); - let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { host.linked() }; + // The linked files are fixed at the run's first step, also when that step is an exact open that gets none. + let linked = host.linked(); + let linked = if id == "document.open" && host.disk.borrow().exact { Default::default() } else { linked }; let gate = host.disk.borrow().gate(documents, linked); let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); From f24eff296329cf96f3fe3ae54833a2a84205738d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:11:32 -0800 Subject: [PATCH 375/533] PDF: stream length test helper ignores names ending in obj stream_length took the last "obj" substring in the text as the object header, so a stream dictionary name such as /Tag/obj moved the scan past the outer dictionary and lost its /Length. The keyword now counts only at the start of the text or after PDF white space. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 25 ++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index f3493555c9..fc386ac09c 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -115,10 +115,16 @@ fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) - } /// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary -/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` -/// when it is missing or cannot be read. +/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white +/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its +/// object in `pdf`. `None` when it is missing or cannot be read. fn stream_length(text: &[u8], pdf: &[u8]) -> Option { - let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let from = text + .windows(3) + .enumerate() + .rev() + .find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))) + .map_or(0, |(at, _)| at + 3); let dict = &text[from..]; let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; let mut depth = 1usize; @@ -404,3 +410,16 @@ fn the_transparency_check_skips_strings_and_metadata() { assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); } } + +/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the +/// stream's `/Length` is still read from the outer dictionary. +#[test] +fn the_stream_length_skips_names_that_end_in_obj() { + let text = b"1 0 obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + // NUL is PDF white space, so it may separate the generation number from `obj`. + let text = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); +} From fdbf98d3227ff0e94c27a871257ec15ec07b52d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:14:25 -0800 Subject: [PATCH 376/533] Task bar: More Options rows read in title case, as their commands do The Contextual Task Bar's More Options menu listed "Hide bar", "Pin bar position" and "Reset bar position" in sentence case beside "Bar Actions" and "Reset Bar Actions", and its button read "More options". The Quick Pen toolbar's menu had the same words, although its commands are Pin Toolbar Position and Reset Toolbar Position. Both bars now show VectorCraft's own words over the framework's: More Options, Hide Bar or Hide Toolbar, and Pin and Reset as the titles of the commands they run (window.taskBar.pin and .reset, window.quickPenToolbar.pin and .reset). The grip is named Move Bar or Move Toolbar. Outside English, a word that the language's catalog does not translate keeps the framework's translation. --- crates/ui-egui/src/canvas/quick_pen_bar.rs | 9 +++- crates/ui-egui/src/canvas/task_bar.rs | 36 +++++++++++++- crates/ui-egui/src/tests/quickpenbar.rs | 26 ++++++++-- crates/ui-egui/src/tests/taskbar.rs | 58 +++++++++++++++++++--- 4 files changed, 115 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index 9b2846847e..ec268beb61 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -19,7 +19,7 @@ use craft::ui::canvas_controls::TaskBar; use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{Direction, Env}; +use craft::ui::runtime::env::{Direction, Env, WordsOverride, with_env}; use vectorcraft_tools::quickpen::{self, Stroke as Action}; use super::{Ui, VectorcraftApp, json}; @@ -31,6 +31,13 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { return None; } + let lang = app.ui_language(); + let words = super::task_bar::bar_words(lang, "Move Toolbar", "Hide Toolbar", "window.quickPenToolbar.pin", "window.quickPenToolbar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_quick_pen_bar(app, ui, space)) +} + +/// The Quick Pen toolbar of [`quick_pen_bar`], in a scope with the toolbar's words. +fn shown_quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) if super::tool_adapter::in_gesture(app, ui.ctx()) { return None; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 56657ef670..d2bbdf1f5c 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -1,17 +1,18 @@ use craft::behavior::CanvasView; use craft::behavior::{IconId, Mixed}; use craft::color_ui::ui::{PaintChip, PaintChipSize}; +use craft::i18n::WordSet as _; use craft::theme::{Srgba, Variant}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; -use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; +use craft::ui::canvas_controls::{CanvasControlWords, TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; use vectorcraft_doc::NodeKind; use vectorcraft_doc::text::TextKind; use vectorcraft_geom::{Point, Rect}; @@ -442,12 +443,43 @@ fn more_rows(offer: &Offer) -> Vec { ] } +/// VectorCraft's words for a canvas bar's More Options button, its grip (`grip`) and the rows the framework puts in +/// More Options (`hide`, and the commands `pin` and `reset`, named by their titles), over the framework's words. Outside +/// English, a word the language's catalog does not translate keeps the framework's translation. +pub(crate) fn bar_words(lang: crate::i18n::Lang, grip: &'static str, hide: &'static str, pin: &str, reset: &str) -> WordRows { + fn plain(lang: crate::i18n::Lang, english: &'static str) -> (&'static str, &'static str) { + (english, crate::i18n::tr(lang, english)) + } + fn command(lang: crate::i18n::Lang, id: &str) -> (&'static str, &'static str) { + let english = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map_or("", |c| c.1); + (english, crate::i18n::tr_id(lang, id, english)) + } + let words = [ + ("taskBar.more", plain(lang, "More Options")), + ("taskBar.move", plain(lang, grip)), + ("taskBar.hide", plain(lang, hide)), + ("taskBar.pin", command(lang, pin)), + ("taskBar.reset", command(lang, reset)), + ]; + words + .into_iter() + .filter(|(_, (english, shown))| !english.is_empty() && (lang == crate::i18n::Lang::EN || shown != english)) + .filter_map(|(id, (_, shown))| Some((CanvasControlWords::word(id)?, shown))) + .fold(WordRows::new(), |rows, (word, shown)| rows.row(word, shown)) +} + /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions /// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action /// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the /// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + let words = bar_words(app.ui_language(), "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_task_bar(app, ui, space)) +} + +/// The Contextual Task Bar of [`task_bar`], in a scope with the bar's words. +fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { let offer = offered(app)?; let key = (app.session.active()?.uid, false); let mut local = app.ui.task_bar_place.for_key(key); diff --git a/crates/ui-egui/src/tests/quickpenbar.rs b/crates/ui-egui/src/tests/quickpenbar.rs index 709e2b4822..08e432ab1c 100644 --- a/crates/ui-egui/src/tests/quickpenbar.rs +++ b/crates/ui-egui/src/tests/quickpenbar.rs @@ -1,6 +1,6 @@ //! The Quick Pen toolbar: it shows while the Quick Pen tool is active, its buttons set the tool's //! action and flip the last sharp-corner arc, it follows the drawing beside the path's last point, -//! and its More options menu's commands hide it, pin it and reset its place. +//! and its More Options menu's commands hide it, pin it and reset its place. use egui::{Event, PointerButton, Pos2, Rect, Vec2, vec2}; use serde_json::json; @@ -15,7 +15,7 @@ use crate::VectorcraftApp; const BAR: &str = "Quick Pen"; /// The names of its members. -const MEMBERS: [&str; 5] = ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More options"]; +const MEMBERS: [&str; 5] = ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"]; fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -252,7 +252,7 @@ fn the_toolbar_stays_while_its_handle_drags_far() { let mut app = app(); on_canvas(&mut app, |rig| { assert!(bar(rig).is_some()); - let grip = rig.target("Move bar").expect("the toolbar's handle"); + let grip = rig.target("Move Toolbar").expect("the toolbar's handle"); rig.fx.press(&grip); let from = grip.center(); for k in 1..=6 { @@ -265,7 +265,7 @@ fn the_toolbar_stays_while_its_handle_drags_far() { } /// The handle drags the toolbar, which keeps that offset as it follows the drawing, but not in its -/// resting place with no path being drawn; pinned, it stays put; Reset bar position puts it back beside +/// resting place with no path being drawn; pinned, it stays put; Reset Toolbar Position puts it back beside /// the drawing, unpinned. #[test] fn the_toolbar_drags_pins_and_resets() { @@ -277,7 +277,7 @@ fn the_toolbar_drags_pins_and_resets() { click_doc(rig, 150.0, 100.0); let beside = from_end(rig, 150.0, 100.0); assert!(beside.x > 0.0 && beside.y > 0.0, "beside the end, below it: {beside:?}"); - let grip = rig.target("Move bar").expect("the toolbar's handle"); + let grip = rig.target("Move Toolbar").expect("the toolbar's handle"); let by = vec2(30.0, 40.0); rig.fx.drag(&grip, by); rig.fx.settle(); @@ -313,3 +313,19 @@ fn the_toolbar_drags_pins_and_resets() { assert!((reset - beside).length() < 1.5, "back beside the drawing: {beside:?} then {reset:?}"); }); } + +/// The toolbar's More Options rows read as the commands they run, Hide Toolbar as Window › Quick Pen +/// Toolbar's description names it, and Pin Toolbar Position pins the toolbar. +#[test] +fn more_options_rows_read_as_their_commands() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.click("More Options"); + let pin = super::taskbar::command_title("window.quickPenToolbar.pin"); + for row in ["Hide Toolbar", pin, super::taskbar::command_title("window.quickPenToolbar.reset")] { + assert!(rig.target(row).is_some(), "More Options lists {row}"); + } + rig.click(pin); + assert!(rig.app().ui.quick_pen_bar_place.place.pinned, "Pin Toolbar Position pins the toolbar"); + }); +} diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 1995432740..42b27f59ac 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1501,7 +1501,7 @@ fn shape_tools_show_edit_path_paint_and_properties_after_drawing() { assert!(!offers(&o, what), "{tool}: {what} is left out of {:?}", names_of(&o)); } on_canvas(&mut app, |rig| { - assert!(rig.target("More options").is_some(), "{tool}: More options"); + assert!(rig.target("More Options").is_some(), "{tool}: More Options"); if let Some(heading) = heading { rig.click("Shape Properties"); assert!(rig.has_text(heading), "{tool}: {heading}"); @@ -1570,7 +1570,7 @@ fn the_smooth_tool_shows_fidelity_and_tool_options_for_a_path() { select(&mut app, &[path]); app.run("tool.select", json!({"tool": "smooth"})).unwrap(); on_canvas(&mut app, |rig| { - assert!(rig.target("Tool Options…").is_some() && rig.target("More options").is_some()); + assert!(rig.target("Tool Options…").is_some() && rig.target("More Options").is_some()); let field = rig.field_after("Fidelity:"); rig.enter_value(field, "7"); }); @@ -1967,7 +1967,7 @@ fn more_options_bar_actions_turns_an_action_off_and_on() { show_action(&mut app, "offsetPath", false); assert!(!shows(&offer(&mut app).unwrap(), "Offset Path")); on_canvas(&mut app, |rig| { - rig.click("More options"); + rig.click("More Options"); assert!(rig.target("Bar Actions").is_some(), "More lists Bar Actions"); rig.click("Reset Bar Actions"); }); @@ -1975,6 +1975,52 @@ fn more_options_bar_actions_turns_an_action_off_and_on() { assert!(shows(&offer(&mut app).unwrap(), "Offset Path")); } +/// The title of the command `id`. +pub(crate) fn command_title(id: &str) -> &'static str { + crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.1).unwrap_or_else(|| panic!("no command {id}")) +} + +/// The bar's More Options button, its grip and its menu's rows read in title case, as the rows of the +/// bar's own Bar Actions and the commands Pin and Reset run do, and Pin Bar Position pins the bar. +#[test] +fn more_options_rows_read_as_their_commands() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + on_canvas(&mut app, |rig| { + assert!(rig.target("Move Bar").is_some(), "the grip"); + rig.click("More Options"); + let (pin, reset) = (command_title("window.taskBar.pin"), command_title("window.taskBar.reset")); + for row in ["Hide Bar", pin, reset] { + assert!(rig.target(row).is_some(), "More Options lists {row}"); + } + rig.click(pin); + }); + assert!(app.ui.task_bar_place.place.pinned, "Pin Bar Position pins the bar"); +} + +/// Outside English, a bar's word takes VectorCraft's translation where its catalog has one and the framework's +/// otherwise; a command that does not exist leaves its row to the framework. +#[test] +fn bar_words_keep_the_framework_translation_without_a_catalog_row() { + use crate::i18n::LangExt as _; + use craft::i18n::WordSet as _; + use craft::ui::canvas_controls::CanvasControlWords; + let word = |id: &str| CanvasControlWords::word(id).unwrap_or_else(|| panic!("no word {id}")); + let de = crate::i18n::Lang::from_code("de").unwrap(); + let rows = canvas::task_bar::bar_words(de, "Move Bar", "Hide Bar", "window.taskBar.pin", "no.such.command"); + let german = crate::i18n::tr(de, "More Options"); + assert_ne!(german, "More Options", "the German catalog translates More Options"); + assert_eq!(rows.text(word("taskBar.more")), Some(german)); + assert_eq!(rows.text(word("taskBar.pin")), Some(crate::i18n::tr_id(de, "window.taskBar.pin", command_title("window.taskBar.pin")))); + assert_eq!(rows.text(word("taskBar.move")), None, "no German row for Move Bar"); + assert_eq!(rows.text(word("taskBar.reset")), None, "no such command"); + let english = canvas::task_bar::bar_words(crate::i18n::Lang::EN, "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + assert_eq!(english.text(word("taskBar.move")), Some("Move Bar")); + assert_eq!(english.text(word("taskBar.reset")), Some(command_title("window.taskBar.reset"))); +} + /// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar /// Actions, and with all of them turned off the bar shows none of them but still shows, with More /// options. That covers Connect and Join (both `join`), the actions matched by the tool they switch to @@ -2154,8 +2200,8 @@ fn every_action_the_bar_offers_can_be_turned_off() { let off = offer(&mut app).unwrap_or_else(|| panic!("{case}: the bar still shows")); assert!(off.actions.is_empty() && off.chips.is_empty(), "{case}: every action is off: {:?}", names_of(&off)); assert_eq!(off.listed.len(), o.listed.len(), "{case}: Bar Actions still lists them"); - // The bar still shows, with More options, where Bar Actions turns them back on. - let more = on_canvas(&mut app, |rig| rig.target(BAR).is_some() && rig.target("More options").is_some()); - assert!(more, "{case}: the bar still shows its More options"); + // The bar still shows, with More Options, where Bar Actions turns them back on. + let more = on_canvas(&mut app, |rig| rig.target(BAR).is_some() && rig.target("More Options").is_some()); + assert!(more, "{case}: the bar still shows its More Options"); } } From 26c62f92f47298d6009ed0db502e711bf5ae465f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:17:50 -0800 Subject: [PATCH 377/533] Scripts: a class can extend AsyncFunction and GeneratorFunction `new` on a class that extends `AsyncFunction` or `GeneratorFunction` threw "this built-in cannot be subclassed", because the subclass check listed only `Function` among the function constructors. Both now take the subclass's prototype from `new.target`, as CreateDynamicFunction asks (ECMA-262 2017 section 19.2.1.1.1). `AsyncFunction` also parses its source before it reads `new.target.prototype`, as `Function` and `GeneratorFunction` already did. The check came in with the classes support (#9094) and `AsyncFunction` with async functions (#9131). --- crates/js/src/async_tests.rs | 17 +++++++++++++++++ crates/js/src/class_ops.rs | 18 +++++++++++++----- crates/js/src/generator_tests.rs | 17 +++++++++++++++++ docs/mcp.md | 4 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 50 insertions(+), 8 deletions(-) diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 6438392335..909b191571 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -194,6 +194,23 @@ fn async_function_prototype_has_its_to_string_tag() { assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); } +#[test] +fn a_class_extends_async_function_and_its_instances_inherit_from_the_class() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2017 section + // 19.2.1.1.1). + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + class X extends AF { tag() { return 'x'; } }\n\ + var f = new X('a', 'return a + 1');\n\ + log.push(Object.getPrototypeOf(f) === X.prototype, f instanceof AF, f.tag(), Object.prototype.toString.call(f));\n\ + f(1).then(function (v) { log.push(v); });"; + assert_eq!(log(src), "true true x [object AsyncFunction] 2"); + // The source is parsed before `new.target.prototype` is read. + let order = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + var NT = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') log.push('read'); return t[k]; } });\n\ + try { Reflect.construct(AF, ['(('], NT); } catch (e) { log.push(e instanceof SyntaxError); }"; + assert_eq!(log(order), "true"); +} + #[test] fn an_await_stays_within_the_heap_limit() { // The activation, its two reactions, the derived promise and the suspended frame's bytes all diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 9b6bd6017a..ca038cb0bc 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -172,7 +172,15 @@ impl Interp { let i = &self.intrinsics; Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] .contains(&p) - || i.error_protos.contains(&p)) + || i.error_protos.contains(&p) + || self.dynamic_function_proto(p)) + } + + /// Is `p` the prototype of the functions that `GeneratorFunction` or `AsyncFunction` makes? + /// Both constructors take a subclass's prototype from `new.target` (ECMA-262 2017 sections + /// 25.2.1.1 and 25.5.1.1, through CreateDynamicFunction in section 19.2.1.1.1). + fn dynamic_function_proto(&self, p: ObjId) -> bool { + self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) || self.promises.async_function_proto == Some(p) } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). @@ -367,13 +375,13 @@ impl Interp { return Err(self.type_error("the Promise executor is not a function")); } // `Number`, `String` and `Date` convert arguments before reading `prototype` - // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction` - // convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1). + // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function`, `GeneratorFunction` and + // `AsyncFunction` convert and parse source first (sections 19.2.1.1.1, 25.2.1.1 + // and 25.5.1.1). let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| { - [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) - || self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) + [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) || self.dynamic_function_proto(p) }) }; let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto); diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 551fb4e5e6..19eb0c1edf 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -253,6 +253,23 @@ fn bad_generators_are_syntax_errors() { truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); } +#[test] +fn a_class_extends_generator_function_and_function() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2015 section + // 19.2.1.1.1). + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor;\n\ + class G extends GF { tag() { return 'g'; } }\n\ + var g = new G('yield 7');\n\ + Object.getPrototypeOf(g) === G.prototype && g instanceof GF && g.tag() === 'g' && g().next().value === 7", + ); + truth( + "class F extends Function { tag() { return 'f'; } }\n\ + var f = new F('a', 'return a * 2');\n\ + Object.getPrototypeOf(f) === F.prototype && f.tag() === 'f' && f(3) === 6", + ); +} + #[test] fn realms_without_es2015_have_no_generators() { let es5 = Options::default(); diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..77846aef25 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2838,7 +2838,7 @@ inside a method, accessor or class constructor, and `super(…)` inside a derive arrow function within one; elsewhere, through an indirect `eval` and in a `Function` body they are a `SyntaxError` (https://262.ecma-international.org/6.0/#sec-performeval). A class can extend a class, a function, `null` 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 +`Number`, `Boolean`, `RegExp`, `Date`, the error types, `GeneratorFunction` and `AsyncFunction`. 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. Spread, `for`-`of` and array patterns use the iterator protocol. A loop or pattern left early, by `break`, `return`, a @@ -2898,7 +2898,7 @@ its symbol property is nonwritable, nonenumerable and configurable. A failure during conversion or validation throws before the prototype getter runs. `Reflect.construct(Promise, args, newTarget)` rejects a missing or noncallable executor with `TypeError` before reading `newTarget.prototype`. For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call. -`Function` and `GeneratorFunction` convert and parse their source arguments before reading `newTarget.prototype`. +`Function`, `GeneratorFunction` and `AsyncFunction` convert and parse their source arguments before reading `newTarget.prototype`. A conversion or syntax error throws before that prototype getter runs. `Reflect.has` and an empty-handler proxy's membership checks use host collection indexers, including numeric indices and named items. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..2e2a8b2270 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,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,676 of 4,682 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`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1 when run as scripts. With `module: true`, they run as modules and accept these ECMAScript 2015 forms. `import` and `export` outside a module are syntax errors (the modules entry below). `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. The collector retains tagged-template cache entries only while the site's code is reachable. - - 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`. + - 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`, the error types, `GeneratorFunction` and `AsyncFunction` (neither is a global: a script reaches each through the prototype of a generator or async function, and writing an async function needs `Options::es2017`); 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`. - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string and Symbol property keys. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate key or a value that is neither a string nor a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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`. From 66c71eeb8d5c4a91ced1ecb6f91f640986a17686 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:22:38 -0800 Subject: [PATCH 378/533] JavaScript: modules export async function declarations `export async function f() {}` stopped with "expected a declaration after 'export'", because the module parser checked only for `var`, `function` and lexical declarations. `export default async function` read the function as an expression bound to the default binding, so a named one did not bind its name in the module and was not hoisted. Both forms now parse as async function declarations, as ECMA-262 2017 section 15.2.3 (ExportDeclaration with HoistableDeclaration) gives. Async generators stay syntax errors here, as in a plain declaration. The export forms were missed when #9131 added async functions. --- crates/js/src/parser/module.rs | 50 +++++++++++++++++++++++++++++----- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 3 files changed, 46 insertions(+), 9 deletions(-) diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index 850846abe1..0cfb20cce2 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -266,7 +266,10 @@ impl Parser<'_> { self.bump()?; return self.export_default(info, span).map(Some); } - let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + let exportable = self.at_keyword(Keyword::Var) + || self.at_keyword(Keyword::Function) + || self.at_async_function() + || self.at_lexical_declaration().is_some(); if !exportable { return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); } @@ -287,7 +290,7 @@ impl Parser<'_> { if self.at_keyword(Keyword::Class) { return Err(self.error_at_token(&self.tok, "classes are not supported")); } - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.default_function(); self.leave(); @@ -305,19 +308,22 @@ impl Parser<'_> { Ok(stmt) } - /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of - /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + /// `function name(…) {…}` or `function (…) {…}` after `export default`, either one optionally + /// `async`: a declaration of `name`, or of [`DEFAULT_BINDING`] for a function without one. fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let is_async = self.at_async(); + let async_start = if is_async { Some(self.bump()?.span) } else { None }; let keyword = self.expect_keyword(Keyword::Function)?; - let start = keyword.span; - let generator = self.es2015 && self.eat(Punct::Star)?; + let start = async_start.unwrap_or(keyword.span); + // Async generators (ECMAScript 2018) stay syntax errors, as in a plain declaration. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name()? } else { (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) }; let local = name.0.name.clone(); - let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?; + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?; let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); Ok((stmt, fid, local)) } @@ -410,6 +416,36 @@ mod tests { assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into()))); } + #[test] + fn async_function_declarations_are_exported() { + let options = Options { es2015: true, es2017: true, ..Options::default() }; + let cases = [ + ("export async function f() {}", "f", "f"), + ("export default async function f() {}", "default", "f"), + ("export default async function () {}", "default", crate::ast::DEFAULT_BINDING), + ]; + for (source, export, binding) in cases { + let (program, info) = match parse_module(source, &options) { + Ok(parsed) => parsed, + Err(error) => panic!("{source}: {error:?}"), + }; + assert!( + matches!(info.exports.as_slice(), [crate::ExportEntry::Local { export_name, local, .. }] if export_name == export && local == binding), + "{source}: {:?}", + info.exports + ); + let declared = program.body.iter().any(|&stmt| match program.ast.stmt(stmt) { + Some(crate::ast::Stmt::FunctionDecl(fid)) => program.ast.function(*fid).is_some_and(|f| f.is_async), + _ => false, + }); + assert!(declared, "{source}: an async function declaration"); + } + // A line break after `async` ends the declaration; the export is then an expression. + assert!(parse_module("export async\nfunction f() {}", &options).is_err()); + // Without ES2017, `async` is an identifier and cannot start an exported declaration. + assert!(parse_module("export async function f() {}", &Options { es2015: true, ..Options::default() }).is_err()); + } + #[test] fn module_specifiers_reject_legacy_octal_escapes() { for source in diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..2778885d06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3794,7 +3794,8 @@ and does not read `Symbol.toStringTag`. A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, -async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +async arrow functions and async methods in object literals. A module also exports async function declarations +(`export async function f() {}`, and `export default async function` with or without a name). A call returns a `Promise` that the function's `return` resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..a6f0ea7b10 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1209,7 +1209,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A module exports async function declarations with `export async function`, which requires a name, and `export default async function`, which allows a name to be omitted. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/src/parser/module.rs` (`async_function_declarations_are_exported`), `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 32f4dfd62a307d75596ce8f3e10764686870da2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:29:36 -0800 Subject: [PATCH 379/533] Docs: title-bar Search shows only while the app bar is wide enough In a narrow window the title bar drops Search, so the one-column Tools note now names Help > Search Commands... and its shortcut first. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 41f90515cf..92fad7cdcb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in Help › Search Commands… and its shortcut, and in the title bar while the app bar is wide enough to show it. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. From 7eed206ab0827f9683b15f363559a995f319b04a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:44:55 -0800 Subject: [PATCH 380/533] Recolor Artwork: test that Limit to Library drops a picked swatch it snaps away A swatch picked for a row is kept only while the row's new color is the swatch's color. The new test picks a swatch under Limit to Library whose color the library snaps to another one, and checks that the row takes the snapped color without the swatch. --- crates/ui-egui/src/dialogs/recolor.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 8c0ba7c440..83d815c561 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -4706,6 +4706,23 @@ mod tests { assert_eq!(row_shown(&rc.app(), &adjusted, 0).0, None, "no Tint under a Global Adjust"); } + /// A swatch picked for a row under Limit to Library, whose color the library snaps to another + /// one, is not kept: the row's new color is no longer the swatch's color. + #[test] + fn a_picked_swatch_that_limit_to_library_snaps_away_is_not_kept() { + let mut rc = gray_with_ink(json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}])); + rc.set("limitTo", json!("document")).unwrap(); + rc.settled(); + let before = rc.rows()[0]["to"].clone(); + let odd = Color::rgb(0.13, 0.57, 0.31); + rc.with_dialog(|app, d| with_new_swatch(app, d, 0, odd, Some(json!({"name": "Ink", "library": "document"})))).unwrap(); + let r = &rc.rows()[0]; + assert_ne!(r["to"], before, "the pick gives the row a new color: {r}"); + let to = to_color(r).unwrap_or_else(|| panic!("the row has a new color: {r}")); + assert!(ColorKey::of(&to) != ColorKey::of(&odd), "Limit to Library snaps the color: {r}"); + assert!(r.get(SWATCH).is_none(), "{r}"); + } + /// A row's chip shows its tint while its picked swatch links the art, also while a preview /// changes that swatch; once the swatch is deleted the chip shows the full color the art takes /// and OK recolors with it. A process swatch picked in its place takes the row's swatch and tint From 87e3205d119f12e4ad97185891d7e2b0af593334 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:45:28 -0800 Subject: [PATCH 381/533] Performance: idle frames replay the Color, Gradient, Stroke, Character, Paragraph, Swatches, Layers and Appearance panels These eight panel bodies ran on every frame, and the dock measures each body before it shows it, so an open Color or Gradient panel added about 12 ms to every frame and the others 1 to 7 ms. The dock now shows each of them in a MemoView keyed on what can change the body from outside it: the active document's uid and revision, the documents open, the commands the app and the session have run, the active tool and its options, the fill or stroke in front, a font preview, the fonts and plug-ins installed, the interface language, and the panel settings that dialogs and popovers also edit (Layers Panel Options, the Color Mixer, the Stroke popover, the Swatches popover's browser and the Swatch Libraries button). While a gesture previews its edit, the bodies run in every frame until it ends. A body still runs in every frame the pointer or the keyboard focus is in it. --- crates/ui-egui/src/dock.rs | 330 +++++++++++++++++++++++++- crates/ui-egui/src/panels/swatches.rs | 40 +++- 2 files changed, 365 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d5f31df6c3..9aaf0a2190 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,19 +1,23 @@ //! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or //! flyout panel. -use craft::ui::contract::{Props as _, Scroll, ShowContainer as _}; +use craft::ui::contract::{MemoProps, MemoView, Props as _, Scroll, ShowContainer as _}; use craft::ui::layout_components::Stack; use egui::Ui; use crate::state::DockTab; use crate::{VectorcraftApp, panels}; +/// The panels whose bodies show in a `MemoView` ([`memoized`]): a frame that changes none of what [`BodyInputs`] holds +/// replays the body instead of running it again. +const MEMOIZED: [&str; 8] = ["appearance", "character", "color", "gradient", "layers", "paragraph", "stroke", "swatches"]; + /// Panel `id`'s contents in the room its group gives it; content taller than the group scrolls in /// the group's body. pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { match DockTab::from_id(id) { Some(DockTab::Properties) => panels::properties::show(app, ui), - Some(DockTab::Layers) => panels::layers::show(app, ui), + Some(DockTab::Layers) => memoized(app, ui, id, layers_body), Some(DockTab::Libraries) => panels::libraries(app, ui), None if matches!( id, @@ -36,8 +40,326 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { { // These panels lay out forms. Collection panels own their scrolling viewport // and reserve their own footer outside it. - Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id)); + Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); + } + None => memoized(app, ui, id, icon_panel_body), + } +} + +/// The Layers panel's body. +fn layers_body(p: &mut BodyProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + panels::layers::show(p.app, ui); +} + +/// An icon panel's body. +fn icon_panel_body(p: &mut BodyProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + panels::show_icon_panel(p.app, ui, p.id); +} + +/// Shows panel `id`'s `body`: in a `MemoView` keyed on [`BodyInputs`] for a panel in [`MEMOIZED`], directly for any +/// other. What the body picks it carries out on the app in the run that picks it: a view runs in every pass the pointer +/// or the focus engages it. +fn memoized(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, body: fn(&mut BodyProps<'_>, &mut Ui)) { + #[cfg(test)] + let memoized = MEMOIZED.contains(&id) && !tests::shown_directly(); + #[cfg(not(test))] + let memoized = MEMOIZED.contains(&id); + let inputs = memoized.then(|| BodyInputs::of(app, ui.ctx())); + let mut props = BodyProps { app, id, inputs }; + if !memoized { + body(&mut props, ui); + return; + } + let _ = MemoView::new(("panel-body", id), props, body).shown_out_of_view().show(ui); +} + +/// What a panel body shows: the app, read through [`BodyInputs`]. +#[derive(MemoProps)] +struct BodyProps<'a> { + #[memo_props(covered_by = "inputs", reason = "the bodies read the app only where BodyInputs follows it")] + app: &'a mut VectorcraftApp, + /// The panel's id. + id: &'a str, + /// `None` for a body shown directly. + inputs: Option, +} + +/// What can change a panel body from outside it: the active document's edits, selection and view (its revision), the +/// documents open, every command run (panel menus, shortcuts, other panels and dialogs, and the commands a tool runs on +/// the session), a gesture's previews, the active tool and its +/// options (the Type tool's text selection), the fill or stroke in front, a font preview, the fonts and plug-ins +/// installed, the interface language, and panel settings shared with dialogs and popovers. +#[derive(MemoProps)] +struct BodyInputs { + /// The active document's uid and revision. + document: Option<(u64, u64)>, + /// How many documents are open. + documents: usize, + /// How many commands the app has run. + commands: u64, + /// How many commands the session journaled, and how many times it rewrote its journal: a tool runs its commands + /// on the session without the app (the Gradient tool's click on a stop). + journal: (usize, u64), + /// The active tool. + tool: &'static str, + /// The active tool's options, as JSON. + tool_options: String, + /// Whether the fill is in front of the stroke. + fill_active: bool, + /// The options replaced by the Layers Panel Options dialog's OK callback. + #[memo_props(hash = "the Layers panel's saved display options")] + layers_options: panels::layers::PanelOptions, + /// The Color panel's settings, also edited by the paint chip's Color Mixer popover. + color_options: craft::color_ui::ui::ColorPanelState, + /// Options shared with the Stroke popover, including the last disabled dash pattern. + stroke_options: (bool, bool, Option<(Vec, bool)>), + /// The browser state shared with a paint chip's Swatches popover. + swatches: panels::swatches::BodyInputs, + /// Whether the Swatches footer's library button is pressed. + swatch_libraries_open: bool, + /// Whether a font preview shows in the document. + font_preview: bool, + /// While a gesture previews its edit (a scrubbed field, a drag on the canvas) or a tool computes its edit, the + /// pass: a preview can change what new art takes without a command, so the bodies run in every pass until it ends. + live: Option, + /// The fonts and hyphenation exceptions ([`vectorcraft_text::layout_inputs`]). + fonts: u64, + /// The plug-ins installed. + plugins: u64, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, +} + +impl BodyInputs { + fn of(app: &VectorcraftApp, ctx: &egui::Context) -> Self { + let live = app.session.active().is_some_and(|d| d.interaction.is_some()) || app.session.tool_waiting(); + BodyInputs { + live: live.then(|| ctx.cumulative_pass_nr()), + document: app.session.active().map(|d| (d.uid, d.revision)), + documents: app.session.documents().len(), + commands: app.run_count, + journal: (app.session.journal.len(), app.session.journal.rewrites()), + tool: app.session.tool_id(), + tool_options: app.session.tool_options().to_string(), + fill_active: app.session.fill_active, + layers_options: app.ui.layers_panel.clone(), + color_options: app.ui.color_panel, + stroke_options: (app.ui.stroke_panel.hide_options, app.ui.stroke_panel.scale_linked, app.ui.stroke_panel.dash_last.clone()), + swatches: panels::swatches::BodyInputs::of(app), + swatch_libraries_open: panels::library_panel::any_open::(&app.ui), + font_preview: app.font_preview_owner.is_some(), + fonts: vectorcraft_text::layout_inputs(), + plugins: vectorcraft_plugins::registry::revision(), + lang: crate::i18n::current(), + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::{Cell, RefCell}; + + use egui::Ui; + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; + + thread_local! { + /// How many times this thread ran a panel body. + static BODY_RUNS: Cell = const { Cell::new(0) }; + /// This thread shows the memoized bodies directly, outside their `MemoView`s. + static DIRECT: Cell = const { Cell::new(false) }; + /// The panel [`draw`] shows. + static SHOWN: RefCell<&'static str> = const { RefCell::new("") }; + } + + pub(super) fn count_run() { + BODY_RUNS.with(|n| n.set(n.get() + 1)); + } + + fn runs() -> u64 { + BODY_RUNS.with(Cell::get) + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(Cell::get) + } + + fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + super::panel_body(app, ui, SHOWN.with(|s| *s.borrow())); + } + + /// Panel `id` over a document with a rectangle selected, after its first frames. + fn panel(id: &'static str) -> Panel { + SHOWN.with(|s| *s.borrow_mut() = id); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.frame(); + panel.frame(); + panel + } + + /// How many times `frames` frames run the body. + fn runs_in(panel: &mut Panel, frames: usize) -> u64 { + let before = runs(); + for _ in 0..frames { + panel.frame(); + } + runs() - before + } + + /// Frames that change nothing replay the Color panel's body. A fill set by a command run elsewhere runs it again, + /// and its Hex field shows the new color; so does the fill or stroke brought to the front without a command, as + /// the Contextual Task Bar does. + #[test] + fn idle_frames_replay_the_color_panel() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Color panel"); + panel.app().run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new fill runs the Color panel again"); + assert!(panel.shows_value_with(|v| v.eq_ignore_ascii_case("336699")), "and it shows the fill: {:?}", panel.values()); + assert_eq!(runs_in(&mut panel, 10), 0, "the frames after replay it again"); + let active = panel.app().session.fill_active; + panel.app().session.fill_active = !active; + assert!(runs_in(&mut panel, 2) > 0, "the other well brought to the front runs the Color panel again"); + } + + /// Frames that change nothing replay the Layers panel's body, and a new object, drawn by a command run elsewhere, + /// runs it again and adds a row. + #[test] + fn idle_frames_replay_the_layers_panel() { + let mut panel = panel("layers"); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Layers panel"); + let rows = panel.texts().len(); + panel.app().run("shape.ellipse", json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new object runs the Layers panel again"); + assert!(panel.texts().len() > rows, "and it shows a row for it"); + // The panel runs while it reveals the new row. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "once the row is revealed, the frames after replay it again"); + } + + /// Replacing the options outside app.run, as the dialog's OK callback does, refreshes an idle body. + #[test] + fn layers_options_changed_by_a_dialog_refresh_the_body() { + let mut panel = panel("layers"); + panel.app().run("ui.layersExpand", json!({"open": true})).unwrap(); + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the Layers panel has settled"); + let texts = panel.texts(); + assert!(texts.iter().any(|(text, _)| text.contains("Rectangle")), "the object row shows: {texts:?}"); + let before = super::BodyInputs::of(&panel.app(), panel.ctx()); + let options = panel.app().ui.layers_panel.clone(); + panel.app().ui.layers_panel = crate::panels::layers::PanelOptions { layers_only: true, ..options }; + let after = super::BodyInputs::of(&panel.app(), panel.ctx()); + assert_eq!((after.document, after.commands, after.journal), (before.document, before.commands, before.journal)); + assert!(runs_in(&mut panel, 2) > 0, "the options run the body again without a command"); + assert!(!panel.texts().iter().any(|(text, _)| text.contains("Rectangle")), "Show Layers Only hides the object row"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// The Color Mixer can change display units without changing a paint or running a command. + #[test] + fn color_options_changed_in_a_popover_refresh_the_body() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Color panel has settled"); + let values = panel.values(); + let percent = panel.app().ui.color_panel.rgb_percent; + panel.app().ui.color_panel.rgb_percent = !percent; + assert!(runs_in(&mut panel, 2) > 0, "shared Color Mixer settings run the body again"); + assert_ne!(panel.values(), values, "the RGB fields show the new units"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// A Swatches popover's find field filters the docked browser too, without a command. + #[test] + fn swatches_filter_changed_in_a_popover_refreshes_the_body() { + let mut panel = panel("swatches"); + panel.app().run("swatch.new", json!({"name": "Memo swatch", "color": "#336699"})).unwrap(); + panel.app().ui.swatches_panel.show_find = true; + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the Swatches panel has settled"); + panel.app().ui.swatches_panel.state.browser.filter = "No matching swatch".into(); + assert!(runs_in(&mut panel, 2) > 0, "the shared filter runs the body again"); + assert!(panel.shows_value_with(|v| v == "No matching swatch"), "the find field shows the new filter"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// The Stroke popover changes linked arrowhead scales without a command. + #[test] + fn stroke_options_changed_in_a_popover_refresh_the_body() { + let mut panel = panel("stroke"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Stroke panel has settled"); + let linked = panel.app().ui.stroke_panel.scale_linked; + panel.app().ui.stroke_panel.scale_linked = !linked; + assert!(runs_in(&mut panel, 2) > 0, "shared Stroke popover settings run the body again"); + assert_eq!(panel.toggled("Make all settings the same"), Some(craft::behavior::Mixed::Same(!linked))); + // The link toggle runs the panel while its animation finishes. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// A stop selected by a command the session runs without the app, as the Gradient tool's click on a stop does, + /// runs the Gradient panel again. + #[test] + fn a_stop_selected_on_the_canvas_runs_the_gradient_panel() { + let mut panel = panel("gradient"); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]); + panel.app().run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + panel.app().run("gradient.selectStop", json!({"index": 0})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new fill runs the Gradient panel"); + // The panel runs while the controls the gradient brought in finish their animations. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Gradient panel"); + panel.app().session.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a stop selected through the session runs the Gradient panel again"); + } + + /// A stroke weight scrubbed outside the Stroke panel with nothing selected previews what new art takes, without a + /// command or a new document revision: the panel runs in every frame of the gesture and shows the weight. + #[test] + fn a_weight_scrubbed_elsewhere_runs_the_stroke_panel() { + let mut panel = panel("stroke"); + panel.app().run("select.none", json!({})).unwrap(); + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Stroke panel"); + let scrub = |panel: &mut Panel, weight: f64| { + let mut app = panel.app(); + crate::panels::live_run(&mut app, "Stroke Weight", "stroke.set", json!({"weight": weight}), crate::panels::Live::Dragging); + }; + for weight in [6.0, 7.0] { + scrub(&mut panel, weight); + assert!(runs_in(&mut panel, 1) > 0, "a frame of the gesture at {weight} pt runs the Stroke panel"); + } + assert!(panel.shows_value_with(|v| v.starts_with('7')), "the panel shows the 7 pt weight: {:?}", panel.values()); + } + + /// The texts `id`'s body paints after idle frames, shown in its `MemoView` or, with `direct`, directly. + fn texts(id: &'static str, direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut panel = panel(id); + panel.frame(); + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// A body shown in its `MemoView` lands where the same body shown directly does: a form panel in its scrolling + /// stack, a collection panel that fills its room, and the Layers tab. + #[test] + fn memoized_bodies_land_where_direct_ones_do() { + for id in ["stroke", "gradient", "layers"] { + let direct = texts(id, true); + assert!(!direct.is_empty(), "{id} paints text"); + assert_eq!(texts(id, false), direct, "the memoized {id} body lands where the direct one does"); } - None => panels::show_icon_panel(app, ui, id), } } diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index ca2b52c605..bea36866bb 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -81,7 +81,7 @@ impl View { } /// Swatch-kind filter (Show Swatch Kinds menu). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Kind { #[default] All, @@ -213,6 +213,44 @@ impl Model { } } +/// The browser settings and selection shared with the paint chip popover, without its document caches. +#[derive(MemoProps)] +pub(crate) struct BodyInputs { + view: PresetView, + zoom: f64, + toggled: Vec<(bool, String)>, + filter: String, + selected: Vec, + lead: Option, + anchor: Option, + rename: Option, + #[memo_props(hash = "the Show Swatch Kinds filter")] + kind: Kind, + show_find: bool, +} + +impl BodyInputs { + pub(crate) fn of(app: &VectorcraftApp) -> Self { + let model = &app.ui.swatches_panel; + let state = &model.state; + let browser = &state.browser; + let mut toggled: Vec<_> = browser.toggled.iter().map(|key| (matches!(key, SwatchKey::Group(_)), name_of(key).to_owned())).collect(); + toggled.sort_unstable(); + Self { + view: browser.view, + zoom: browser.zoom, + toggled, + filter: browser.filter.clone(), + selected: state.selection.items.clone(), + lead: state.selection.lead.clone(), + anchor: state.selection.anchor.clone(), + rename: state.rename.clone(), + kind: model.kind, + show_find: model.show_find, + } + } +} + fn name_of(key: &SwatchKey) -> &str { match key { SwatchKey::Group(n) | SwatchKey::Swatch(n) => n, From c34822b2a9b23c3ce5847b38a0bdce465180cb2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:31:31 -0800 Subject: [PATCH 382/533] Print: a Windows paper stays chosen when the new printer lists its name at more sizes Since #10584, a Windows paper's key is its name, or its name and size when the printer lists that name at more than one size. Changing printers looked the chosen paper up by key, so a paper that one printer lists once and the other lists at two sizes fell back to a custom size. The printer change now also finds the new printer's paper by name and size, and keeps it chosen. --- crates/ui-egui/src/dialogs/print.rs | 23 +++++++- crates/ui-egui/src/dialogs/tests_print.rs | 64 +++++++++++++++++++++++ docs/mcp.md | 6 +++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6c76cca2e5..830f113744 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -224,6 +224,13 @@ fn same_size(a: &Paper, b: &Paper) -> bool { (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 } +/// The paper of `papers` with the name and size of `old`. A Windows paper's key is its name, or its name and size when +/// the printer lists that name at more than one size, so one printer's key can differ from another's for the same paper. +fn same_paper<'a>(old: &Paper, papers: &'a [Paper]) -> Option<&'a Paper> { + let name = |p: &Paper| p.key.split('\t').next().unwrap_or_default().to_string(); + papers.iter().find(|p| name(p) == name(old) && same_size(old, p)) +} + /// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { let mut out = settings(fields); @@ -597,7 +604,8 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of - // the same Width and Height. One the new printer lists at the size of one of the dialog's own papers becomes that + // the same Width and Height. One the new printer lists by the same name and size under another key keeps that + // paper. One the new printer lists at the size of one of the dialog's own papers becomes that // paper, the choice the new list offers for it. if papers_changed && media.starts_with(PRINTER_PAPER) @@ -610,6 +618,19 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, fields.set("media", own.id()); return Some((own.id().to_string(), settings(fields))); } + // The new printer lists the same paper under another key: it stays chosen. + // A built-in paper takes its place only the same way up, since the built-in paper prints at its own size. + if let Some(new) = chosen.as_ref().and_then(|old| same_paper(old, &open.papers.1)) + && let Some(id) = match own_media_choice(new, &open.papers.1) { + None => Some(format!("{PRINTER_PAPER}{}", new.key)), + Some(own) => { + own.size().filter(|&(w, h)| (w - new.width).abs() <= 0.5 && (h - new.height).abs() <= 0.5).map(|_| own.id().to_string()) + } + } + { + fields.set("media", id.as_str()); + return Some((id, settings(fields))); + } if let Some(paper) = &chosen { fields.set("width", paper.width); fields.set("height", paper.height); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 35bc78f194..e6f4d17153 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -736,6 +736,70 @@ fn windows_forms_stay_selected_when_queue_enumeration_order_changes() { } } +/// Single lists one paper named Custom; Double lists Custom at that size and at another. +struct SharedNameForms; + +impl PrintService for SharedNameForms { + fn printers(&mut self) -> Vec { + vec![Printer::new("Single").is_default(true), Printer::new("Double"), Printer::new("Sideways")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let out = if printer == "Double" { + "256\tCustom\t400\t600\n256\tCustom\t500\t700\n1\tLetter\t850\t1100\n1\tLetter\t1100\t850\n" + } else if printer == "Sideways" { + "1\tLetter\t1100\t850\n" + } else { + "256\tCustom\t400\t600\n1\tLetter\t850\t1100\n" + }; + Papers::Ready(crate::print::windows_papers(out)) + } +} + +#[test] +fn a_windows_paper_stays_chosen_when_another_printer_lists_its_name_at_more_sizes() { + let services = Services { print: Some(Box::new(SharedNameForms)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:Custom")); + pump(&mut app); + set(&mut app, "printer", json!("Double")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:Custom\t400x600", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(288.0), Some(432.0)), "{f}"); + set(&mut app, "printer", json!("Single")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:Custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(288.0), Some(432.0)), "{f}"); + // Double's upright Letter is Single's only Letter, which the Size list offers as the built-in Letter. + set(&mut app, "printer", json!("Double")); + pump(&mut app); + set(&mut app, "media", json!("printer:Letter\t850x1100")); + pump(&mut app); + set(&mut app, "printer", json!("Single")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "letter", "{f}"); + // Sideways lists the same sideways Letter under a different key. It becomes custom at 792 x 612 points. + set(&mut app, "printer", json!("Double")); + pump(&mut app); + set(&mut app, "media", json!("printer:Letter\t1100x850")); + pump(&mut app); + set(&mut app, "printer", json!("Sideways")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(792.0), Some(612.0)), "{f}"); +} + #[test] fn long_windows_paper_labels_keep_dimensions_and_collision_numbers() { let name = "é".repeat(128); diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..9dbfa024d0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13343,6 +13343,12 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. +After a `printer` change, read `media` again once the new printer's sizes have loaded. Until then, the dialog keeps +the previous printer's paper list. A printer paper the new printer lists by the same name and size stays chosen under +the new printer's `printer:` id or as the built-in paper when the new list offers it. With the same key, the built-in +paper can replace it either way up. With a different key, the built-in paper replaces it only when its orientation +matches; otherwise, it becomes `custom` at its Width and Height. Any other printer paper also becomes `custom` at +its Width and Height. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From e324706fae5fed570f8e20d6389c1eb7276a7c2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:16:57 -0800 Subject: [PATCH 383/533] xtask: census rule reads continue before a call and grouped inline block_on closures A call in a nested for body no longer counts as run when an earlier continue that targets that loop can skip it. A continue inside a nested loop, one whose label names a nearer loop, and a continue token inside a macro or a raw identifier do not skip the call. An inline async closure call wrapped in grouping parentheses and passed as block_on's whole argument (block_on(((async || app.run(c))()))) now counts as run; a callee that only ends in block_on still does not. --- xtask/src/test_lint.rs | 142 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 128 insertions(+), 14 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f05605aabd..6ad7f1c3dc 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2593,18 +2593,25 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } let prefix = b[head..open].trim_ascii(); // A loop label (`'outer: for …`, `'été: for …`) comes before the keyword. - let prefix = prefix + let labeled = prefix .strip_prefix(b"'") .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count())) - .and_then(|(label, rest)| rest.trim_ascii_start().strip_prefix(b":").filter(|r| !label.is_empty() && r.first() != Some(&b':'))) - .map_or(prefix, <[u8]>::trim_ascii_start); + .and_then(|(label, rest)| { + rest.trim_ascii_start() + .strip_prefix(b":") + .filter(|r| !label.is_empty() && r.first() != Some(&b':')) + .map(|r| (label, r.trim_ascii_start())) + }); + let label = labeled.map(|(label, _)| label); + let prefix = labeled.map_or(prefix, |(_, rest)| rest); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { return false; } - } else if nested_for && literal_source_yields(prefix) != Some(true) { - // A nested `for` body runs only when its source yields an item. + } else if nested_for && (literal_source_yields(prefix) != Some(true) || skips_rest_of_iteration(b, open, start, label)) { + // A nested `for` body runs only when its source yields an item, and its later statements + // only when no earlier `continue` skips them. return false; } else if !prefix.ends_with(b"|") && !nested_for @@ -2749,15 +2756,24 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that - // never runs. - let outer = (stmt..open.saturating_sub(1)).rev().find(|&i| !b[i].is_ascii_whitespace()); - let blocked = matching(b, call).is_some_and(|call_close| { - outer.is_some_and(|o| { - b[o] == b'(' - && !b[stmt..o].contains(&b'|') - && ends_with_block_on(&b[..o]) - && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) - }) + // never runs. Grouping parentheses around the call (`block_on(((async || …)()))`) are skipped. + let before = |end: usize| (stmt..end).rev().find(|&i| !b[i].is_ascii_whitespace()); + let blocked = matching(b, call).is_some_and(|mut inner| { + let mut outer = before(open.saturating_sub(1)); + loop { + let Some((o, c)) = outer.filter(|&o| b[o] == b'(' && !b[stmt..o].contains(&b'|')).and_then(|o| matching(b, o).map(|c| (o, c))) else { + break false; + }; + let rest = b[inner + 1..c].trim_ascii(); + if ends_with_block_on(&b[..o]) { + break matches!(rest, b"" | b","); + } + if !rest.is_empty() { + break false; + } + inner = c; + outer = before(o); + } }); if !asynchronous || blocked { return true; @@ -2769,6 +2785,64 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) } +/// Whether a `continue` in the loop body that opens at `open` comes before `start` and skips the +/// rest of that loop's iteration: one with the loop's `label`, or one without a label that is not +/// inside a nested `for`, `while` or `loop` body. A labeled `continue` inside a nested loop with the +/// same label targets that nested loop. Only a `continue` that starts an expression counts, not one +/// inside a macro's tokens (`stringify!(continue)`) or a raw identifier (`r#continue`). A `break` in +/// the body already rules out a census hit, so only `continue` is read here. +fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[u8]>) -> bool { + let label_at = |at: usize| { + let name = &b[at..]; + &name[..name.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count()] + }; + // The labels of the nested loops whose bodies hold `at` (`None` for a loop without a label). + let nested_loops = |at: usize| -> Vec> { + (open + 1..at) + .filter(|&k| b[k] == b'{' && matching(b, k).is_some_and(|close| at < close)) + .filter_map(|k| { + // Groups in the head (`for _ in (0..2).filter(|_| { true })`) are skipped whole. + let mut head_start = k; + while head_start > open + 1 { + head_start -= 1; + match b[head_start] { + b')' | b']' => head_start = (open + 1..head_start).rev().find(|&i| matching(b, i) == Some(head_start))?, + b';' | b'{' | b'}' => { + head_start += 1; + break; + } + _ => {} + } + } + let lead = k - b[head_start..k].trim_ascii_start().len(); + let head = b[lead..k].trim_ascii_end(); + // A loop label (`'inner: for …`) comes before the keyword. + let (inner, head) = match head.strip_prefix(b"'") { + Some(rest) => { + let name = label_at(lead + 1); + let after = rest[name.len()..].trim_ascii_start().strip_prefix(b":")?; + (Some(name), after.trim_ascii_start()) + } + None => (None, head), + }; + [b"for".as_slice(), b"while", b"loop"].iter().any(|kw| words(head, kw, 0, head.len()).first() == Some(&0)).then_some(inner) + }) + .collect() + }; + words(b, b"continue", open + 1, start).into_iter().any(|at| { + if !b[open + 1..at].trim_ascii_end().last().is_some_and(|&c| matches!(c, b'{' | b'}' | b';' | b'>')) { + return false; + } + let nested = nested_loops(at); + let quote = skip_ws(b, at + b"continue".len()); + if b.get(quote) == Some(&b'\'') { + let name = label_at(quote + 1); + return label == Some(name) && !nested.contains(&Some(name)); + } + nested.is_empty() + }) +} + /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether /// the closure is async. fn strip_closure_keywords(head: &str) -> (&str, bool) { @@ -10431,6 +10505,46 @@ mod tests { ); assert_eq!(census("for _ in &[1] { app.run(c); } assert!(menu(c).is_some());"), [], "a borrowed array literal with one item runs its body"); assert_eq!(census("'inner: for _ in (&[1]) { app.run(c); } assert!(menu(c).is_some());"), [], "a parenthesized borrowed array runs its body"); + assert_eq!( + census("for _ in &[1] { if skip { continue; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "an earlier continue may skip the call" + ); + assert_eq!( + census("'outer: for _ in 0..3 { for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in a nested loop may skip the call" + ); + assert_eq!( + census("for _ in &[1] { for _ in 0..2 { if skip { continue; } } app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue that targets a nested loop does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { for _ in (0..2).filter(|_| { true }) { continue; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a nested loop with a block in its head holds its continue" + ); + assert_eq!( + census("'outer: for _ in 0..3 { 'outer: for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue targets the nearest loop with that label" + ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!(continue); let r#continue = 1; app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a macro or a raw identifier does not skip the call" + ); + assert_eq!( + census("block_on(((async || app.run(c))())); assert!(menu(c).is_some());"), + [], + "an inline async closure call in grouping parentheses passed to block_on runs" + ); + assert_eq!( + census("discard_block_on(((async || app.run(c))())); assert!(menu(c).is_some());"), + [(2, "census")], + "an inline async closure call passed to a callee that only ends in block_on does not run" + ); assert_eq!( census("let run = async || app.run(c); block_on(run().into_stream().take(0).count()); assert!(menu(c).is_some());"), [(2, "census")], From 1133208ba3acb835f58ef4019c041b39b50f1577 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:28:21 -0800 Subject: [PATCH 384/533] Plug-ins: a failed script run gives back the events its opens pushed out When a script run failed, the document.opened events its commands queued were dropped, but the events those opens had pushed out of the waiting queue (a document.saved, for example) were not put back, so plug-ins never received them. A failed command.batch already put them back. Each pushed-out event now records which event pushed it out, and the running script's opens are tracked by their queue sequence, so both rollbacks share one path. A delivery between script slices keeps the events the script's opens pushed out until the run ends, and a full store of pushed-out events no longer loses that link when it drops an open. The fault came with 01ec822509d. --- crates/engine/src/plugin_events.rs | 112 ++++++++++++++++++++++------- 1 file changed, 88 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 7a60028afc..ac6fafae24 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -86,8 +86,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, - /// The event this enqueue pushed out of the waiting queue. - displaced: Option, + /// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether + /// that event was a `document.opened`. + pushed_out_by: Option<(u64, bool)>, /// Queued by a command of the running script, whose run has not ended yet /// ([`Session::plugin_events_script_ended`]). by_script: bool, @@ -162,6 +163,8 @@ pub struct PluginEvents { /// The events dropped from `pending` since the last delivery, oldest first, which /// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room. evicted: VecDeque, + /// The [`Pending::seq`] of each `document.opened` the running script's commands queued. + script_opens: HashSet, /// How many events have been queued as their own entry. queued: u64, dispatching: bool, @@ -223,11 +226,10 @@ impl PluginEvents { } return; } - let mut displaced = None; if self.pending.len() >= MAX_PENDING - && let Some(dropped) = self.pending.pop_front() + && let Some(mut dropped) = self.pending.pop_front() { - displaced = Some(dropped.seq); + dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened)); log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); // Kept until the next delivery, in case a rollback frees room for it again. // When that store is full, an open goes first, since only opens are rolled back. @@ -238,10 +240,27 @@ impl PluginEvents { self.evicted.push_back(dropped); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false }); self.queued += 1; } + /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` + /// picks. The events those opens pushed out of the waiting queue return in their original + /// order, ahead of the events still waiting, while there is room. + fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) { + let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); + self.pending.retain(|p| !dropped(p)); + self.evicted.retain(|p| !dropped(p)); + let back = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq)); + while self.pending.len() < MAX_PENDING + && let Some(at) = self.evicted.iter().rposition(back) + && let Some(mut p) = self.evicted.remove(at) + { + p.pushed_out_by = None; + self.pending.push_front(p); + } + } + fn notice(&mut self, n: Notice) { if self.notices.len() >= MAX_NOTICES { self.notices.pop_front(); @@ -362,6 +381,9 @@ impl Session { && let Some(p) = self.plugin_events.pending.back_mut() { p.by_script = true; + if event == Event::DocumentOpened { + self.plugin_events.script_opens.insert(p.seq); + } } } @@ -370,12 +392,13 @@ impl Session { /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since /// the documents they opened were discarded with its working copy. Its saves stay, since the /// files they wrote stay written, and so do the events of documents a frontend opened while the - /// run was paused. The next delivery gives what is left in the order it was queued. + /// run was paused. Events those opens pushed out of the waiting queue come back, as after + /// [`Session::forget_plugin_opens_since`]. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { let events = &mut self.plugin_events; + let opens = std::mem::take(&mut events.script_opens); if !kept { - events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); - events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + events.drop_opens(|seq| opens.contains(&seq)); } for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { p.by_script = false; @@ -389,21 +412,9 @@ impl Session { /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The - /// saves stay, since the files they wrote stay written. - /// Events displaced by those opens return in their original order, ahead of the events still - /// waiting, while there is room. + /// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]). pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { - let events = &mut self.plugin_events; - let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark; - let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect(); - events.pending.retain(|p| !undone(p)); - events.evicted.retain(|p| !undone(p)); - while events.pending.len() < MAX_PENDING - && let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq)) - && let Some(p) = events.evicted.remove(at) - { - events.pending.push_front(p); - } + self.plugin_events.drop_opens(|seq| seq >= mark); } /// Compares each open document with how the last check saw it and queues the events its changes @@ -489,7 +500,11 @@ impl Session { } let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; - self.plugin_events.evicted.clear(); + // Events pushed out by the opens of a running script stay until its run ends, which puts + // them back if the run fails. + let events = &mut self.plugin_events; + let opens = &events.script_opens; + events.evicted.retain(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq))); // A handler's calls are checked as calls from outside, also when the command that ended // played saved steps ([`Session::replay`] puts its flag back only after this delivery). let replaying = self.set_replaying(false); @@ -854,6 +869,55 @@ mod tests { ); } + #[test] + fn a_failed_script_run_brings_back_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + // Enough opens to fill the store of pushed-out events, which then drops opens first. + for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED); + assert_eq!(s.plugin_events.pending.len(), MAX_PENDING); + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out"); + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + #[test] + fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + // A save a frontend queued while the run is paused pushes out the first open. + s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]); + s.deliver_plugin_events(); + assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + /// Queues a `document.opened` as a command of a running script does. + fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) { + s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]); + if let Some(p) = s.plugin_events.pending.back_mut() { + p.by_script = true; + s.plugin_events.script_opens.insert(p.seq); + } + } + #[test] fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() { let mut s = Session::new(); From 08a29802b824eef1c25a0d62d657dacdac407cc2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:38:44 -0800 Subject: [PATCH 385/533] Scripts: placing or relinking an image reads its file once PlacedItem.file and PlacedItem.relink() ran file.place.info on the file to check that it held an image, then file.place or links.relink read and decoded it again. The image check now runs inside file.place and links.relink while a script places or relinks an image: a file in no image format is refused before the document changes, with "The file is not an image", and a damaged image keeps its own error. The double read came in with fed96731e24 (#9077). A test counts the engine's file reads and fails with 2 reads on main. --- crates/engine/src/cmd/fileio.rs | 3 ++ crates/engine/src/cmd/fileio/access.rs | 8 ++++ crates/engine/src/cmd/fileio/load.rs | 14 +++++++ crates/engine/src/cmd/links.rs | 12 +++++- crates/engine/src/cmd/place.rs | 9 +++++ crates/engine/src/lib.rs | 4 ++ crates/engine/src/script/dom/images.rs | 28 +++++++++----- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 39 ++++++++++++++++++++ 9 files changed, 107 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 38654bb8ba..2e7de1b4aa 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; +pub(crate) use load::is_raster_image; pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ @@ -146,6 +147,8 @@ mod commands; mod export_names; mod formats; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::FILES_READ; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 649e8944f8..0a4cf89b18 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -283,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX #[cfg(not(target_arch = "wasm32"))] pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// The paths [`read_file`] has read on this thread, in order. + pub(crate) static FILES_READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { use std::io::Read; may_read(path)?; + #[cfg(test)] + FILES_READ.with(|r| r.borrow_mut().push(path.to_string())); // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index b0a6aab5fc..6424c7c987 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { (drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size")) } +/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of +/// it can be decoded. +pub(crate) fn is_raster_image(bytes: &[u8]) -> bool { + super::pcraftread::is_pcraft(bytes) + || psdread::is_psd(bytes) + || jxlread::is_jxl(bytes) + || super::jp2read::is_jpeg2000(bytes) + || super::heifread::is_heif(bytes) + || super::pxrread::is_pxr(bytes) + || craft_image_codecs::detect(bytes).is_some() + || super::tgaread::is_targa(bytes) + || super::pcxread::is_pcx(bytes) +} + /// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index afc1a85f3d..dbff645ca2 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2339,7 +2339,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { + None + } else { + Some(linked_image(&bytes, Some(&path)).map_err(|e| { + // A file in no image format; a damaged image keeps its own error. + if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) { + s.image_only.set(Some(false)); + } + bad(C, format!("{path}: {e}")) + })?) + }; // A copy beside the document would point at plate files it can't find there. if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index ba2b523f62..949b470263 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result { Some(read) => read, None => prepare(s, p)?.read()?, }; + let image = match read.loaded.art { + Art::Image(..) => read.loaded.link.is_some(), + Art::Dcs(_) => true, + _ => false, + }; + if s.image_only.get().is_some() && !image { + s.image_only.set(Some(false)); + return Err(bad(PLACE, "the file is not an image")); + } apply(s, read) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 145954340a..6558a5b9d5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -318,6 +318,10 @@ pub struct Session { /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, + /// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or + /// `links.relink` refuses a file that holds no image before the document changes, setting it to + /// `Some(false)`; `None` otherwise. + pub(crate) image_only: std::cell::Cell>, /// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which /// the command loads the place cursor with instead of reading them; `None` otherwise. pub(crate) queue_hand_off: Option, diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 29adc7ad6a..33271bb456 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -299,8 +299,8 @@ fn may_read(h: &Host, path: &str) -> bool { /// The real path of the `File` `d` gives as an image to place or relink: one the script may read /// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of -/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no -/// error names the path. +/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path. +/// What the file holds is checked by the command that places or relinks it, which reads it once. fn image_path(h: &Host, d: &Data, what: &str) -> Result { let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; if path.len() > super::super::files::MAX_PATH_CHARS { @@ -318,13 +318,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result { if meta.len() > MAX_PLACED_BYTES { return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); } - let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); - // What the file holds, read the way `file.place` reads it, before the document changes. - let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?; - if field(&info, "pixelWidth").is_none() { - return Err(HostError::Error(NOT_AN_IMAGE.into())); + Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) +} + +/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink` +/// refusing a file that holds no image before the document changes: that refusal is +/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check +/// and for the image it places. +fn image_only(h: &Host, f: impl FnOnce(&Host) -> Result) -> Result { + let kept = h.session.borrow().image_only.replace(Some(true)); + let r = f(h); + let refused = h.session.borrow().image_only.replace(kept) == Some(false); + match r { + Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())), + r => r, } - Ok(path) } // ---- PlacedItem ---- @@ -394,7 +402,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { // The placement and its check run under one savepoint, so an error after the place leaves // no linked image behind. let id = super::atomically(h, |h| { - let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?; let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = @@ -411,7 +419,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { fn placed_relink(h: &Host, a: &[Data]) -> Answer { let item = this_of(h, a, "PlacedItem")?; let path = image_path(h, arg(a, 1), "relink's file")?; - edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?; + image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 15192a6593..938edca5f1 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -140,6 +140,7 @@ impl Session { composite_names_registered: HashSet::new(), reading: false, place_hand_off: None, + image_only: std::cell::Cell::new(None), queue_hand_off: None, place_queue_roots: None, place_queue_loads: 0, diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 4103ab0bff..681a386f28 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -287,6 +287,45 @@ fn a_file_that_is_not_an_image_is_refused_before_placing() { let _ = std::fs::remove_dir_all(base); } +/// How many times the engine read the file at `path` on this thread since the last call. +#[cfg(not(target_arch = "wasm32"))] +fn reads_of(path: &Path) -> usize { + let path = path.to_string_lossy(); + crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_or_relinking_from_a_script_reads_the_file_once() { + let base = folder("read-once"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + reads_of(&a); + log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a))); + assert_eq!(reads_of(&a), 1, "placing reads the file once"); + log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b))); + assert_eq!(reads_of(&b), 1, "relinking reads the file once"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() { + let base = folder("relink-text"); + let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let before = undo_steps(&s); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(¬es))); + assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_items_add_is_bounded() { let base = folder("pending"); From 09763b3a6cb69a9d6a6e55c531a027c91b906ebf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:45:36 -0800 Subject: [PATCH 386/533] Plug-ins: keep event order and the queue limit when a failed run gives events back A rollback now gives back every event pushed out after the first one an undone open pushed out, newest first while there is room, so the waiting queue keeps the newest events as if the opens had never been queued. Between script slices, a frontend event waits behind an older frontend event that a failed run can still give back, and the record of the script's opens forgets those no event refers to any more. --- crates/engine/src/plugin_events.rs | 99 +++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index ac6fafae24..4a85763667 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -242,6 +242,7 @@ impl PluginEvents { let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false }); self.queued += 1; + self.prune_script_opens(); } /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` @@ -251,14 +252,25 @@ impl PluginEvents { let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); self.pending.retain(|p| !dropped(p)); self.evicted.retain(|p| !dropped(p)); - let back = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq)); + let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min(); while self.pending.len() < MAX_PENDING - && let Some(at) = self.evicted.iter().rposition(back) + && let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq)) && let Some(mut p) = self.evicted.remove(at) { p.pushed_out_by = None; self.pending.push_front(p); } + self.prune_script_opens(); + } + + /// Forgets the running script's opens that no waiting or pushed-out event refers to. + fn prune_script_opens(&mut self) { + if self.script_opens.is_empty() { + return; + } + let referenced: HashSet = + self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect(); + self.script_opens.retain(|seq| referenced.contains(seq)); } fn notice(&mut self, n: Notice) { @@ -504,7 +516,15 @@ impl Session { // them back if the run fails. let events = &mut self.plugin_events; let opens = &events.script_opens; - events.evicted.retain(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq))); + let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq)); + let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min(); + events.evicted.retain(|p| { + restorable(p) + || (first.is_some_and(|seq| p.seq >= seq) + && (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r)))) + }); + let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min(); + events.prune_script_opens(); // A handler's calls are checked as calls from outside, also when the command that ended // played saved steps ([`Session::replay`] puts its flag back only after this delivery). let replaying = self.set_replaying(false); @@ -527,6 +547,11 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } + p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event))); + if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) { + held.push_back(p); + continue; + } let mut served = 0; for (i, (r, reasons)) in p.to.iter().enumerate() { let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { @@ -562,8 +587,10 @@ impl Session { self.depth = depth; self.set_replaying(replaying); self.plugin_events.dispatching = false; + self.plugin_events.prune_script_opens(); self.plugin_events.pending.iter().any(|p| { !p.by_script + && frontend_barrier.is_none_or(|seq| p.seq < seq) && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) @@ -888,6 +915,72 @@ mod tests { assert_eq!(s.plugin_events.pending, before); } + #[test] + fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + queue_script_open(&mut s, 100, &r); + s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]); + s.plugin_events.pending.back_mut().unwrap().by_script = true; + s.plugin_events_script_ended(false); + let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect(); + let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect(); + assert_eq!(saves, expected); + } + + #[test] + fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() { + use vectorcraft_plugins::wat as tpl; + + let mut s = Session::new(); + let manifest = concat!( + r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#, + r#""events":["document.opened","document.saved"]}"# + ); + let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap()); + let r = recipient(&plugin); + s.plugin_events.test_subscribers = Some(vec![plugin]); + s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]); + assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame"); + assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + s.deliver_plugin_events(); + let given: Vec = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect(); + assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]); + } + + #[test] + fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 0..2 * MAX_PENDING as u64 { + let mark = s.plugin_events_mark(); + queue_script_open(&mut s, uid, &r); + s.forget_plugin_opens_since(mark); + assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references"); + } + for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 { + queue_script_open(&mut s, uid, &r); + let events = &s.plugin_events; + assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len())); + } + s.plugin_events_script_ended(false); + assert!(s.plugin_events.pending.is_empty()); + assert!(s.plugin_events.evicted.is_empty()); + assert!(s.plugin_events.script_opens.is_empty()); + } + #[test] fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() { let mut s = Session::new(); From 15d11beb8369075c7331edcf2f2b912559d862cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:48:30 -0800 Subject: [PATCH 387/533] Print: a second scheduler on a loopback port supplies its own paper sizes A `CUPS_SERVER` or `ServerName` of `localhost`, `127.0.0.1` or `::1` counts as this machine's scheduler only with no port or port 631. On another port (a second CUPS instance) the dialog no longer reads `/etc/cups/ppd`, whose queues belong to the default scheduler, and asks `lpoptions` and IPP instead. When the named server is one of CUPS's own domain sockets and neither the PPD nor `lpoptions` lists sizes, the IPP lookup asks `localhost` on the IPP default port, as it already does when no server is named. `ipptool` rejects a URI whose host is a socket path (`httpSeparateURI` in CUPS's `cups/http-support.c`), so another socket path is not asked. --- apps/vectorcraft/src/printing.rs | 61 +++++++++++++++++++++++++------- docs/mcp.md | 5 +-- 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f77d74610c..4eb39067a0 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -199,11 +199,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = named.or_else(|| { - let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) - }); + let server = ipp_server(named, |s| std::path::Path::new(s).exists()); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -235,6 +231,24 @@ mod system { output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. + #[cfg(not(windows))] + const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server + /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default + /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local + /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job + /// does not go to. + /// + /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri + #[cfg(not(windows))] + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + match named { + Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) => Some(server), + None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), + } + } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. @@ -255,7 +269,8 @@ mod system { }) } /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback + /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. #[cfg(not(windows))] pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { let Some(server) = server.map(str::trim) else { return true }; @@ -264,14 +279,15 @@ mod system { } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); - let host = if let Some(rest) = server.strip_prefix('[') { - rest.split_once(']').map_or(rest, |(host, _)| host) + let (host, port) = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { - server.split_once(':').map_or(server, |(host, _)| host) + server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) } else { - server + (server, None) }; - host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; + loopback && port.is_none_or(|port| port.trim() == "631") } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is @@ -588,7 +604,19 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, scheduler_is_local}; + use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + + #[test] + fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); + assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket), None); + assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + } #[test] fn only_a_scheduler_on_this_machine_counts_as_local() { @@ -597,10 +625,13 @@ mod client_conf_tests { Some("/run/cups/cups.sock"), Some("localhost"), Some("LocalHost:631"), - Some("127.0.0.1:8631"), + Some("localhost:631"), + Some("127.0.0.1:631"), Some("::1"), Some("[::1]:631"), + Some("[::1]"), Some("localhost/version=1.1"), + Some("localhost:631/version=1.1"), ] { assert!(scheduler_is_local(local), "{local:?}"); } @@ -612,6 +643,10 @@ mod client_conf_tests { "2001:db8::1", "localhost.example.com", "print.example.com:631/version=1.1", + "localhost:8631", + "127.0.0.1:8631", + "[::1]:8631", + "localhost:8631/version=1.1", ] { assert!(!scheduler_is_local(Some(remote)), "{remote}"); } diff --git a/docs/mcp.md b/docs/mcp.md index 8a0b9f86ee..250806a975 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13344,10 +13344,11 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, -`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is -asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the +server is asked as `localhost` on port 631; another socket path is not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. From 96820e7c2b2beb6890a25406e50e610706d9d4cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:56:31 -0800 Subject: [PATCH 388/533] Tests: the Quick Pen toolbar drag test checks where the toolbar ends up The test-lint step failed on this branch because renaming the handle to "Move Toolbar" put the_toolbar_stays_while_its_handle_drags_far in the changed lines, and its assertions only checked that the toolbar existed. The test now checks that after the release the toolbar keeps its size and has moved. --- crates/ui-egui/src/tests/quickpenbar.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/tests/quickpenbar.rs b/crates/ui-egui/src/tests/quickpenbar.rs index 08e432ab1c..841cc76d18 100644 --- a/crates/ui-egui/src/tests/quickpenbar.rs +++ b/crates/ui-egui/src/tests/quickpenbar.rs @@ -251,7 +251,7 @@ fn the_toolbar_goes_to_the_other_side_where_it_runs_off_the_canvas() { fn the_toolbar_stays_while_its_handle_drags_far() { let mut app = app(); on_canvas(&mut app, |rig| { - assert!(bar(rig).is_some()); + let before = bar(rig).expect("the toolbar is shown"); let grip = rig.target("Move Toolbar").expect("the toolbar's handle"); rig.fx.press(&grip); let from = grip.center(); @@ -260,7 +260,9 @@ fn the_toolbar_stays_while_its_handle_drags_far() { assert!(rig.fx.by_label(BAR).is_some(), "shown at step {k}"); } rig.fx.release_at(from + vec2(-120.0, -180.0)); - assert!(bar(rig).is_some()); + let after = bar(rig).expect("the toolbar stays after the release"); + assert_eq!(after.size(), before.size(), "the drag keeps the toolbar's size"); + assert_ne!(after.min, before.min, "the drag moved the toolbar"); }); } From 2c48d977f965368fdccebdbc2bcadc0fa66494d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:59:38 -0800 Subject: [PATCH 389/533] Recolor Artwork: check the row count before the randomize swatch check The gate's test-lint step failed on the new test: its assert!(...all(...)) over the randomized map would pass on an empty map. The test now asserts that both rows come back first. --- crates/engine/src/tests/recolor.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 3c8da0536a..3d8687edd7 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -928,7 +928,9 @@ fn a_rows_swatch_links_its_art_without_limit_to_library() { assert_eq!(ink["swatch"], json!({"name": "Ink", "library": "document"}), "{r}"); assert!(green.get("swatch").is_none(), "{r}"); let r = run(&mut s, "recolor.randomize", json!({"map": two, "order": false, "saturationBrightness": true, "seed": 3})); - assert!(r["map"].as_array().unwrap().iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}"); + let rows = r["map"].as_array().unwrap(); + assert_eq!(rows.len(), 2, "{r}"); + assert!(rows.iter().all(|r| r.get("swatch").is_none()), "a changed color drops its swatch: {r}"); } } From 1f6ad294ab42d22f47dd52156dd897be15ef3f3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:07:22 -0800 Subject: [PATCH 390/533] Menus: a click on the canvas or a key the canvas takes keeps the menu states The menu model rebuilt every row's state on each frame with a pointer press or release or a key press. A plain click on the canvas therefore rebuilt it twice (press and release), and so did every Space, Shift or tool key. Several row checks walk the selection, so one rebuild took 4.5 ms with one object selected and 60 ms with 6,000 (dev profile). A press that lands on the canvas, with no other layer over it, and a key while the canvas or nothing has the focus no longer force a rebuild. Those inputs change the rows only through the document, the tool or a command, or through state the key now reads: the tool, whether the panels show (Tab), the open flyout and the dock layout, the current window, the view's rotation and active artboard, and whether a dialog is open or a shortcut is being recorded. Clicks away from the canvas, and keys that a text field, a dialog or a panel control takes, still rebuild once. While the Type tool edits text, clicks and keys on the canvas also still rebuild, since they move the caret. Tests: - canvas::tests::a_canvas_click_that_changes_nothing_keeps_the_menus - canvas::tests::a_selection_move_rebuilds_the_menus_for_its_release_only - canvas::tests::a_click_or_a_key_in_edited_text_rebuilds_the_menus - menus::tests::a_key_press_a_dialog_takes_rebuilds_the_menus_once - menus::tests::hiding_the_panels_unchecks_the_window_rows - menus::tests::a_view_turned_on_the_canvas_moves_the_rotate_view_check - menus::tests::closing_a_panel_flyout_unchecks_its_window_row - panel_docking::tests::a_key_a_panel_control_takes_rebuilds_the_menus --- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/caches.rs | 6 ++ crates/ui-egui/src/canvas/tests.rs | 91 ++++++++++++++---- crates/ui-egui/src/canvas/tool_adapter.rs | 11 +++ crates/ui-egui/src/menus/model.rs | 45 ++++++--- crates/ui-egui/src/menus/native.rs | 5 +- crates/ui-egui/src/menus/tests.rs | 111 ++++++++++++++++++++-- crates/ui-egui/src/panel_docking/tests.rs | 14 +++ 8 files changed, 245 insertions(+), 40 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 571a355846..efb429f73d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -167,6 +167,8 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + pressed_at: None, + keys_at: None, host_caps_lock: None, committed_preview: false, panes: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 58b2e6c803..6dcec22bff 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -129,6 +129,12 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The input time of the last pass whose pointer button events all landed on a canvas, with no other layer over it: + /// the menus' state key leaves such a press out (`menus::model::last_press`). + pub pressed_at: Option, + /// The input time of the last pass in which the canvas or nothing had the focus, so that the canvas or the app's + /// shortcuts took its keys: the menus' state key leaves those keys out (`menus::model::last_press`). + pub keys_at: Option, /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the /// next reading; `None` before the first pass. pub host_caps_lock: Option, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 41d0e93837..df0d8fc387 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -897,13 +897,12 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); } -/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its -/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the -/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts -/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new -/// app, at most 20 times, until the other catalogs held still through it. -#[test] -fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { +/// How many times each frame of `steps` builds the menus' states again, with the Selection tool and a 60 × 30 +/// rectangle at (100, 100) selected and the pointer resting over its middle (`steps` gets that point). The menus are +/// also built again when a process-wide catalog changes, so the fonts and plug-ins are held steady against tests +/// running alongside for the whole run, and the steps run again on a new app, at most 20 times, until the other +/// catalogs held still through them. +fn selection_tool_rebuilds(steps: impl Fn(Pos2, &craft::behavior::CanvasView) -> Vec>) -> (VectorcraftApp, Vec) { let fonts = vectorcraft_text::FontDb::global(); let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); let catalogs = || { @@ -920,33 +919,59 @@ fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap(); app.select_tool("selection"); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); - let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0))); + let from = xf.to_screen(Point::new(130.0, 115.0)); app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); for _ in 0..2 { app_step(&mut app, &ctx, vec![]); } - let none = egui::Modifiers::NONE; - let mut steps = vec![vec![primary(from, true, none)]]; - steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); - steps.push(vec![primary(to, false, none)]); - steps.extend([vec![], vec![], vec![]]); let mut rebuilt = vec![]; - for events in steps { + for events in steps(from, &xf) { let before = app.menus.rebuilds; app_step(&mut app, &ctx, events); rebuilt.push(app.menus.rebuilds - before); } (app, rebuilt) }; - let (app, rebuilt) = (0..20) + (0..20) .find_map(|_| { let before = catalogs(); let out = run(); (catalogs() == before).then_some(out) }) - .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")) +} + +/// A Selection tool move builds the menus' states again once, for the release that commits it. Its press lands on the +/// canvas, and the frame the move begins in and the frames of its previews, which change the document's revision, keep +/// them. +#[test] +fn a_selection_move_rebuilds_the_menus_for_its_release_only() { + let none = egui::Modifiers::NONE; + let (app, rebuilt) = selection_tool_rebuilds(|from, xf| { + let to = xf.to_screen(Point::new(170.0, 135.0)); + let mut steps = vec![vec![primary(from, true, none)]]; + steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); + steps.push(vec![primary(to, false, none)]); + steps.extend([vec![], vec![], vec![]]); + steps + }); assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle"); - assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle"); + assert_eq!(rebuilt[..9].iter().sum::(), 0, "the press and the 8 moves keep the menus: {rebuilt:?}"); + assert_eq!(rebuilt.iter().sum::(), 1, "the release that commits the move rebuilds them once: {rebuilt:?}"); +} + +/// A click on the selected rectangle that leaves it where it was, and F20 pressed and released with no field or dialog +/// taking it and no command on it, change nothing the menus show: no frame builds the menus' states again. +#[test] +fn a_canvas_click_that_changes_nothing_keeps_the_menus() { + let none = egui::Modifiers::NONE; + let f20 = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: none }; + let (app, rebuilt) = selection_tool_rebuilds(|from, _| { + vec![vec![primary(from, true, none)], vec![primary(from, false, none)], vec![f20(true)], vec![f20(false)], vec![], vec![]] + }); + assert_eq!(drawn_paths(&app), vec![Rect::new(100.0, 100.0, 160.0, 130.0)], "the click leaves the rectangle where it was"); + assert_eq!(app.session.active().map(|d| d.selection.objects.len()), Some(1), "the rectangle stays selected"); + assert_eq!(rebuilt, [0; 6], "rebuilds in each frame: press, release, a key press and release, 2 idle"); } /// #6369: only the selection box remains over the temporary halftone, and the original @@ -4489,6 +4514,38 @@ fn plain(app: &VectorcraftApp, id: u64) -> String { } } +/// While the Type tool edits text, a click in the text and an arrow key, which move the caret without an edit, build +/// the menus' states again: the type rows read the caret's range. +#[test] +fn a_click_or_a_key_in_edited_text_rebuilds_the_menus() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = crate::testing::ui_context(); + let id = start_typing(&mut app, &ctx); + typing_frame(&mut app, &ctx, vec![Event::Text("abc".into())]); + typing_frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(101.0, 100.0)); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let left = |pressed| Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, steps: Vec>| { + let before = app.menus.rebuilds; + for events in steps { + typing_frame(app, &ctx, events); + } + app.menus.rebuilds - before + }; + let click = || vec![vec![Event::PointerMoved(at), button(true)], vec![button(false)]]; + // The first click puts the caret there; the second leaves the document's revision as it is. + rebuilds(&mut app, click()); + let revision = app.session.active().map(|d| d.revision); + assert!(rebuilds(&mut app, click()) > 0, "a click in the text"); + assert_eq!(app.session.active().map(|d| d.revision), revision, "the click changes no revision"); + assert!(rebuilds(&mut app, vec![vec![left(true)], vec![left(false)]]) > 0, "an arrow key in the text"); + assert_eq!(plain(&app, id), "abc", "neither edits the text"); + assert!(app.session.tool_wants_text(), "editing goes on"); +} + /// Starts editing new point type with the Type tool; returns its id. fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..70f1080db5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -656,6 +656,17 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too if ui.ctx().current_pass_index() == 0 && view_press { app.session.tool_press_elsewhere(); } + // A press on the canvas, and a key while the canvas or nothing has the focus, change what the menus show only through + // the document, the tool or a command, which the menus' state key reads, so the key leaves them out + // (`menus::model::last_press`). + let presses: Vec = + ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerButton { pos, .. } = e { Some(*pos) } else { None }).collect()); + if !presses.is_empty() && presses.iter().all(|&at| over(Some(at)) && ui.ctx().layer_id_at(at) == Some(ui.layer_id())) { + app.canvas.pressed_at = Some(ui.input(|i| i.time)); + } + if ui.ctx().memory(|m| m.focused()).is_none_or(|id| id == pass.id) { + app.canvas.keys_at = Some(ui.input(|i| i.time)); + } let view_info = app.view_info(); let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 73a4296dd9..b49274358a 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -91,9 +91,11 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, /// its revision (edits, selection and view changes), history and clipboard, the filter plug-in that ran last, the language, /// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts -/// until the installed ones are scanned, then all of them, #5483). `input`, the pass of the last frame with a pointer -/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash -/// doesn't list (panels shown, a tool picked). While an +/// until the installed ones are scanned, then all of them, #5483), the tool, whether the panels show, the open panel +/// flyout, the dock workspace's identity and revision, the current window and whether a dialog is open or a shortcut +/// is being recorded. `input`, the pass of the last frame with a click away from the canvas or a key a field or a dialog +/// took ([`last_press`]), changes once for each, which covers what the hash +/// doesn't list (a panel's own state, a dialog's fields). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one, /// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An @@ -125,6 +127,14 @@ fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { // Apply Last Filter and Last Filter… are named after the filter that ran last. app.last_filters.last_id().hash(&mut h); app.file_dialog_open().hash(&mut h); + // What a click on the canvas or a key no field takes changes without a command: the tool (a tool's key, a held + // Space), the panels shown (Tab), the open panel flyout and the dock workspace's identity and revision (panels + // shown, hidden or moved), the current window, the view's rotation (Rotate View's checks) and active artboard + // (a selection tool's press on one), and a dialog opened or closed (Escape, Enter). + (s.tool_id(), crate::panel_docking::panels_shown(app), crate::doc_windows::current(app)).hash(&mut h); + (&app.ui.open_panel, std::sync::Arc::as_ptr(&app.ui.dock_workspace).addr(), app.ui.dock_workspace.revision()).hash(&mut h); + app.view().map(|v| (v.rotation.to_bits(), v.artboard)).hash(&mut h); + (app.any_dialog_open(), recording_shortcut(app)).hash(&mut h); (crate::i18n::current().code(), plugin_revision(), crate::scripts_menu::revision(), crate::dialogs::proof_setup::saved_revision()).hash(&mut h); hash_listed_names(&app.ui, &mut h); let fonts = vectorcraft_text::FontDb::global(); @@ -215,20 +225,33 @@ fn lay_out(app: &mut VectorcraftApp, target: Target) { } } -/// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read -/// last included: the `input` of [`state_key`]. It stays the same over the frames after that one, so each of them -/// changes the key once. +/// The pass number of the last frame with a press that [`pressed_pass`] counts, the frame `ctx` read last included: the +/// `input` of [`state_key`]. It stays the same over the frames after that one, so each of them changes the key once. pub(crate) fn last_press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option { - if let Some(pass) = pressed_pass(ctx) { + if let Some(pass) = pressed_pass(app, ctx) { app.menus.pressed = Some(pass); } app.menus.pressed } -/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) or a key -/// pressed. -fn pressed_pass(ctx: &egui::Context) -> Option { - let pressed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { pressed: true, .. }))); +/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) away from +/// the canvas, or a key pressed while a text field, a dialog or a panel's control has the keys. A click on the canvas +/// changes the rows only through the document, the tool or a command, and a key the canvas or the app's shortcuts take +/// only through those, the panels shown (Tab) or a dialog it opens or closes, which [`rows_key`] reads. While the tool +/// edits text, a click or a key on the canvas counts too: it moves the caret or the selected range, which the type rows +/// read. +fn pressed_pass(app: &VectorcraftApp, ctx: &egui::Context) -> Option { + let editing = app.session.tool_wants_text(); + let typing = editing || WindowHost::of(ctx).typing() || app.any_dialog_open(); + let pressed = ctx.input(|i| { + let on_canvas = !editing && app.canvas.pressed_at == Some(i.time); + let canvas_keys = !typing && app.canvas.keys_at == Some(i.time); + i.events.iter().any(|e| match e { + egui::Event::PointerButton { .. } => !on_canvas, + egui::Event::Key { pressed: true, .. } => !canvas_keys, + _ => false, + }) + }); pressed.then(|| ctx.cumulative_pass_nr()) } diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 2450a9b201..fae289c8d5 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -39,8 +39,9 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) { } } -/// Once per frame, after the UI: bring the native menu up to date. A frame with a click or a key -/// press reads the menus again, as input may change state the key doesn't list. +/// Once per frame, after the UI: bring the native menu up to date. A frame with a click away from +/// the canvas or a key a field or a dialog took reads the menus again, as that input may change +/// state the key doesn't list ([`last_press`]). pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.services.native_menu.is_none() { return; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 88c2e04540..ace8c15829 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -183,22 +183,113 @@ fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { Some((app, ctx)) } -/// A key press builds the menus' states again once: the frames after it, with no press, keep them. +/// A key press that a dialog takes builds the menus' states again once: the frames after it, with no press, keep them. +/// The same key with no dialog or field to take it keeps them. #[test] -fn a_key_press_rebuilds_the_menus_once() { - let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_rebuilds_the_menus_once") else { return }; - let before = app.menus.rebuilds; +fn a_key_press_a_dialog_takes_rebuilds_the_menus_once() { + let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_a_dialog_takes_rebuilds_the_menus_once") else { return }; + // F20 runs no command and changes nothing the menus show. + let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, events: Vec| { + let before = app.menus.rebuilds; + app_frame(app, &ctx, events); + for _ in 0..4 { + app_frame(app, &ctx, vec![]); + } + app.menus.rebuilds - before + }; + assert_eq!(rebuilds(&mut app, vec![]), 0, "idle frames keep the menus"); + assert_eq!(rebuilds(&mut app, vec![press(true), press(false)]), 0, "a key nothing takes keeps the menus"); + app.run("file.documentSetup", json!({})).unwrap(); + rebuilds(&mut app, vec![]); + // No field of the dialog has the keys: the dialog itself takes them. + ctx.memory_mut(|m| { + if let Some(field) = m.focused() { + m.surrender_focus(field); + } + }); + rebuilds(&mut app, vec![]); + assert!(app.any_dialog_open(), "Document Setup is open"); + assert!(!craft::ui::runtime::windows::WindowHost::of(&ctx).typing(), "no text field has the keys"); + assert_eq!(rebuilds(&mut app, vec![press(true), press(false)]), 1, "a key the dialog takes rebuilds the menus once"); +} + +/// Show or Hide Panels, which the framework runs itself (Tab) with no app command, takes the check marks off the Window +/// menu's panel rows. +#[test] +fn hiding_the_panels_unchecks_the_window_rows() { + use craft::ui::runtime::commands::{ChromeCommand, CommandSet as _, CommandState, FireSource}; + let Some((mut app, ctx)) = settled_app("menus::tests::hiding_the_panels_unchecks_the_window_rows") else { return }; + let checked_panels = |app: &VectorcraftApp| { + app.menus + .bar + .items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && app.menus.states.get(&it.command).and_then(CommandState::is_checked) == Some(true)) + .count() + }; + assert!(checked_panels(&app) > 0, "a panel shows, and its Window row is checked"); + let raw = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0))), ..Default::default() }; + crate::testing::part_frame(&mut app, &ctx, raw(), |app, ui| { + craft::ui::runtime::commands::fire(ui.ctx(), CommandRef::new(ChromeCommand::TogglePanels.id()), FireSource::Menu); + app.tick(ui.ctx()); + app.ui(ui); + }); for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } - assert_eq!(app.menus.rebuilds, before, "idle frames keep the menus"); - // F20 runs no command and changes nothing the menus show. - let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - app_frame(&mut app, &ctx, vec![press(true), press(false)]); - for _ in 0..4 { + assert!(!crate::panel_docking::panels_shown(&app), "the panels are hidden"); + assert_eq!(checked_panels(&app), 0, "no Window row is checked while the panels are hidden"); +} + +/// A panel flyout opened or closed without a command or input updates its Window row's check mark. +#[test] +fn closing_a_panel_flyout_unchecks_its_window_row() { + use craft::ui::runtime::commands::CommandState; + let Some((mut app, ctx)) = settled_app("menus::tests::closing_a_panel_flyout_unchecks_its_window_row") else { return }; + let row = app + .menus + .bar + .items() + .into_iter() + .find(|it| { + it.command.id == "window.panel" + && it.command.params["panel"] + .as_str() + .is_some_and(|panel| crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&panel.to_owned())) + }) + .expect("the default layout has an iconic panel's Window row") + .command + .clone(); + let checked = |app: &VectorcraftApp| app.menus.states.get(&row).and_then(CommandState::is_checked) == Some(true); + app.ui.open_panel = Some(row.params["panel"].as_str().unwrap().to_owned()); + for _ in 0..2 { app_frame(&mut app, &ctx, vec![]); } - assert_eq!(app.menus.rebuilds, before + 1); + assert!(checked(&app), "the Window row is checked while its panel shows in a flyout"); + app.ui.open_panel = None; + for _ in 0..2 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(!checked(&app), "the Window row is unchecked after its panel's flyout closes"); +} + +/// A view turned by the canvas's navigation (a Shift+drag on the canvas), with no command and no document change, moves +/// View › Rotate View's check to the angle it was turned to. +#[test] +fn a_view_turned_on_the_canvas_moves_the_rotate_view_check() { + use craft::ui::runtime::commands::CommandState; + let Some((mut app, ctx)) = settled_app("menus::tests::a_view_turned_on_the_canvas_moves_the_rotate_view_check") else { return }; + let rows: Vec = app.menus.bar.items().into_iter().filter(|it| it.command.id == "view.rotate").map(|it| it.command.clone()).collect(); + let angle = |row: &CommandRef| row.params["angle"].as_f64().unwrap_or(0.0); + let turned = rows.iter().find(|row| angle(row) != 0.0).expect("Rotate View lists an angle other than 0").clone(); + let checked = |app: &VectorcraftApp, row: &CommandRef| app.menus.states.get(row).and_then(CommandState::is_checked) == Some(true); + assert!(!checked(&app, &turned), "the view starts unturned"); + app.view_mut().expect("a view").rotation = angle(&turned); + for _ in 0..2 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(checked(&app, &turned), "the angle the view is turned to is checked"); } /// A font added to the fonts the whole process shares builds the menus again with no input, Type › Font then lists it, diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 6bcdd4853e..58b47d2a14 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1257,6 +1257,20 @@ fn the_overflow_menu_of_a_docked_group_is_reached_and_used_from_the_keyboard() { assert!(h.strip_has_focus(), "the focus stays on the strip after the pick"); } +/// A key that a panel's control takes builds the menus' states again: the control can change what a panel menu row +/// reads without running a command. +#[test] +fn a_key_a_panel_control_takes_rebuilds_the_menus() { + let mut h = Harness::new(); + let strip = h.named("Panels", egui::accesskit::Role::TabList).expect("a group's tab strip"); + h.click(pos2(strip.center().x, strip.bottom() + 25.0)); + assert!(h.strip_has_focus(), "a press in the group focuses its strip"); + let before = h.app.menus.rebuilds; + h.press(egui::Key::F20, egui::Modifiers::NONE); + h.frames(2); + assert!(h.app.menus.rebuilds > before, "the key the strip took rebuilds the menus"); +} + /// A tab group dragged out of the icon column by its grip floats as an expanded panel: its tabs show /// in the window, and a click on each tab shows that panel. #[test] From ea752548dfe64e728dadd937306c9f5d61c84f46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:09:00 -0800 Subject: [PATCH 391/533] New Document: reject a bad preset or presetCategory instead of ignoring it file.new and file.newPresets.save read `preset` and `presetCategory` with str_param, so a value that is not a string was dropped and the call went on with the default settings or the search of every category. An unknown category reported "no preset called" instead of naming the category, and a presetCategory without a preset was dropped. Each of these is now an error, with the same "unknown category" message file.newPresets gives. Null still leaves a param out, and a replayed journal step reads the params as before, so saved steps still play. presetCategory came in with #9295. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 32 +++++++++++++++++++++---- crates/engine/src/tests/newdoc.rs | 39 +++++++++++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 99ef61ef44..b7ba67ef7c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 26c5d2bbac..c842674fb6 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -860,10 +860,34 @@ pub fn find(s: &Session, name: &str) -> Option { /// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names /// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without -/// `preset`. +/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no +/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads +/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no +/// preset. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { - let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; - let found = match str_param(p, "presetCategory") { + if s.replaying() { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))); + } + let name = text_param(p, "preset", cmd)?; + let wanted = text_param(p, "presetCategory", cmd)? + .map(|c| { + category_names() + .find(|n| n.eq_ignore_ascii_case(c)) + .ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::>().join(", ")))) + }) + .transpose()?; + let Some(name) = name else { + return match wanted { + Some(_) => Err(bad(cmd, "presetCategory needs a preset")), + None => Ok(s.default_settings()), + }; + }; + let found = match wanted { Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), None => find(s, name), }; diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 6e1623c00e..ac34216e2f 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() { assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels); } +#[test] +fn a_bad_preset_or_preset_category_is_an_error() { + let s = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01); + for p in [ + json!({"preset": "A4", "presetCategory": "Napkins"}), + json!({"preset": "A4", "presetCategory": 5}), + json!({"preset": "A4", "presetCategory": ""}), + json!({"preset": "A4", "presetCategory": " Print "}), + json!({"presetCategory": "Print"}), + json!({"presetCategory": "Napkins"}), + json!({"preset": 5}), + json!({"preset": true, "presetCategory": "Print"}), + ] { + assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}"); + let mut save = p.clone(); + save["name"] = json!("Mine"); + assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}"); + } + let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string(); + assert!(e.contains("unknown category `Napkins`"), "{e}"); + // Null leaves a param out. + Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap(); + // A step this version took replays, and one an earlier version took still plays as it did then. + let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + let mut recorded = new_doc(json!({})); + recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print"); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); +} + #[test] fn ppi_overprint_preview_and_bad_params() { // Overprint Preview is process-wide. diff --git a/docs/mcp.md b/docs/mcp.md index f3931f6fb1..59afba853a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10987,7 +10987,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in -that category), `name`, `width`/`height` +that category; an unknown category, or `presetCategory` without `preset`, is an error), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are From dc94ae977c4f425e5a5da1900d4d0cd1a621993e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:10:05 -0800 Subject: [PATCH 392/533] Docs: matrix records passed in need only the six mValue fields The matrix functions read only mValueA to mValueTY from a record passed in. The typename "Matrix" is on the records they give back. --- crates/engine/src/script/dom/matrix.rs | 7 ++++--- docs/mcp.md | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index aeccf78c95..4de0a9efe4 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -1,9 +1,10 @@ //! The matrix functions of `app`, as the help pages //! and //! describe them. A matrix is a plain -//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a -//! new record, those two give a boolean, and none changes the records passed to it. +//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and +//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has +//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives +//! a new record, those two give a boolean, and none changes the records passed to it. //! //! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix //! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. diff --git a/docs/mcp.md b/docs/mcp.md index 3f6d406c90..2a2578895e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3278,7 +3278,8 @@ through `$`: `concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`, `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain - objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each + objects with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY`. A record + passed in needs only those six fields; each record a function gives also has `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. No function changes the records passed to it. A record maps `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own From af8405e4b0ef731e1146ed6267096a7b69353d49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:15:27 -0800 Subject: [PATCH 393/533] xtask: census rule counts a continue at the start of a loop body A continue that opens the loop body had no byte before it, so the expression-start check failed and the call after it was treated as run. It now counts. A continue inside the tokens of a macro that does not run them (stringify!({ continue; })) no longer counts as skipping the call; one inside a macro that may run its arguments (vec![{ continue; }]) still does. --- xtask/src/test_lint.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 6ad7f1c3dc..5ebd082af4 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2789,7 +2789,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac /// rest of that loop's iteration: one with the loop's `label`, or one without a label that is not /// inside a nested `for`, `while` or `loop` body. A labeled `continue` inside a nested loop with the /// same label targets that nested loop. Only a `continue` that starts an expression counts, not one -/// inside a macro's tokens (`stringify!(continue)`) or a raw identifier (`r#continue`). A `break` in +/// inside the tokens of a macro that does not run them (`stringify!(continue)`) or a raw identifier +/// (`r#continue`). A `continue` at the start of the body counts. A `break` in /// the body already rules out a census hit, so only `continue` is read here. fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[u8]>) -> bool { let label_at = |at: usize| { @@ -2829,8 +2830,21 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ }) .collect() }; + // Whether `at` sits inside the tokens of a macro that does not run them (`stringify!({ continue; })`). + // Other macros (`vec![{ continue; }]`) may run their arguments, so their `continue` still counts. + let in_macro = |at: usize| { + (open + 1..at).any(|k| { + matches!(b[k], b'(' | b'[' | b'{') + && matching(b, k).is_some_and(|close| at < close) + && b[open + 1..k].trim_ascii_end().strip_suffix(b"!").is_some_and(|h| { + let name = &h[h.iter().rposition(|&c| !is_ident(c)).map_or(0, |i| i + 1)..]; + matches!(name, b"stringify" | b"concat_idents" | b"macro_rules") + }) + }) + }; words(b, b"continue", open + 1, start).into_iter().any(|at| { - if !b[open + 1..at].trim_ascii_end().last().is_some_and(|&c| matches!(c, b'{' | b'}' | b';' | b'>')) { + // The start of the loop body also starts an expression. + if !b[open + 1..at].trim_ascii_end().last().is_none_or(|&c| matches!(c, b'{' | b'}' | b';' | b'>')) || in_macro(at) { return false; } let nested = nested_loops(at); @@ -10535,6 +10549,21 @@ mod tests { [], "a continue token in a macro or a raw identifier does not skip the call" ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!({ continue; }); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue statement inside a macro's tokens does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { let _k = vec![{ if skip { continue; } 0 }]; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue in a macro argument that runs may skip the call" + ); + assert_eq!( + census("for _ in &[1] { continue; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue at the start of the loop body skips the call" + ); assert_eq!( census("block_on(((async || app.run(c))())); assert!(menu(c).is_some());"), [], From bd1f5daf2a809cfc445d11143572f9aa4e4a507a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:22:28 -0800 Subject: [PATCH 394/533] Type Tools: reserve only the old run count in Make Numbers Sequence replace_runs reserved old.len() + 2 * changes.len() runs. For 2,000 numbers that is 4,001 runs on every preview change, while push merges neighbors with equal style and the output usually keeps about old.len() runs. The vector now starts at old.len() and grows when formatting splits a run. This changes only the initial allocation, so no test can fail without it; the existing long-text and styled-output tests still pass. --- crates/engine/src/cmd/addons/typetools/numbers.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index 2db74afbfb..fb4306ddd5 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -336,7 +336,7 @@ pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { fn replace_runs(runs: &mut Vec, changes: &[Edit]) { note_text_pass(); let old = std::mem::take(runs); - let mut out: Vec = Vec::with_capacity(old.len() + 2 * changes.len()); + let mut out: Vec = Vec::with_capacity(old.len()); let mut pending = changes.iter().rev().peekable(); // Where the run starts and where the last replaced range ends. let (mut off, mut cut) = (0, 0); From 924f3d0e50d4bdda7a51631579492a1cc2438066 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:29:28 -0800 Subject: [PATCH 395/533] Performance: only the Swatches body reads the swatch browser state The memoized panel bodies built the Swatches browser inputs (the filter, the selection and the sorted toggled keys) for every panel on every frame. They are now built only for the Swatches panel; the other bodies do not read them. --- crates/ui-egui/src/dock.rs | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 9aaf0a2190..ea6dcb4c69 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -68,7 +68,7 @@ fn memoized(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, body: fn(&mut BodyP let memoized = MEMOIZED.contains(&id) && !tests::shown_directly(); #[cfg(not(test))] let memoized = MEMOIZED.contains(&id); - let inputs = memoized.then(|| BodyInputs::of(app, ui.ctx())); + let inputs = memoized.then(|| BodyInputs::of(app, ui.ctx(), id)); let mut props = BodyProps { app, id, inputs }; if !memoized { body(&mut props, ui); @@ -117,10 +117,11 @@ struct BodyInputs { color_options: craft::color_ui::ui::ColorPanelState, /// Options shared with the Stroke popover, including the last disabled dash pattern. stroke_options: (bool, bool, Option<(Vec, bool)>), - /// The browser state shared with a paint chip's Swatches popover. - swatches: panels::swatches::BodyInputs, - /// Whether the Swatches footer's library button is pressed. - swatch_libraries_open: bool, + /// The browser state shared with a paint chip's Swatches popover. `None` for every panel but Swatches: no other + /// body reads it. + swatches: Option, + /// Whether the Swatches footer's library button is pressed. `None` for every panel but Swatches. + swatch_libraries_open: Option, /// Whether a font preview shows in the document. font_preview: bool, /// While a gesture previews its edit (a scrubbed field, a drag on the canvas) or a tool computes its edit, the @@ -135,7 +136,9 @@ struct BodyInputs { } impl BodyInputs { - fn of(app: &VectorcraftApp, ctx: &egui::Context) -> Self { + /// The inputs of panel `id`'s body. + fn of(app: &VectorcraftApp, ctx: &egui::Context, id: &str) -> Self { + let swatches = id == "swatches"; let live = app.session.active().is_some_and(|d| d.interaction.is_some()) || app.session.tool_waiting(); BodyInputs { live: live.then(|| ctx.cumulative_pass_nr()), @@ -149,8 +152,8 @@ impl BodyInputs { layers_options: app.ui.layers_panel.clone(), color_options: app.ui.color_panel, stroke_options: (app.ui.stroke_panel.hide_options, app.ui.stroke_panel.scale_linked, app.ui.stroke_panel.dash_last.clone()), - swatches: panels::swatches::BodyInputs::of(app), - swatch_libraries_open: panels::library_panel::any_open::(&app.ui), + swatches: swatches.then(|| panels::swatches::BodyInputs::of(app)), + swatch_libraries_open: swatches.then(|| panels::library_panel::any_open::(&app.ui)), font_preview: app.font_preview_owner.is_some(), fonts: vectorcraft_text::layout_inputs(), plugins: vectorcraft_plugins::registry::revision(), @@ -256,10 +259,10 @@ mod tests { assert_eq!(runs_in(&mut panel, 10), 0, "the Layers panel has settled"); let texts = panel.texts(); assert!(texts.iter().any(|(text, _)| text.contains("Rectangle")), "the object row shows: {texts:?}"); - let before = super::BodyInputs::of(&panel.app(), panel.ctx()); + let before = super::BodyInputs::of(&panel.app(), panel.ctx(), "layers"); let options = panel.app().ui.layers_panel.clone(); panel.app().ui.layers_panel = crate::panels::layers::PanelOptions { layers_only: true, ..options }; - let after = super::BodyInputs::of(&panel.app(), panel.ctx()); + let after = super::BodyInputs::of(&panel.app(), panel.ctx(), "layers"); assert_eq!((after.document, after.commands, after.journal), (before.document, before.commands, before.journal)); assert!(runs_in(&mut panel, 2) > 0, "the options run the body again without a command"); assert!(!panel.texts().iter().any(|(text, _)| text.contains("Rectangle")), "Show Layers Only hides the object row"); @@ -293,6 +296,17 @@ mod tests { assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); } + /// Only the Swatches body reads the swatch browser, so a filter changed in a popover replays the Color panel. + #[test] + fn swatches_filter_does_not_run_the_color_panel() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Color panel has settled"); + let inputs = super::BodyInputs::of(&panel.app(), panel.ctx(), "color"); + assert!(inputs.swatches.is_none() && inputs.swatch_libraries_open.is_none(), "the Color body's inputs hold no swatch state"); + panel.app().ui.swatches_panel.state.browser.filter = "No matching swatch".into(); + assert_eq!(runs_in(&mut panel, 10), 0, "the swatch filter replays the Color panel"); + } + /// The Stroke popover changes linked arrowhead scales without a command. #[test] fn stroke_options_changed_in_a_popover_refresh_the_body() { From f3153a92ab97f86b454177c9d180a098bcfc2409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:30:27 -0800 Subject: [PATCH 396/533] Scripts: a Copy's notes written at once keep the recording limit shown While the worker has a save, an export, a print or a recovery copy to finish, a script's Copy writes its formats at once, and their notes replaced the recording limit's message before the run set it again. The limit's message is now set again when the status bar shows those notes too. A write failure reported at once still stays. Follows #9295. --- crates/ui-egui/src/script_runs.rs | 6 ++-- crates/ui-egui/src/sysclip.rs | 6 ++++ crates/ui-egui/src/tests/sysclip.rs | 46 +++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 0c3b996aa7..beb83dd7d3 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -73,9 +73,11 @@ pub fn poll(app: &mut VectorcraftApp) { let limit = limited.then(|| app.ui.status.clone()); app.publish_clipboard(false); // The limit's message is set again, so the notes of the Copy's formats do not - // replace it. A write failure reported at once stays on the status bar. + // replace it, whether they are written later or at once (while the worker has a + // save, an export, a print or a recovery copy to finish). A write failure reported + // at once stays on the status bar. if let Some(limit) = limit - && app.ui.status == limit + && (app.ui.status == limit || app.clipboard_publishing.shows_notes(&app.ui)) { app.status(limit); app.ui.status_notes = None; diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 9371e118fd..d36259039d 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -121,6 +121,12 @@ impl Publishing { ui.status == self.status.0 && ui.status_sets == self.status.1 } + /// Does `ui`'s status bar show the notes of a Copy's or Cut's formats ([`show_copy_notes`]), + /// with nothing setting the status since? + pub(crate) fn shows_notes(&self, ui: &crate::state::UiState) -> bool { + self.notes_status.as_ref().is_some_and(|(status, sets)| *status == ui.status && *sets == ui.status_sets) + } + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? Different text read from `cb` shows /// a later copy: the record of the failed write is then dropped, so the clipboard holding the diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 87ac38b1d1..5790da66b2 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -655,6 +655,52 @@ fn a_copy_note_does_not_replace_a_scripts_recording_limit() { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); } +/// Runs a script whose Copy is followed by commands that take a recording past its limit, to its end. +fn run_copy_script_past_recording_limit(app: &mut VectorcraftApp) { + run(app, crate::panels::actions::START_RECORDING, json!({})); + for _ in 0..vectorcraft_engine::script::actions::MAX_ACTION_STEPS - 1 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + app.session.script_frames = true; + let source = "vc.run('edit.copy', {}); vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + run(app, "script.run", json!({"source": source, "name": "t.js"})); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(app); + } + assert!(!app.session.script_running(), "the script ends"); +} + +/// While the worker has a save to finish, a script's Copy writes its formats at once: their note +/// does not replace the recording limit's message either. +#[test] +fn a_copy_note_written_at_once_does_not_replace_a_scripts_recording_limit() { + let (mut app, board, hold) = app_with_busy_worker("Saving a.vectorcraft"); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run_copy_script_past_recording_limit(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "the formats are written before the save ends"); + let limit = "the action already has 10,000 steps"; + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); + drop(hold); + background::wait_all(&mut app); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the save's end leaves the limit"); +} + +/// While the worker has a save to finish, a script's Copy whose formats cannot be written says so +/// in place of the recording limit's message. +#[test] +fn a_copy_written_at_once_that_fails_is_reported_over_a_scripts_recording_limit() { + let (mut app, board, hold) = app_with_busy_worker("Saving a.vectorcraft"); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + refuse_writes(&board, true); + run_copy_script_past_recording_limit(&mut app); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard: "), "the failure is shown: {}", app.ui.status); + drop(hold); + background::wait_all(&mut app); +} + /// A message shown while a Copy's formats are made on the worker stays: the formats are written /// once they are ready, and their note does not replace the newer message. #[test] From cdbd288f3c230a049a07221793348fe48bdbf863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:40:50 -0800 Subject: [PATCH 397/533] Scripts: tracings saved without their record catch artwork added before the script reaches them A tracing saved without the record of the objects its trace made was checked against a snapshot taken when the script first got its PluginItem. A script that reached the tracing's paths first (through pathItems or the selection) and added artwork beside them had that artwork in the snapshot, so tracing again or releasing the tracing discarded it without an error. - Before each command a script runs, the run notes the id the active document gives its next object. An object the run made since then counts as added to an older tracing saved without its record. - After file.revert the note moves to the reloaded document's next id, so objects read back from the file are not counted as added. The snapshot check comes from 466debdc (Scripts: tracing refuses protected art). --- crates/engine/src/script/dom.rs | 1 + crates/engine/src/script/dom/tracing.rs | 52 +++++++++++++++++-- crates/engine/src/tests/script_dom_tracing.rs | 51 ++++++++++++++++++ 3 files changed, 99 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4e50da3b48..8bc2329a92 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -110,6 +110,7 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + tracing::before_command(h); variables::before_command(h, id) } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index a37a062849..22a1e36f1d 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -128,6 +128,10 @@ pub(super) struct State { prev: RefCell>, sources: RefCell>, descendants: RefCell>>, + /// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`]) + /// and the lowest id the run could allocate after the first note or the latest revert + /// ([`note_document`]). + marks: RefCell>, retraces: Cell, } @@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { }); } +/// Before each command a script runs: notes the active document ([`note_document`]). +pub(super) fn before_command(h: &Host) { + let s = h.session.borrow(); + if let Some(st) = s.active() { + note_document(h, st); + } +} + +/// Records the next object id when the run first notes the document `st`. A revert resets +/// the mark to the reloaded document's next object id and keeps the descendant snapshots. +/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it. +fn note_document(h: &Host, st: &crate::DocState) { + let mut marks = h.dom.tracing.marks.borrow_mut(); + match marks.get_mut(&st.uid) { + Some((reverts, _)) if *reverts == st.reverts => {} + Some((reverts, mark)) => { + *reverts = st.reverts; + *mark = st.doc.peek_next_id(); + } + None => { + marks.insert(st.uid, (st.reverts, st.doc.peek_next_id())); + } + } +} + +/// Returns the lowest id the run could allocate in document `uid` after its first note or latest +/// revert ([`note_document`]). +fn mark(h: &Host, uid: u64) -> Option { + h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark) +} + pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) @@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// and "Cannot edit page item" when it holds a locked object other than its source image, which /// the replacement would discard. The objects looked at are charged to the run either way. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { - let (visited, result) = read_group(h, item, |_, group| { + let (visited, result) = read_group(h, item, |st, group| { + note_document(h, st); remember_source(h, item.doc.uid, group); - // The objects the trace made, as the tracing records them; a tracing saved without that - // record is checked against the objects it held when this run first saw it. + // A tracing with a record is checked against the objects its trace made. A tracing without + // a record is checked against its first descendant snapshot, which survives reverts. + // If the group id is below the document's mark, members at or above the mark are also added. + // A revert resets the mark to the reloaded document's next object id. let made = group.trace_made(); let descendants = h.dom.tracing.descendants.borrow(); let ids = match made { Some(_) => None, - None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), + None => descendants.get(&(item.doc.uid, item.id.0)), + }; + let newer = match made { + Some(_) => None, + None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m), }; let source = group.children().and_then(|c| c.first()).map(|n| n.id); let mut visited = 0u64; @@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { (Some(m), _) => !m.contains(n.id), (None, Some(ids)) => !ids.contains(&n.id), (None, None) => false, - }; + } || newer.is_some_and(|m| n.id.0 >= m); // Added artwork is reported before a locked object, whichever comes first. if added { return Ok((visited, Err(HostError::Error(refusal.into())))); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..5949e019fc 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -506,6 +506,57 @@ fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() { + let base = folder("retrace-legacy-paths"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let held = members(&s, group); + // The script reaches the tracing's paths before the tracing itself. + let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);"; + let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0))); + assert_eq!(out, [json!(ADDED_ARTWORK)]); + assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() { + let base = folder("retrace-legacy-revert"); + let path = base.join("main/legacy.vectorcraft"); + for seen_first in [false, true] { + for added in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = members(&s, group); + s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap(); + let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" }; + let add = if added { + format!( + "var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';", + json!(path.to_string_lossy()) + ) + } else { + String::new() + }; + let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0))); + // A revert keeps the snapshot taken before it. + let message = if added || seen_first { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn engine_trace_can_be_retraced_by_a_script() { let base = folder("retrace-engine-artwork"); From 629ad05f3c792e8a318ede0cac940195391d08d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:44:10 -0800 Subject: [PATCH 398/533] Render: frames that wait for the worker keep the canvas renderer's paths The canvas calls Renderer::finish_measurement_only in every frame that waits for the render worker. Since 51d3dcf2ea each call ages the renderer's caches, so after four waiting frames the paths it drew were swept even when nothing was measured, as after a zoom or a pan. The next frame the canvas rendered itself built every path again: a pan step at 400% on a 6,000-path document took 25 to 34 ms instead of 8 to 10 ms. finish_measurement_only now ages the caches only when Renderer::changed measured through the renderer since its last frame or the last call, so a drag whose frames go to the worker still lets go of old node versions. --- crates/render/src/changed.rs | 1 + crates/render/src/lib.rs | 3 +++ crates/render/src/renderer.rs | 7 +++++++ crates/render/src/tests/memory.rs | 24 ++++++++++++++++++++++++ 4 files changed, 35 insertions(+) diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index ef282e5b4d..e7ab2c01ef 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -96,6 +96,7 @@ impl crate::Renderer { /// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and /// nothing is held. pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed { + self.measuring = true; // Trim View clips each draw when blending reaches the page and clips one composited // layer otherwise. Changing modes can change unchanged art at an artboard edge. if opts.trim && !old.artboards.is_empty() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 544438d96f..4358cc180d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -182,6 +182,9 @@ pub struct Renderer { /// ([`lru::MEASURED_BUDGET`]). measured_bytes: usize, measured_budget: usize, + /// [`Renderer::changed`] measured through this renderer since its last frame began or since + /// [`Renderer::finish_measurement_only`] last aged its caches. + measuring: bool, /// The export bounds of the objects measured without their hidden members /// (`encode::drawn_bounds`), by the object they were made from: kept for a pass over artboards, /// let go when a frame ends. diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 065055f96c..fdf7847412 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -76,6 +76,7 @@ impl Renderer { measured: PtrMap::default(), measured_bytes: 0, measured_budget: lru::MEASURED_BUDGET, + measuring: false, pass_bounds: PtrMap::default(), three_d_bounds: PtrMap::default(), three_d_kept: 0, @@ -244,6 +245,7 @@ impl Renderer { /// Start a frame: cache entries used from now on are marked with its stamp. fn begin_frame(&mut self) { self.stamp += 1; + self.measuring = false; self.inline_depth = 0; // Nothing is drawn offscreen yet (even if an earlier frame stopped part way). (self.offscreen_live, self.offscreen_budget) = (0, 0); @@ -267,7 +269,12 @@ impl Renderer { /// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update. /// Age the measurement caches and keep the previous draw's effect rasters available. + /// Without a [`Self::changed`] since the last frame or the last call, nothing changes: + /// the paths of the last frame stay for this renderer's next frame. pub fn finish_measurement_only(&mut self) { + if !std::mem::take(&mut self.measuring) { + return; + } self.stamp += 1; self.sweep_node_geometry(); let g = self.stamp; diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 8579c314b8..2e890606bd 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -34,6 +34,30 @@ fn geometry_from_measurement_only_frames_releases_old_node_versions() { assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw"); } +/// The canvas finishes a measurement in every frame that waits for another renderer's frame, also +/// when it measured nothing (a zoom or a pan). Those frames keep the paths this renderer drew, so +/// its next frame, the next step of a pan, does not build them all again. +#[test] +fn finishing_without_a_measurement_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert!(renderer.geom.contains_key(&drawn), "the frame keeps the path it drew"); + for _ in 0..8 { + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { From 79ef692ce50c5ba6b67976a54e138df40ad73b4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:05:59 -0800 Subject: [PATCH 399/533] Scripts: palette events keep their checks after getters and print questions - paletteClose with another engine's palette id no longer drops that palette's waiting events. - A hidden palette is not described after a run or an add, so a throwing getter on it no longer fails the run; script.palettes and docs/mcp.md say a hidden palette lists its controls as they were. - A check box's click rechecks the box after reading its value, so a getter that disables it or closes the palette stops the click. - A list's change rechecks that the list is still enabled and visible after its item texts are read, and is dropped when a getter disabled or hid it. - A waiting palette event does not start its run, or ask for frames, while the last run's print jobs wait for their answer. - script.palette.event's help states that a change merges only after its palette's last waiting click or close. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/script/palettes.rs | 2 +- crates/engine/src/tests/script_palettes.rs | 13 ++++++ crates/js/src/scriptui.rs | 15 ++++++- crates/js/src/scriptui_tests.rs | 50 ++++++++++++++++++++++ crates/ui-egui/src/app.rs | 4 +- crates/ui-egui/src/script_palettes.rs | 9 +++- crates/ui-egui/src/tests/script_print.rs | 23 ++++++++++ docs/mcp.md | 3 +- 9 files changed, 115 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 5cca4d282b..560804633e 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "List Script Palettes", [], None, - "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run; a hidden palette lists its controls as they were when it was hidden, until show() shows it again → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", always, palettes ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler", always, palette_event ), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 97435efb25..a63a712918 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -172,9 +172,9 @@ impl Palettes { pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool { let before = self.list.len(); self.list.retain(|p| !(p.id == id && p.engine == engine)); - self.waiting.retain(|q| q.palette != id); let closed = self.list.len() != before; if closed { + self.waiting.retain(|q| q.palette != id); self.actions.retain(|(p, _)| *p != id); } closed diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index fa57cf5fc5..28cf359dc1 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -580,6 +580,19 @@ fn a_palette_click_during_another_run_runs_after_it() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn closing_a_palette_id_in_another_engine_keeps_that_palette_s_waiting_events() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nvar q = new Window('palette', 'Other'); q.add('button', undefined, 'B'); q.show();"); + let tools = s.script_palettes().iter().find(|p| p.engine == "tools").expect("the tools palette").id; + assert_eq!(s.script_palette_event(tools, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(!s.script_palettes.close(tools, "other"), "the other engine has no palette with that id"); + assert_eq!(s.script_palette_events_waiting(), 1, "the tools palette's click still waits"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); +} + #[test] fn double_clicks_while_queued_run_once() { let mut s = one_doc(); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 9bfe267ec2..8864fc1911 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1406,6 +1406,10 @@ fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { fn click_control_for(i: &mut Interp, c: ObjId, kind: &str, taker: Taker) -> JsResult> { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + // A `value` getter may have disabled or hidden the box, or closed its palette. + if taker.is_some() && !takes(i, taker)? { + return Ok(None); + } i.put(c, key("value"), Value::Bool(!on), true)?; } else if kind == "radiobutton" { i.put(c, key("value"), Value::Bool(true), true)?; @@ -1791,9 +1795,13 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { Ok(()) } -/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. A +/// palette that `hide()` hid is not read: `show()` gives its controls when it shows it again. fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + if !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } let (desc, ..) = describe(i, win)?; let f = host_fn(i, "paletteUpdate")?; i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; @@ -2318,6 +2326,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, if !holds(i, win, c)? { return Err(error(i, "a palette event names a control the palette no longer holds")); } + // An item's text getter may have disabled or hidden the list, or a + // group above it: the event is then dropped, as for a click. + if !live_up(i, win, c)? { + return Ok(()); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 57e1917331..6e3f5ffa1c 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1198,6 +1198,56 @@ fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_close assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into())); } +#[test] +fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() { + for disable in ["l.enabled = false;", "l.visible = false;"] { + let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); + // The second read of the first item's text, which compares it with the items the person + // saw, disables the list. + r.run(&format!( + "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; \ + Object.defineProperty(l.items[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \ + p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String("none".into()), "{disable}"); + assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}"); + } +} + +#[test] +fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() { + // Whichever read of `value` disables the box, the click neither sets it nor runs its handler. + for read in 1..=4 { + let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]); + r.run(&format!( + "var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \ + Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \ + set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;" + )) + .unwrap(); + r.run("Window.__vcPaletteEvent();").unwrap(); + let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap(); + assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}"); + } +} + +#[test] +fn a_hidden_palette_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); p.hide(); \ + Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read"); + assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); +} + #[test] fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 657be1fa62..d3eb43461d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -587,7 +587,7 @@ impl VectorcraftApp { // asks for its frames, and a run that waits for the person goes on at their next input. An // event that waits for an open undo group asks for no frame; the pass that ends the group // asks for the next one (`ui_frame`). - if self.session.script_palette_can_start() { + if crate::script_palettes::can_start(self) { ctx.request_repaint(); } if self.session.script_running() @@ -828,7 +828,7 @@ impl VectorcraftApp { } menus::native::sync(self, &ctx); // A palette event that waited for an undo group this pass ended starts its run next frame. - if self.session.script_palette_can_start() { + if crate::script_palettes::can_start(self) { ctx.request_repaint(); } // Only a field's commit in the pass of the press is the one it made. diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index b07deea333..eed7529753 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -464,11 +464,18 @@ pub(crate) fn with_palette(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut with_host(app, |host, _| host.get_mut_by_id::(palette_id(id)).map(f)).flatten() } +/// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]): +/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no +/// frame meanwhile. +pub(crate) fn can_start(app: &VectorcraftApp) -> bool { + app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app) +} + /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. /// A run that could not begin shows its own error: the last report is an earlier run's. The run /// lists the printers it may print to ([`crate::print::script_printers`]), as `script.run` does. pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { - if !app.session.script_palette_can_start() { + if !can_start(app) { return false; } app.session.script_printers = crate::print::script_printers(app); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 327592a654..a8d5c7c030 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -256,6 +256,29 @@ fn the_print_question_waits_while_a_text_field_has_the_keyboard() { assert!(sent.borrow().is_empty()); } +/// A palette's click waits while the last run's print jobs wait for their answer, and runs after it. +#[test] +fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() { + let (mut app, _, _) = print_app(true); + run( + &mut app, + "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let id = app.session.script_palettes()[0].id; + run(&mut app, PRINT_TO_LAB); + assert!(app.session.script_prints_waiting() || asking(&app), "the jobs wait for their answer"); + app.session.script_palette_event(id, vectorcraft_engine::script::UiEvent::Click(1)).unwrap(); + for _ in 0..5 { + script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the palette's run does not start while the jobs wait"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + cancel(&mut app, PRINT_KIND); + script_runs::poll(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered"); +} + /// Cancel, from anyone, drops the jobs and keeps the run's changes. #[test] fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() { diff --git a/docs/mcp.md b/docs/mcp.md index d1b3308375..1f627e5d22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4307,7 +4307,8 @@ the same controls, handlers and limits: `#targetengine`, or with `#targetengine main`, `new Window("palette")` throws an `Error` that says to add a `#targetengine` line (see [Script engines](#script-engines)). - `show()` runs `onShow` and returns `undefined` at once. `hide()` hides the palette, and `show()` shows it again. - `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. + While a palette is hidden, `script.palettes` lists its controls as they were when it was hidden; `show()` gives + the controls as they are then. `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same. A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error, and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were. From 0962257f9f1583ece0ebf51d9b36c4320c1355df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:10:03 -0800 Subject: [PATCH 400/533] Tests: menu tests check their own process before building the app The gate's test-lint step failed on four menu tests: each returned early on the Option from settled_app, which the lint reads as a skip on a value from the code under test. The child-process check now sits in each test and settled_app returns the app directly, so the assertions are unchanged. --- crates/ui-egui/src/menus/tests.rs | 38 ++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index ace8c15829..a68f026cef 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -165,13 +165,10 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() { } /// An app with a new document whose installed fonts are cataloged, after the frames that build its first menus and the -/// window's keymap. It runs in a process of its own ([`crate::testing::in_own_process`]): the menus' key holds the -/// installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in that another test -/// installs, or a font it adds, rebuilds this app's menus. `None` in the parent process. -fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { - if !crate::testing::in_own_process(test) { - return None; - } +/// window's keymap. Each test that uses it runs in a process of its own ([`crate::testing::in_own_process`]): the menus' +/// key holds the installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in +/// that another test installs, or a font it adds, rebuilds this app's menus. +fn settled_app() -> (VectorcraftApp, egui::Context) { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. vectorcraft_text::FontDb::global().family_list(); @@ -180,14 +177,17 @@ fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } - Some((app, ctx)) + (app, ctx) } /// A key press that a dialog takes builds the menus' states again once: the frames after it, with no press, keep them. /// The same key with no dialog or field to take it keeps them. #[test] fn a_key_press_a_dialog_takes_rebuilds_the_menus_once() { - let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_a_dialog_takes_rebuilds_the_menus_once") else { return }; + if !crate::testing::in_own_process("menus::tests::a_key_press_a_dialog_takes_rebuilds_the_menus_once") { + return; + } + let (mut app, ctx) = settled_app(); // F20 runs no command and changes nothing the menus show. let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; let rebuilds = |app: &mut VectorcraftApp, events: Vec| { @@ -219,7 +219,10 @@ fn a_key_press_a_dialog_takes_rebuilds_the_menus_once() { #[test] fn hiding_the_panels_unchecks_the_window_rows() { use craft::ui::runtime::commands::{ChromeCommand, CommandSet as _, CommandState, FireSource}; - let Some((mut app, ctx)) = settled_app("menus::tests::hiding_the_panels_unchecks_the_window_rows") else { return }; + if !crate::testing::in_own_process("menus::tests::hiding_the_panels_unchecks_the_window_rows") { + return; + } + let (mut app, ctx) = settled_app(); let checked_panels = |app: &VectorcraftApp| { app.menus .bar @@ -246,7 +249,10 @@ fn hiding_the_panels_unchecks_the_window_rows() { #[test] fn closing_a_panel_flyout_unchecks_its_window_row() { use craft::ui::runtime::commands::CommandState; - let Some((mut app, ctx)) = settled_app("menus::tests::closing_a_panel_flyout_unchecks_its_window_row") else { return }; + if !crate::testing::in_own_process("menus::tests::closing_a_panel_flyout_unchecks_its_window_row") { + return; + } + let (mut app, ctx) = settled_app(); let row = app .menus .bar @@ -279,7 +285,10 @@ fn closing_a_panel_flyout_unchecks_its_window_row() { #[test] fn a_view_turned_on_the_canvas_moves_the_rotate_view_check() { use craft::ui::runtime::commands::CommandState; - let Some((mut app, ctx)) = settled_app("menus::tests::a_view_turned_on_the_canvas_moves_the_rotate_view_check") else { return }; + if !crate::testing::in_own_process("menus::tests::a_view_turned_on_the_canvas_moves_the_rotate_view_check") { + return; + } + let (mut app, ctx) = settled_app(); let rows: Vec = app.menus.bar.items().into_iter().filter(|it| it.command.id == "view.rotate").map(|it| it.command.clone()).collect(); let angle = |row: &CommandRef| row.params["angle"].as_f64().unwrap_or(0.0); let turned = rows.iter().find(|row| angle(row) != 0.0).expect("Rotate View lists an angle other than 0").clone(); @@ -297,7 +306,10 @@ fn a_view_turned_on_the_canvas_moves_the_rotate_view_check() { #[test] fn a_new_font_rebuilds_the_menus() { const FAMILY: &str = "Menurebuild Sans"; - let Some((mut app, ctx)) = settled_app("menus::tests::a_new_font_rebuilds_the_menus") else { return }; + if !crate::testing::in_own_process("menus::tests::a_new_font_rebuilds_the_menus") { + return; + } + let (mut app, ctx) = settled_app(); let lists = |app: &VectorcraftApp| app.menus.bar.items().into_iter().any(|it| it.command.id == "text.setStyle" && it.command.params["font"] == FAMILY); assert!(!lists(&app)); From 1922ba20c901a6bd790eaabf7992a48e8302d03b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:25:21 -0800 Subject: [PATCH 401/533] Scripts: ExportOptionsAutoCAD.unitScaleRatio is a percentage The scripting reference gives unitScaleRatio as the ratio, as a percentage, by which the output is scaled, from 0 to 1000. exportFile passed it to the DXF writer as drawing units per unit, so 100 wrote the drawing 100 times too large and 1 wrote it at full size. - The value is divided by 100 before it reaches the DXF writer, and a value left out still writes at full size (100). - A value below 0.0001, which the writer's smallest scale cannot represent, throws a range error at the script instead of an error about the DXF scale from the writer. - docs/mcp.md describes the percentage and the default of 100. The option was added in #9266. --- crates/engine/src/script/dom/save_open.rs | 14 ++++--- crates/engine/src/tests/script_save_open.rs | 41 +++++++++++++++++++-- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 49 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b2f33027c5..b95a485259 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -31,8 +31,8 @@ //! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not //! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page //! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to -//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one -//! `unit`, more than 0 and at most 1000. +//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is +//! one drawing unit. It is at least 0.0001 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -738,10 +738,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: Data::Number(n) if n.is_finite() => *n, _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }; - if !(n > 0.0 && n <= 1000.0) { - return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + // A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is + // 0.0001%. + if !(0.0001..=1000.0).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000"))); } - p.insert("scale".into(), json!(n)); + p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start()))); } "version" => { let version = match pick("AutoCADCompatibility")? { @@ -1006,7 +1008,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 52fc48cf73..a4f1edec3b 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -578,9 +578,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ - o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ - o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" @@ -594,7 +594,8 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); - assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + // The DXF writes six decimals. + assert!((dxf_widest(&a) - dxf_widest(&b) * 10.0).abs() < 1e-4, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); @@ -606,6 +607,34 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let _ = std::fs::remove_dir_all(base); } +/// `unitScaleRatio` is a percentage: 100 writes the drawing at the size an option left out gives, +/// and 200 writes it twice as wide. +#[test] +fn an_autocad_unit_scale_ratio_is_a_percentage() { + let base = folder("autocad-ratio"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF;\n\ + d.exportFile(new File(dir + '/n'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/h'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 200; d.exportFile(new File(dir + '/t'), ExportType.AutoCAD, o);\n\ + vc.log(1);" + ), + ); + let width = |name: &str| dxf_widest(&std::fs::read_to_string(dir.join(name)).unwrap()); + let (n, h, t) = (width("n.dxf"), width("h.dxf"), width("t.dxf")); + assert!((h - n).abs() < 1e-6, "100 is full size: {h} and {n}"); + assert!((t - 2.0 * n).abs() < 1e-5, "200 is twice the size: {t} and {n}"); + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -1071,6 +1100,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "at most 1000", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 0.00001; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD.unitScaleRatio must be at least 0.0001", + ), ( format!( "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" diff --git a/docs/mcp.md b/docs/mcp.md index 8507629dc6..84fd2ddae8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3326,10 +3326,10 @@ through `$`: `ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/) and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version` (`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`, - `unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`, + `unitScaleRatio` (a percentage: at 100 one `unit` is one drawing unit; at least 0.0001 and at most 1000), `colors`, `rasterFormat`, `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and - `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 100, VectorCraft's own values. `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and `AutoCADColors.TrueColors` throws an error. `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c135dc04fe..b854df5cd5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1126,7 +1126,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - 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/). From b51d13d2a4d72cf233227e8bcf9dc050fa75c2cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:28:48 -0800 Subject: [PATCH 402/533] New document: a replayed rows count over 1000 is kept to 1000 A file.new step replayed from a journal or the Actions panel rounded artboardLayout.rows and then refused a result over 1000, so a step with rows 1000.5 or 5000 stopped the playback. The rows count now follows the columns rule: it is rounded, must be 1 or more, and is kept to at most 1000. Recent stores the kept count. docs/mcp.md says the same. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/tests/newdoc.rs | 7 ++++++- crates/engine/src/tests/script_dom.rs | 4 ++-- docs/mcp.md | 2 +- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 79ce3f97fa..3dc7f579d8 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -395,7 +395,7 @@ impl DocSettings { } "rows" => { self.rows = if replaying { - v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 200792d5fe..a320b09b18 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -219,6 +219,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { ("rows", 2.4, 2), ("rows", 0.6, 1), ("rows", 1000.4, 1000), + ("rows", 1000.6, 1000), + ("rows", 5000.0, 1000), ] { let mut p = json!({"width": 10, "height": 10, "artboards": 4, "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); @@ -236,8 +238,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { p["artboardLayout"][key] = json!(expected); } assert_eq!(boards(&s), boards(&new_doc(p))); + if key == "rows" { + assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}"); + } } - for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] { let mut p = json!({"artboardLayout": layout}); p["artboardLayout"]["layout"] = json!("gridByColumn"); let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ca827eb2ab..e4d2f62350 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1306,10 +1306,10 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { #[test] fn file_new_replays_legacy_fractional_and_large_rows() { - for (rows, rounded) in [(3.6, 4), (1000.4, 1000)] { + for (rows, rounded) in [(3.6, 4), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] { let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); let mut s = Session::new(); - // A direct call refuses a fraction; a replay rounds it to a count from 1 to 1000. + // A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000. let direct = Session::new().execute("file.new", ¶ms); assert!(direct.is_err(), "{rows}: {direct:?}"); s.replay("file.new", ¶ms).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 5a0fb08062..14fd04a184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -636,7 +636,7 @@ left out or null; `appearance.setActiveItem` reads a null `index` as clearing th whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of -1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000. +1 or more is rounded and kept to at most 1000, and a `rows` is rounded, must then be 1 or more, and is kept to at most 1000. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value From a7c6ff1d4304f87303f779455041c4fb123d7c32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:45:14 -0800 Subject: [PATCH 403/533] Scripts: clipped = true refuses a hidden or locked topmost object Assigning `clipped = true` to a GroupItem checked only that the group and its layer were editable, so a hidden or locked topmost object lost its fill and stroke and became the clipping path. The setter now refuses that object before running the command, with no undo step. The setter came from #9048. --- crates/engine/src/script/dom/layers.rs | 12 +++++++++-- crates/engine/src/tests/script_dom.rs | 29 ++++++++++++++++++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..39a0934d52 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1005,11 +1005,16 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer { } /// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the -/// clipping mask. The group keeps its id either way. +/// clipping mask. The group keeps its id either way. A hidden or locked topmost object is refused +/// before it loses its paint. fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "clipped")?; let item = this_item_of(h, a, "GroupItem")?; - let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + let (now, ok, top) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let top = d.node(item.id).and_then(|n| n.children()).and_then(|c| c.iter().rev().find(|c| !c.is_ruler_guide())).map(|c| c.id); + (d.node(item.id).is_some_and(crate::doc::Node::clips), editable(d, item.id), top.filter(|t| !editable(d, *t))) + }); if now == on { return Ok(Data::Undefined); } @@ -1017,6 +1022,9 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } + if let Some(t) = top.filter(|_| on) { + return Err(HostError::Error(format!("Cannot clip GroupItem {}: its topmost object {} is hidden or locked", item.id.0, t.0))); + } on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..0fc770b819 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3263,6 +3263,35 @@ fn clipped_setter_refuses_locked_artboards_layers_and_groups() { } } +#[test] +fn clipped_setter_refuses_a_hidden_or_locked_topmost_object() { + for hidden in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Protect", |d, _| { + let n = d.node_mut(b).unwrap(); + if hidden { + n.visible = false; + } else { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('changed'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "hidden {hidden}: {out:?}"); + assert_eq!(out[1], json!(false)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b).unwrap().appearance), before); + assert_eq!(undo_steps(&s), steps); + } +} + #[test] fn scoped_collections_convert_to_strings() { let (mut s, ..) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..6e6a2d86ec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3311,7 +3311,8 @@ through `$`: operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is - hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer + hidden or locked, or its artboard is locked, and `true` is also refused when the topmost object is hidden or + locked. A scoped `removeAll()` that leaves a clipping group or layer without art releases its mask in the same undo step. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` makes an empty compound path in the same place diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..fe09d6fd46 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1125,7 +1125,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks, including a hidden or locked topmost object that would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. From 99a04b9a78e584879e2a7ad37100f8179e8dbbe9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:52:07 -0800 Subject: [PATCH 404/533] Scripts: transforms keep path strokes within 1000 points and take empty paths `resize` and `transform` with `changeLineWidths` at the transformation's own scale scaled a path's strokes past the 1000-point limit that other line widths enforce, and could store a NaN weight for a scale too large for a number. Every stroke layer the transformation scales is now checked against the limit with the factor the transformation applies. `rotate`, `resize` and `transform` threw "the object has no bounds" on a path without points whenever the call named or defaulted to a point of the bounds. Such a path now takes the transformation about the origin, or the first artboard's bottom-left corner for `Transformation.DOCUMENTORIGIN`, so its linked mask, strokes, effects and patterns still transform. Both faults came in with #9295. --- crates/engine/src/script/dom/paths.rs | 14 +++++ crates/engine/src/script/dom/transform.rs | 41 +++++++++--- .../engine/src/tests/script_dom_transform.rs | 63 +++++++++++++++++++ docs/mcp.md | 12 ++-- 4 files changed, 116 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 50cd224f44..6761a0a40c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1156,6 +1156,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) } +/// The largest stroke weight in the path `item`'s own appearance, in points. +pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |_, n, _| { + n.appearance + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .fold(0.0, f64::max) + }) +} + /// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. pub(super) fn is_path(h: &super::Host, item: Item) -> bool { with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 6c07a070e1..1102a09450 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -20,9 +20,13 @@ //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale //! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to -//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any -//! other value, and a scale of strokes and effects with positions left as they are, throws an -//! error that says so. +//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. +//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight +//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale +//! of strokes and effects with positions left as they are, throws an error that says so. +//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` +//! still uses the first artboard's bottom-left corner; other named points use the origin. +//! Its linked opacity mask, strokes, effects and patterns transform with the same options. //! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a //! locked object, and an object on a locked artboard are refused with nothing changed, and so are //! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object @@ -132,8 +136,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { } /// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` -/// ([`anchor_name`]) names. -fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result { +/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. +fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { + if r.is_none() && !paths::is_path(h, item) { + return Err(HostError::Error("the object has no bounds".into())); + } + if name == "DOCUMENTORIGIN" { + return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); + } + let Some(r) = r else { + return Ok(Point::ORIGIN); + }; let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); Ok(match name { "TOPLEFT" => Point::new(r.x0, r.y0), @@ -144,7 +157,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result Point::new(r.x0, r.y1), "BOTTOM" => Point::new(cx, r.y1), "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, _ => Point::new(cx, cy), }) } @@ -215,12 +227,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } - // The identity acts the same about every point, so an object without bounds (an empty path) - // takes it too. + // The identity acts the same about every point for any object. let o = match (about, bounds) { _ if m == IDENTITY => Point::ORIGIN, - (Some(name), Some(r)) => anchor(h, item, r, name)?, - (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (Some(name), r) => anchor(h, item, r, name)?, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); @@ -242,6 +252,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, } let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; + // Every stroke layer's weight is checked with the factor `object.transform` applies. + let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; + if let Some(k) = factor + && paths::is_path(h, item) + && (!k.is_finite() || { + let width = paths::largest_stroke_weight(h, item)? * k; + !width.is_finite() || width > paths::MAX_STROKE_WIDTH + }) + { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; // The transformation and the stroke weight change together or not at all. atomically(h, |h| { diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index d57d4570d5..f3aa67c361 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -130,6 +130,69 @@ fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); } +#[test] +fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() { + let (mut s, _, _) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains("more than 1000 points"), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A scale that keeps the weight within the limit still scales it. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);"); + assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}"); + + // The lower stroke must stay within the limit too. + let (mut s, a, _) = doc(); + s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap(); + s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + + // A nonfinite scale must not turn a zero-width stroke into NaN. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); +} + +#[test] +fn an_empty_path_takes_any_transformation_about_any_point() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.add();"); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\ + n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\ + vc.log(n.pathPoints.length);", + ); + assert_eq!(out, vec![json!(0)]); + // Its stroke weight still scales with the transformation. + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);", + ); + assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');"); + assert!(e.contains("Transformation value"), "{e}"); +} + #[test] fn transform_applies_a_matrix_record_about_the_center() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 8507629dc6..75d6f17110 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3181,13 +3181,17 @@ through `$`: object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is, so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and `transform` act about the center of the geometric bounds unless a `Transformation` value names another point of - them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients - default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different + them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. A path without points takes + any of them about any point named. `Transformation.DOCUMENTORIGIN` still uses the first artboard's bottom-left + corner; other named points use the origin. Its linked opacity mask, strokes, effects and patterns transform with + the same options. Positions and gradients default to `true` and patterns to the Transform Pattern Tiles + preference. Fill and stroke patterns with different values, and gradients different from positions, counting the defaults of arguments left out, throw an error that says they are not available yet. `changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the - square root of the area it scales by (stroke weights and effects scale with it). `resize` on a path also takes any - other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, + square root of the area it scales by (stroke weights and effects scale with it; the scale and every stroke layer's + resulting weight on a path must stay finite, and a weight that would pass 1000 points throws). `resize` on a path + also takes any other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, at most 1000 points). On a member of a compound path or compound shape, the compound's stroke weight follows the percent through `stroke.set`; when the percent is the resize's own scale, the member's own strokes and effects also scale with it. `transform` with `changeLineWidths` at the matrix's own scale sets the compound's stroke weight the From a227132cac646ab1666bc103619ed21e82c75e60 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:58:11 -0800 Subject: [PATCH 405/533] Docs: clipped = true alone checks the topmost object --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fe09d6fd46..a828afc2da 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1125,7 +1125,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks, including a hidden or locked topmost object that would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. From cca97099a7cabeaf9fe4635613fd03da77073648 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:02:52 -0800 Subject: [PATCH 406/533] Scripts: image matrix assignment refuses locked and hidden images Assigning `matrix` to a placed or raster image ran `object.transform` on a locked or hidden image, an image inside a locked or hidden layer or group, and an image on a locked artboard. The transform methods (`translate`, `rotate`, `resize`, `transform`) refuse all of these with nothing changed. The setter now refuses them with the same errors, before the unchanged matrix check, so assigning the current matrix to such an image throws too. The locked artboard check uses the cached lookup that `editable` uses. The setter came in with #9062. Docs: docs/mcp.md. --- crates/engine/src/script/dom/images.rs | 19 ++++++++++- crates/engine/src/script/dom/transform.rs | 6 ++-- crates/engine/src/tests/script_dom_images.rs | 35 ++++++++++++++++++++ docs/mcp.md | 4 ++- 4 files changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index ec2c7997cf..41711ad12e 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -473,7 +473,8 @@ fn area_of(m: Affine) -> bool { /// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. /// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted -/// image is refused before anything changes; the matrix the image has already changes nothing. +/// image is refused before anything changes, and so is a locked or hidden image or one on a locked +/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing. fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { let item = this_of(h, a, cls)?; let m = matrix_value(arg(a, 1))?; @@ -484,6 +485,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { if n.is_distorted_image() { return Err(HostError::Error(DISTORTED.into())); } + // The transform methods' refusals: a locked or hidden image, one inside a locked or hidden + // layer or group, and one on a locked artboard, whether or not the matrix changes. + let d = &st.doc; + let line = d.ancestry(item.id); + let any = |f: fn(&vectorcraft_doc::Node) -> bool| { + line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f))) + }; + if any(|n| n.locked) { + return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0))); + } + if any(|n| !n.visible) { + return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0))); + } + if super::on_locked_artboard(h, st, item.id) { + return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0))); + } let f = frame(st)?; let target = Affine::new(match h.dom.coords.get() { Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 6c07a070e1..e4834de923 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -36,13 +36,13 @@ use super::matrix::{self, Matrix}; use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; /// The error for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; /// The error for a locked object. -const LOCKED: &str = "cannot transform locked objects"; +pub(super) const LOCKED: &str = "cannot transform locked objects"; /// The error for a hidden object. -const HIDDEN: &str = "cannot transform hidden objects"; +pub(super) const HIDDEN: &str = "cannot transform hidden objects"; /// The identity matrix. const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index ac1e9ca782..646d4f2e2a 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -497,6 +497,41 @@ fn a_stale_placed_item_is_not_a_relative_object() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_matrix_refuses_locked_hidden_and_locked_artboard_images() { + let base = folder("matrix-locks"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + // A moved matrix and the matrix the image already has are refused alike. + let sets = [ + "var p = app.activeDocument.placedItems[0], m = p.matrix; m.mValueTX = m.mValueTX + 5; p.matrix = m;", + "var p = app.activeDocument.placedItems[0]; p.matrix = p.matrix;", + ]; + let refused = |s: &mut Session, message: &str| { + for set in sets { + let (was, before) = (s.active().unwrap().doc.clone(), undo_steps(s)); + let e = failure(s, &base, set); + assert!(e.contains(message), "{set}: {e}"); + assert_eq!(*s.active().unwrap().doc, *was, "{set}"); + assert_eq!(undo_steps(s), before, "{set}"); + } + }; + for (field, set_to, message) in [("locked", true, "cannot transform locked objects"), ("visible", false, "cannot transform hidden objects")] { + s.execute("object.setProps", &json!({"ids": [id.0], field: set_to})).unwrap(); + refused(&mut s, message); + s.execute("object.setProps", &json!({"ids": [id.0], field: !set_to})).unwrap(); + } + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + refused(&mut s, "cannot transform objects on a locked artboard"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_matrix_refuses_bad_values_without_changing_the_image() { let base = folder("matrix-bad"); diff --git a/docs/mcp.md b/docs/mcp.md index 90aefa32ce..b560031dc0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3507,7 +3507,9 @@ through `$`: that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning `matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a - nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + nearly singular image cannot reach exactly throw an error with nothing changed. Assigning `matrix` to a locked or + hidden image, one inside a locked or hidden layer or group, or one on a locked artboard throws the transform methods' + error with nothing changed, even when the matrix is unchanged. `boundingBox` is the pixel rectangle at one point a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` From f83b121a46c565c1332562e7e7fd81a9533c6bec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:06:48 -0800 Subject: [PATCH 407/533] xtask: census rule ignores a continue in a nested loop that never runs A labeled continue inside a nested `for` over a literal source that yields nothing (`for _ in 0..0`) never executes, so it does not skip the rest of the outer iteration, and the command call after that loop always runs. A nested loop that runs (`0..1`) still makes the continue skip the call. --- xtask/src/test_lint.rs | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5ebd082af4..f70abd6da0 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2790,15 +2790,18 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac /// inside a nested `for`, `while` or `loop` body. A labeled `continue` inside a nested loop with the /// same label targets that nested loop. Only a `continue` that starts an expression counts, not one /// inside the tokens of a macro that does not run them (`stringify!(continue)`) or a raw identifier -/// (`r#continue`). A `continue` at the start of the body counts. A `break` in +/// (`r#continue`). A `continue` inside a nested `for` over a literal source that yields nothing +/// (`for _ in 0..0`) never runs and does not count. A `continue` at the start of the body counts. A `break` in /// the body already rules out a census hit, so only `continue` is read here. fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[u8]>) -> bool { let label_at = |at: usize| { let name = &b[at..]; &name[..name.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count()] }; - // The labels of the nested loops whose bodies hold `at` (`None` for a loop without a label). - let nested_loops = |at: usize| -> Vec> { + // The labels of the nested loops whose bodies hold `at` (`None` for a loop without a label), each + // with whether the loop is a `for` over a literal source that yields nothing (`0..0`), so that + // its body never runs. + let nested_loops = |at: usize| -> Vec<(Option<&[u8]>, bool)> { (open + 1..at) .filter(|&k| b[k] == b'{' && matching(b, k).is_some_and(|close| at < close)) .filter_map(|k| { @@ -2826,7 +2829,8 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ } None => (None, head), }; - [b"for".as_slice(), b"while", b"loop"].iter().any(|kw| words(head, kw, 0, head.len()).first() == Some(&0)).then_some(inner) + let kw = [b"for".as_slice(), b"while", b"loop"].into_iter().find(|kw| words(head, kw, 0, head.len()).first() == Some(&0))?; + Some((inner, kw == b"for" && literal_source_yields(head) == Some(false))) }) .collect() }; @@ -2851,9 +2855,11 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ let quote = skip_ws(b, at + b"continue".len()); if b.get(quote) == Some(&b'\'') { let name = label_at(quote + 1); - return label == Some(name) && !nested.contains(&Some(name)); + // A `continue` inside a nested loop whose body never runs never executes. + label == Some(name) && !nested.iter().any(|&(inner, never_runs)| never_runs || inner == Some(name)) + } else { + nested.is_empty() } - nested.is_empty() }) } @@ -10587,6 +10593,22 @@ mod tests { ); } + #[test] + fn census_ignores_a_continue_in_a_nested_loop_that_never_runs() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("'outer: for _ in &[1] { for _ in 0..0 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue in a nested loop that never runs does not skip the call" + ); + assert_eq!( + census("'outer: for _ in &[1] { for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in a nested loop that runs skips the call" + ); + } + #[test] fn census_needs_evidence_that_the_call_runs_on_the_entry() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From e00a12ac60e0d99a010ca3bff6fd543cdef73213 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:14:13 -0800 Subject: [PATCH 408/533] Render: only a measurement ages the canvas renderer's caches Renderer::changed set the measuring flag before it compared anything, so comparing a document with itself still made the next finish_measurement_only sweep the paths of the last frame. The flag is now set where the diff measures an object through the renderer, in the Trim View check (children_blend caches the groups it reads), and when a change outside the layers redraws everything, so bounds kept for old symbol definitions still expire. --- crates/render/src/changed.rs | 17 +++++++++++++++-- crates/render/src/tests/memory.rs | 24 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index e7ab2c01ef..c0efa55a0b 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -96,16 +96,25 @@ impl crate::Renderer { /// renderer draws copies of the objects (`proof::prepare`), so they are measured afresh and /// nothing is held. pub fn changed(&mut self, old: &Document, new: &Document, opts: &crate::RenderOptions) -> Changed { - self.measuring = true; // Trim View clips each draw when blending reaches the page and clips one composited // layer otherwise. Changing modes can change unchanged art at an artboard edge. if opts.trim && !old.artboards.is_empty() { + // `children_blend` caches the groups it reads in `blends`, which holds their nodes, + // so this counts as a measurement for `finish_measurement_only`. + self.measuring = true; let before = crate::proof::prepare(old, opts, &mut self.proof_art); let after = crate::proof::prepare(new, opts, &mut self.proof_art); if self.children_blend(&before.layers) != self.children_blend(&after.layers) { return Changed::Everything; } } + // A change outside the layers (symbol definitions among them) redraws everything without + // measuring anything here; the caches still age so that bounds kept for the old + // definitions expire. + if new.pattern_edit.is_some() || !old.same_outside_layers(new) { + self.measuring = true; + return Changed::Everything; + } let renderer = (!crate::proof::overprints(opts)).then_some(self); changed_with(old, new, renderer, opts) } @@ -250,7 +259,11 @@ impl Diff<'_, '_> { Side::New => new, }; match renderer { - Some(r) => r.bounds_of(symbols, n), + Some(r) => { + // Only a measurement ages the renderer's caches in `finish_measurement_only`. + r.measuring = true; + r.bounds_of(symbols, n) + } None => crate::brush_fx::cull_bounds(symbols, n), } } diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 2e890606bd..023a62bad3 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -58,6 +58,30 @@ fn finishing_without_a_measurement_keeps_the_drawn_paths() { assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); } +/// Comparing a document with itself measures nothing, so the frames that follow keep the paths +/// this renderer drew. +#[test] +fn an_unchanged_document_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + let opts = RenderOptions::default(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &opts); + for _ in 0..4 { + assert!(matches!(renderer.changed(&doc, &doc, &opts), Changed::Nothing)); + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { From 6826f306ae0feabcb3184dc21f9f95b50374272a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:15:18 -0800 Subject: [PATCH 409/533] Scripts: palette tests check the post-limit refresh and the list revision The engine test now records what the palette's getter plays only after the handler starts, and asserts that a refresh ran after the limit with the run's own actions. The list test turns the item's text getter back into a plain text before it replaces the items, so only the revision check rejects the choice. --- crates/engine/src/tests/script_palettes.rs | 17 +++++++++++------ crates/js/src/scriptui_tests.rs | 10 ++++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 28cf359dc1..cf873ec324 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -742,17 +742,22 @@ fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { #[test] fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { let mut s = one_doc(); - let (id, _) = acts_palette(&mut s, "for (;;) {}"); + let (id, _) = acts_palette(&mut s, "started = true; for (;;) {}"); + // The getter records what it plays only once the handler has started, so a read before the + // click is taken does not count. run( &mut s, - "#targetengine acts\nvar played = 'none'; Object.defineProperty(p, 'text', {get: function () { \ - try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } return 'P'; }});", + "#targetengine acts\nvar started = false; var after = []; Object.defineProperty(p, 'text', {get: function () { \ + var played; try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } \ + if (started) { after.push(played); } return 'P'; }});", ) .unwrap(); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); - assert!(run(&mut s, "#targetengine acts\nplayed = 'none'; p.update();").is_err(), "the handler's loop ends the run"); - let log = run(&mut s, "#targetengine acts\nvc.log(played);").unwrap()["log"].clone(); - assert_eq!(log, json!(["own"]), "the refresh after the limit plays the run's own actions, not the palette's"); + assert!(run(&mut s, "#targetengine acts\nstarted = false; after = []; p.update();").is_err(), "the handler's loop ends the run"); + let log = run(&mut s, "#targetengine acts\nvc.log(after.join(' '));").unwrap()["log"].clone(); + let after = log[0].as_str().unwrap_or_default(); + assert!(!after.is_empty(), "the palette is refreshed after the handler hit its limit: {log}"); + assert!(after.split(' ').all(|p| p == "own"), "the refresh after the limit plays the run's own actions, not the palette's: {log}"); } #[test] diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 6e3f5ffa1c..11bde4ca26 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1099,12 +1099,14 @@ fn a_palette_list_change_after_an_item_s_text_changed_throws() { fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() { let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]); // The event reads the first item's text twice: for the palette's description, then to compare - // it with the items the person saw. The second read replaces the items with ones of the same - // texts. + // it with the items the person saw. The second read turns the getter back into a plain text and + // replaces the items with ones of the same texts, so only the list's revision tells them apart. r.run( "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ - l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ - Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ + l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; var first = l.items[0]; \ + Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \ + Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \ + l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \ p.show();", ) .unwrap(); From 774762bbf6d08be9ecf27b0043de1557280147df Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:27:36 -0800 Subject: [PATCH 410/533] Print: file.print refuses a null paper, and only the local scheduler's sockets read its PPDs `file.print` treated `paper: null` like an omitted `paper`; a null value is now an error, as the params text already says for anything but a keyword. The Print dialog leaves `paper` out of its job when the driver lists no keyword for the Size chosen. A `CUPS_SERVER` or `ServerName` that names a domain socket counted as this machine's scheduler for any path, so the dialog read `/etc/cups/ppd` for a second scheduler on another socket. Only CUPS's own sockets, the sockets the `Listen` lines of `/etc/cups/cupsd.conf` name, and links to either now read the local PPDs. The IPP lookup asks `localhost:631` for CUPS's own sockets and links to them only. A `\#` in a `cupsd.conf` path keeps its `#`, as in `client.conf`. Follows up #10581. --- apps/vectorcraft/src/printing.rs | 133 +++++++++++++++++----- crates/ui-egui/src/dialogs/print.rs | 7 +- crates/ui-egui/src/dialogs/tests_print.rs | 2 +- crates/ui-egui/src/print.rs | 6 +- docs/mcp.md | 7 +- 5 files changed, 117 insertions(+), 38 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 4eb39067a0..651be6f6a3 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -177,9 +177,10 @@ mod system { return Vec::new(); } let named = cups_server(); + let sockets = local_sockets(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref()) { + if scheduler_is_local(named.as_deref(), &sockets, real_path) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -199,7 +200,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - let server = ipp_server(named, |s| std::path::Path::new(s).exists()); + let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -234,17 +235,52 @@ mod system { /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. #[cfg(not(windows))] const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server - /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default - /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local - /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job - /// does not go to. + /// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS). + #[cfg(not(windows))] + pub(super) fn real_path(path: &str) -> Option { + std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned()) + } + /// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add. + #[cfg(not(windows))] + pub(super) fn local_sockets() -> Vec { + use std::io::Read as _; + let mut text = String::new(); + let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text)); + cupsd_listen_sockets(if read.is_ok() { &text } else { "" }) + } + /// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`. + #[cfg(not(windows))] + pub(super) fn cupsd_listen_sockets(text: &str) -> Vec { + let listed = text.lines().filter_map(|line| { + let line = cups_conf_line(line); + let (key, value) = line.trim().split_once(char::is_whitespace)?; + let value = value.trim(); + (key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string()) + }); + CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect() + } + /// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the + /// real paths of both. + #[cfg(not(windows))] + fn is_local_socket(path: &str, sockets: &[impl AsRef], resolve: impl Fn(&str) -> Option) -> bool { + let path = path.trim(); + let real = resolve(path); + sockets.iter().any(|s| { + let s = s.as_ref(); + s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real)) + }) + } + /// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path. + /// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` + /// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A + /// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named, + /// and the lookup is skipped. /// /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri #[cfg(not(windows))] - pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option) -> Option { match named { - Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None, Some(server) => Some(server), None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), } @@ -268,14 +304,15 @@ mod system { client_conf_server_name(&text) }) } - /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback - /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. + /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain + /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder + /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] - pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option) -> bool { let Some(server) = server.map(str::trim) else { return true }; if server.starts_with('/') { - return true; + return is_local_socket(server, sockets, resolve); } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); @@ -289,17 +326,22 @@ mod system { let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; loopback && port.is_none_or(|port| port.trim() == "631") } - /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. #[cfg(not(windows))] + fn cups_conf_line(line: &str) -> String { + match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + } + } + /// The last `ServerName` in a `client.conf`. + #[cfg(not(windows))] pub(super) fn client_conf_server_name(text: &str) -> Option { text.lines().rev().find_map(|line| { - let kept = match line.find('#') { - Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), - Some(at) => line[..at].to_string(), - None => line.to_string(), - }; + let kept = cups_conf_line(line); let (key, value) = kept.trim().split_once(char::is_whitespace)?; (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) }) @@ -604,18 +646,47 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { let none = |_: &str| false; let socket = |s: &str| s == "/run/cups/cups.sock"; - assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); - assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); - assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); - assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); - assert_eq!(ipp_server(None, socket), None); - assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + let real = |_: &str| None; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None); + assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket"); + let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked); + assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket, real), None); + assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost")); + } + + #[test] + fn a_socket_the_local_cupsd_listens_on_counts_as_local() { + let real = |_: &str| None; + let sockets = cupsd_listen_sockets( + "Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n", + ); + assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue"); + assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing"); + assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock")); + assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock")); + } + + /// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`. + fn linked(path: &str) -> Option { + path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}")) + } + + #[test] + fn a_socket_path_counts_as_local_only_when_it_is_cups_own() { + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder"); + assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler"); + assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked)); } #[test] @@ -623,6 +694,8 @@ mod client_conf_tests { for local in [ None, Some("/run/cups/cups.sock"), + Some(" /var/run/cups/cups.sock "), + Some("/private/var/run/cupsd"), Some("localhost"), Some("LocalHost:631"), Some("localhost:631"), @@ -633,7 +706,7 @@ mod client_conf_tests { Some("localhost/version=1.1"), Some("localhost:631/version=1.1"), ] { - assert!(scheduler_is_local(local), "{local:?}"); + assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}"); } for remote in [ "print.example.com", @@ -647,8 +720,10 @@ mod client_conf_tests { "127.0.0.1:8631", "[::1]:8631", "localhost:8631/version=1.1", + "/tmp/other.sock", + "/home/me/.cups/second.sock", ] { - assert!(!scheduler_is_local(Some(remote)), "{remote}"); + assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}"); } } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 3e58a287d5..0c40db4157 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -850,8 +850,11 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st app.run("print.setup", json!({ "settings": settings }))?; match answer.finish { PrintFinish::Print => { - let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None }; - let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper }); + let mut job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf }); + // `paper` is left out when there is none: `file.print` refuses a null one. + if applies_paper && let Some(paper) = driver_paper_key(&answer.fields, &open.papers.1) { + job["paper"] = json!(paper); + } crate::print::run(app, &job).map(|_| ()) } // Done only keeps the settings. diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 35675bda64..8004a75e52 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -814,7 +814,7 @@ fn the_job_asks_the_queue_for_the_driver_paper_chosen() { // Without the dialog, the keyword is given as `paper`, and anything else is refused before printing. app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap(); assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm")); - for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] { + for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4), json!(null)] { assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}"); } assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err()); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index c318aa4aa7..5276329c86 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -411,11 +411,11 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result, jo Ok(notes) } -/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable -/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error. +/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent: none). Anything but printable +/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, null included, is an error. fn paper_param(p: &Value) -> Result, String> { match p.get("paper") { - None | Some(Value::Null) => Ok(None), + None => Ok(None), Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())), Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")), } diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..cd96bd62fe 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13526,12 +13526,13 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or -remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, +remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than CUPS's own domain socket, a socket a `Listen` line of `/etc/cups/cupsd.conf` names (or a link to either), `localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is -asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the -server is asked as `localhost` on port 631; another socket path is not asked. +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. When CUPS's own domain socket +or a link to one is named as the server, the lookup asks `localhost` on port 631. Other socket paths, including those added only by +`cupsd.conf` `Listen` lines, are not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. From 0d8a56cfde36e5c836b813ee45539c673b8ff6fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:44:26 -0800 Subject: [PATCH 411/533] Scripts: zOrderPosition reuses the layer list; textFrames.removeAll releases masks - Layer.zOrderPosition reads the sibling list through the cached layer lists, so reading it for every layer of a loop lists the layers once. Each read is still charged for the search through the list. - TextFrames.removeAll releases the mask of a group or layer whose clipping path is one of the type objects it deletes, as PageItems.removeAll and remove() do, so the object above the type is not made the clipping path. - GroupItems.createFromFile checks that its collection is still there first, so a collection whose group was deleted throws "Stale page item" instead of the not-available message. docs/mcp.md says so. --- crates/engine/src/script/dom.rs | 6 ++++- crates/engine/src/script/dom/layers.rs | 14 ++++++----- crates/engine/src/script/dom/text.rs | 10 +++++--- crates/engine/src/tests/script_dom.rs | 33 ++++++++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 27 +++++++++++++++++++++ docs/mcp.md | 3 ++- 6 files changed, 82 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4c14498fe7..a0bd117d11 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -470,7 +470,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, layer, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point, text range or `GroupItems` collection +/// `this` is still there. /// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and /// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { @@ -495,6 +496,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "TextRange" => { text::check_range(&h, arg(&a, 0))?; } + "GroupItems" => { + layers::check_groups(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 8ca6423ea4..0b1b1f0e57 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -295,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let parent = st.doc.parent_of(id); - let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); - h.charge_call(count as u64)?; - let list = layer_list(&st.doc, parent); + let list = layers_listed(h, st, st.doc.parent_of(id))?; h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -1356,9 +1354,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer { Ok(text("[Layers]")) } fn groups_to_string(h: &Host, a: &[Data]) -> Answer { - art_scope(h, arg(a, 0), Kind::Group.class())?; + check_groups(h, arg(a, 0))?; Ok(text("[GroupItems]")) } +/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone. +pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> { + art_scope(h, d, Kind::Group.class()).map(|_| ()) +} fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { art_scope(h, arg(a, 0), Kind::Compound.class())?; Ok(text("[CompoundPathItems]")) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index ab6a86222b..0555782952 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1480,13 +1480,16 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { /// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + // Type that clips a group or layer releases its mask, so the object above it is not made + // the clipping path. + let released = super::masks_cleared_by(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1497,7 +1500,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); + super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; } Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7ebc1c2c40..8bc97bffe9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3714,6 +3714,39 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// Reading `zOrderPosition` for every layer lists the layers once while the document is unchanged. +#[test] +fn z_order_position_of_each_layer_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, k = L.length, z = []; for (var i = 0; i < k; i++) { z.push(L[i].zOrderPosition); } vc.log(z[0]); vc.log(z[k - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// `groupItems.createFromFile` on a collection whose group is gone reports the stale object before +/// the member that is not available yet. +#[test] +fn create_from_file_on_a_stale_group_collection_reports_it_stale() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var g = app.activeDocument.groupItems[0], c = g.groupItems; g.remove(); c.createFromFile(new File('x.svg'));"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.groupItems[0].groupItems.createFromFile(new File('x.svg'));"); + assert!(e.contains("GroupItems.createFromFile is not available yet"), "{e}"); +} + /// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the /// document's `pageItems`, also when the list was already built. #[test] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index cd4bc2f704..f64777a123 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -731,6 +731,33 @@ fn text_frames_of_a_layer_or_group_put_new_type_in_it() { assert_eq!(undo_steps(&s), before); } +/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the +/// type stays an ordinary member and is not made the clipping path. +#[test] +fn text_frames_remove_all_releases_a_mask_the_type_clips() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id); + assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path"); + let steps = undo_steps(&s); + let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);"); + assert_eq!(out, [json!(false)]); + let st = s.active().unwrap(); + assert!(!st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // The run is one undo step, and undoing it puts back both the type and its mask. + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(first(&s), Some(NodeId(t))); +} + /// `textFrames.removeAll()` deletes nothing when a type object it lists is on a locked artboard. #[test] fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { diff --git a/docs/mcp.md b/docs/mcp.md index b2d366a7c4..8e2c1b01fb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3343,7 +3343,8 @@ through `$`: one. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `GroupItems.createFromFile` throw an error that says they are not available yet. `GroupItems.createFromFile` on a + collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and From 27e10129bdbd83d22dd5edb95c7a5e680e5cfca7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:44:27 -0800 Subject: [PATCH 412/533] Scripts: hasSelectedArtwork selects inside an isolated group and charges its scans While a group is isolated, `layer.hasSelectedArtwork = true` looked only at the layer's top-level art, which is not selectable in isolation, so it selected nothing. It now takes what Select All takes in isolation: the art inside the isolated group (through any sublayer it holds), or the isolated object itself, and nothing when the isolated object or what holds it is hidden or locked. While Lock Guides is on, paths made into guides are not counted as art to add, so they no longer trip the selection limit. Reading `hasSelectedArtwork` now counts each selected object it checks toward the script's operation budget, as the setter already did. Follows #9048, which added the property. --- crates/engine/src/script/dom/layers.rs | 36 +++++++++++++++-- crates/engine/src/tests/script_dom.rs | 56 ++++++++++++++++++++++++++ docs/mcp.md | 3 ++ 3 files changed, 91 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..bd0503ae81 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -305,7 +305,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer { fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; - Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) + let selected = with_doc(h, doc, |_, st| { + // The scan is charged by every selected object it looks at. + let objects = &st.selection.objects; + let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))); + h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?; + Ok::<_, HostError>(found.is_some()) + })?; + Ok(Data::Bool(selected)) } /// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every @@ -332,7 +339,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let (ids, over) = with_doc(h, doc, |_, st| { + let (ids, over) = with_doc(h, doc, |s, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; h.charge_call(selected.len() as u64)?; @@ -345,10 +352,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { // The walk is charged by every node it looks at, hidden and locked ones included, whether // or not anything is added. h.charge_call(count)?; + // While an object is isolated, the art that holds it is replaced by the isolated object, + // or by what an isolated group or other container holds, as Select All takes it. + let isolated = st.isolation.and_then(|i| st.doc.node(i)); + let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default(); + let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())); + let mut candidates = Vec::with_capacity(art.len()); + for o in art { + match isolated { + Some(_) if path.contains(&o) && !editable => {} + Some(c) if path.contains(&o) && c.is_container() => { + // The same walk as the layer's, through any sublayer the container holds. + let visited = collect_editable_art(c, &mut candidates); + h.charge_call(visited)?; + } + Some(c) if path.contains(&o) => candidates.push(c.id), + _ => candidates.push(o), + } + } let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); - for o in art { - if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + for o in candidates { + if have.contains(&o) + || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) + || (s.guides_locked() && crate::is_guide_path(&st.doc, o)) + { continue; } // Only art that would be added counts toward the limit. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..325b67e8f6 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3792,6 +3792,62 @@ fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { assert!(error.contains("passed more data"), "{error}"); } +/// Reading `hasSelectedArtwork` is charged for every selected object it looks at. +#[test] +fn has_selected_artwork_charges_the_selection_it_reads() { + let repeated = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + r + }; + repeated(1).unwrap(); + let error = repeated(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +/// While a group is isolated, `hasSelectedArtwork = true` selects the art inside the group, as +/// Select All does. +#[test] +fn has_selected_artwork_selects_inside_an_isolated_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true; vc.log(l.hasSelectedArtwork);"); + assert_eq!(out, [json!(true)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b), "{sel:?}"); +} + +/// While Lock Guides is on, a path made into a guide is not counted as art to add, so a selection +/// at the limit does not refuse a layer that holds only such a path. +#[test] +fn has_selected_artwork_skips_locked_guide_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.active_mut().unwrap().selection.objects = vec![other; 10_000]; + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_000); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..631108be31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3309,6 +3309,9 @@ through `$`: deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer with nothing to add or deselect runs no command. Each assignment counts the current selection toward the script's operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included. + While an object in the layer is isolated, `true` adds what Select All takes in isolation: the art inside an + isolated group, or the isolated object itself. Reading `hasSelectedArtwork` counts each selected object it checks + toward the same budget. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer From d3eb174b6d6e9fba6d323c58c3a573788d537459 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:07:05 -0800 Subject: [PATCH 413/533] Image Trace: object.newGroup at index 0 no longer ends a tracing An Image Trace object keeps its source image as its first child. object.newGroup with index 0 put the new group below that image, so the group stopped being a tracing. Index 0 in an Image Trace object is now refused before anything changes; index 1 puts the group directly above the source image. The index parameter came with #9048. --- crates/engine/src/cmd/object/arrange.rs | 8 ++++++-- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/tests/script_dom_tracing.rs | 16 ++++++++++++++++ docs/mcp.md | 4 +++- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 955520427c..8ed4656295 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -106,8 +106,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { } /// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a -/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The -/// selection stays as it is. +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom; refused +/// in an Image Trace object, whose source image stays at the bottom). The selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { const C: &str = "object.newGroup"; // Only an omitted key takes its default; `null` is refused like any other bad value. @@ -132,6 +132,10 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } + // An Image Trace object keeps its source image first; a group below it would end the tracing. + if index == 0 && crate::cmd::is_trace_group(n) { + return Err(bad(C, "index 0 of an Image Trace object is its source image; use index 1 or more")); + } let label = if compound { "Compound Path" } else { "Group" }; let gid = s.edit(label, |d, _| { let gid = d.alloc_id(); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index bea69d1698..4f9b2887ba 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "Group", [], None, - "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..0d28c8c8e9 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1271,6 +1271,22 @@ fn unimplemented_tracing_members_are_not_reported() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn new_group_at_the_bottom_of_a_tracing_is_refused() { + let base = folder("new-group-bottom"); + let (mut s, id) = session(&base, false); + let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string(); + assert!(e.contains("source image"), "{e}"); + assert_eq!(traces(&s), [tid]); + assert_eq!(undo_steps(&s), steps); + let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(traces(&s), [tid]); + assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..35772df192 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3337,7 +3337,9 @@ through `$`: `GroupItems.createFromFile` throw an error that says they are not available yet. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, - index 0 puts it directly above the clipping path), as one undo step named Group, and + index 0 puts it directly above the clipping path; in an Image Trace object, index 0 is refused and changes nothing, + since the source image stays at the bottom, and index 1 puts it directly above the source image), as one undo step + named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false). Explicit `null` is refused for `parent`, `index` and `compound`. From e10dc47ae897f17b586af2c16ebca2cd57674441 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:07:03 -0800 Subject: [PATCH 414/533] Scripts: doScript steps act on the artboard the script made active After a script called setActiveArtboardIndex, a paste or Fit to Artwork Bounds step that doScript played still went to the Artboard tool's selection from the start of the run, so it pasted on or fitted those artboards instead of the one the script chose. The script's choice now also replaces that selection, until a revert discards it. The choice was added in #9048 and the kept selection in #9055. --- crates/engine/src/script/actions.rs | 5 +++-- crates/engine/src/tests/script_actions.rs | 12 ++++++++++++ docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 8728bd76fb..0356db27d1 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the script chose uses that choice, not the one the run - // started with. + // started with, nor the Artboard tool's selection from the start of the run. let chosen = h.session.borrow().active().and_then(|st| { h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; Some((st.uid, super::dom::active_artboard(st))) @@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { Some(chosen) => std::slice::from_ref(chosen), None => h.active_artboards.as_slice(), }; - let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid)); + let start = Start { active, picks, batch: s.artboard }; let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index ea399d2fd2..cdb3275607 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -458,6 +458,18 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // Once the script makes an artboard active, the selection from the start of the run no longer holds. + let (mut s, was, _) = setup(); + let before = objects(&s); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 1, "one copy, on the artboard the script made active"); + let pasted = s.active().unwrap().selection.objects.clone(); + let copy = s.active().unwrap().doc.bounds_of(&pasted, false).unwrap(); + assert!(copy.x0 >= was[1].x0 && copy.x1 <= was[1].x1, "the copy is on artboard 1: {copy:?}"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(2); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [was[0], was[1], art[2]], "only the artboard the script made active fits its art"); // A kept artboard past the last one is left out; with fewer than two left, the active one applies. let (mut s, ..) = setup(); s.reset_tool(); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..1ab9b11365 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3883,7 +3883,8 @@ through `$`: If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to - Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + Artwork Bounds step act on those instead, as in the panel's playback, until the script calls + `setActiveArtboardIndex` on that document; after a revert discards that choice, the selection applies again. A step of a recorded `command.batch` step that names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's own rules: the action and its set are matched by their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..d864b14102 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1135,7 +1135,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document, untargeted paste and Fit to Artwork Bounds use that artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. From 1337c0c5af7917655efa1153fbf6c0ec03f6e68d Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 3 Dec 2026 08:42:40 +0530 Subject: [PATCH 415/533] Canvas context menu: Artboard Options and artboard lock rows get their own icons The Artboard Options glyph was on artboard.setProps, which the canvas menu runs for the Lock Artboards and Unlock Artboards rows, while the Artboard Options row (tool.options for the Artboard tool) had none. Artboard Options now shows its glyph, and the lock rows show a closed or an open lock by their locked value. Part of #4602. --- crates/ui-egui/src/canvas/context_menu.rs | 44 ++++++++++++++++++++--- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 287a193132..a52c6d64c1 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -85,14 +85,26 @@ const ICONS: &[(&str, &str)] = &[ ("artboard.cut", "scissors"), ("artboard.delete", "trash-2"), ("artboard.rearrange", "dc-rearrange"), - ("artboard.setProps", "dc-artboard-options"), ("file.exportSelection", "share-2"), ("file.exportForScreens", "share-2"), ]; -/// The canvas menu's icon for `item`: its command's entry in [`ICONS`]. +/// The icons of rows whose command alone doesn't say what they do: Artboard Options (`tool.options` for the +/// Artboard tool) and the Lock Artboards and Unlock Artboards rows (`artboard.setProps` with `locked`). +const ARTBOARD_OPTIONS_ICON: &str = "dc-artboard-options"; +const LOCK_ICON: &str = "lock"; +const UNLOCK_ICON: &str = "lock-open"; + +/// The canvas menu's icon for `item`: Artboard Options' and the artboard lock rows' by their parameters, otherwise +/// its command's entry in [`ICONS`]. fn canvas_icon(item: &Item) -> Option { - ICONS.iter().find(|(id, _)| *id == item.command.id).map(|(_, icon)| IconId::new(icon)) + let params = &item.command.params; + let icon = match item.command.id.as_str() { + "tool.options" => (params["tool"] == "artboard").then_some(ARTBOARD_OPTIONS_ICON), + "artboard.setProps" => params["artboards"][0]["locked"].as_bool().map(|locked| if locked { LOCK_ICON } else { UNLOCK_ICON }), + id => ICONS.iter().find(|(command, _)| *command == id).map(|(_, icon)| *icon), + }; + icon.map(IconId::new) } /// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection. @@ -158,7 +170,11 @@ mod tests { use craft::behavior::IconId; use craft::ui::primitives::has_icon; - use super::ICONS; + use craft::menu::Node; + use serde_json::json; + + use super::{ARTBOARD_OPTIONS_ICON, ICONS, LOCK_ICON, UNLOCK_ICON, canvas_icon}; + use crate::menus::cp; /// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot /// empty, and a renamed command would quietly lose its icon. @@ -170,5 +186,25 @@ mod tests { let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id); assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command"); } + for icon in [ARTBOARD_OPTIONS_ICON, LOCK_ICON, UNLOCK_ICON] { + assert!(has_icon(&IconId::new(icon)), "{icon} isn't an icon"); + } + } + + /// Rows that share a command take their icon from their parameters: the Artboard Options glyph goes on + /// Artboard Options (`tool.options` for the Artboard tool), not on another tool's options, and the Lock + /// Artboards and Unlock Artboards rows (`artboard.setProps`) show a closed and an open lock. + #[test] + fn rows_that_share_a_command_take_their_icon_from_its_parameters() { + let icon = |node: Node| match node { + Node::Item(item) => canvas_icon(&item), + _ => None, + }; + let lock = |locked| cp("Lock All", "artboard.setProps", json!({ "artboards": [{ "index": 0, "locked": locked }] })); + assert_eq!(icon(cp("Artboard Options", "tool.options", json!({ "tool": "artboard" }))), Some(IconId::new(ARTBOARD_OPTIONS_ICON))); + assert_eq!(icon(cp("Options", "tool.options", json!({ "tool": "pen" }))), None); + assert_eq!(icon(lock(true)), Some(IconId::new(LOCK_ICON))); + assert_eq!(icon(lock(false)), Some(IconId::new(UNLOCK_ICON))); + assert_ne!(icon(lock(true)), icon(lock(false))); } } From e0632d6f7943a02f17647332e54e9ac355cbdae0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:27:08 -0800 Subject: [PATCH 416/533] Docs: scope where unknown halftone styles are rejected object.vectorHalftone, effect.apply and effect.setParams reject an unknown style. A stored effect with an unknown style draws as Custom. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ded26fb25d..df14112336 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1474,7 +1474,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. - - Vector Halftone styles are Custom (Shape and Angle as set), Grid (Euclidean dots at 0°), Grid Angle (Euclidean at 45°), Grid Dots (round dots at 0°) and Grid Dots Angle (round at 45°). Explicit `shape` and `angle` values override the style in `object.vectorHalftone`; named styles override stored values in the live effect. The dialog hides Shape and Angle for named styles, and unknown styles are rejected (`styles_set_the_shape_and_angle`, `halftone_styles_set_the_shape_and_angle_unless_given`, `halftone_effect_refuses_an_unknown_style`, `a_named_style_hides_shape_and_angle`). At partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage. At full tone every dot shape except Line is the cell's exact square (`full_tone_dots_have_exactly_the_cell_corners`). + - Vector Halftone styles are Custom (Shape and Angle as set), Grid (Euclidean dots at 0°), Grid Angle (Euclidean at 45°), Grid Dots (round dots at 0°) and Grid Dots Angle (round at 45°). Explicit `shape` and `angle` values override the style in `object.vectorHalftone`; named styles override stored values in the live effect. The dialog hides Shape and Angle for named styles. `object.vectorHalftone`, `effect.apply` and `effect.setParams` reject an unknown style, and a stored effect with an unknown style draws as Custom (`styles_set_the_shape_and_angle`, `halftone_styles_set_the_shape_and_angle_unless_given`, `halftone_effect_refuses_an_unknown_style`, `a_named_style_hides_shape_and_angle`). At partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage. At full tone every dot shape except Line is the cell's exact square (`full_tone_dots_have_exactly_the_cell_corners`). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. From 0b40292b5a6651cf92e7b9e6e0e56fc9d8c8cc06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 19:36:11 -0800 Subject: [PATCH 417/533] xtask: census rule reads loops and continues used as expressions The nested-loop scan now strips an initializer, a return or break operand, and grouping parentheses before the loop keyword, so a labeled continue inside `let _ = for _ in 0..0 { ... };` is known to never run, and a continue inside a grouped nested loop targets that loop. A continue after `=`, `(`, `,`, `return` or `break` now starts an expression, so `let _: () = continue;` before the call is seen as skipping it. Macro tokens and `r#continue` stay excluded. --- xtask/src/test_lint.rs | 88 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 4 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f70abd6da0..0e17e13a13 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1082,6 +1082,14 @@ fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { out } +/// Whether the `=` at `i` assigns (`=`, `+=`, `let x = …`), rather than being part of `==`, `!=`, +/// `<=`, `>=`, `=>` or `..=`. +fn is_assignment(b: &[u8], i: usize) -> bool { + b.get(i) == Some(&b'=') + && !i.checked_sub(1).and_then(|j| b.get(j)).is_some_and(|c| matches!(c, b'=' | b'!' | b'<' | b'>' | b'.')) + && !b.get(i + 1).is_some_and(|c| matches!(c, b'=' | b'>')) +} + /// The index of the bracket closing the one at `open`. fn matching(m: &[u8], open: usize) -> Option { let (o, c) = match m.get(open)? { @@ -2818,7 +2826,31 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ _ => {} } } - let lead = k - b[head_start..k].trim_ascii_start().len(); + let mut lead = k - b[head_start..k].trim_ascii_start().len(); + let loop_kw = + |head: &[u8]| [b"for".as_slice(), b"while", b"loop"].into_iter().find(|kw| words(head, kw, 0, head.len()).first() == Some(&0)); + // A loop used as an expression comes after an initializer or an operand (`let _ = for …`, + // `x = 'inner: loop …`, `return while …`). + if !b[lead..k].starts_with(b"'") && loop_kw(&b[lead..k]).is_none() { + let mut depth = 0i32; + let eq = (lead..k).find(|&i| { + match b[i] { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + depth == 0 && is_assignment(b, i) + }); + if let Some(eq) = eq { + lead = skip_ws(b, eq + 1); + } + // Grouping parentheses (`let _ = (for … { … });`) also open before the keyword. + for w in [b"(".as_slice(), b"return", b"break", b"("] { + while lead < k && b[lead..].starts_with(w) && (w == b"(" || words(b, w, lead, k).first() == Some(&lead)) { + lead = skip_ws(b, lead + w.len()); + } + } + } let head = b[lead..k].trim_ascii_end(); // A loop label (`'inner: for …`) comes before the keyword. let (inner, head) = match head.strip_prefix(b"'") { @@ -2829,7 +2861,7 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ } None => (None, head), }; - let kw = [b"for".as_slice(), b"while", b"loop"].into_iter().find(|kw| words(head, kw, 0, head.len()).first() == Some(&0))?; + let kw = loop_kw(head)?; Some((inner, kw == b"for" && literal_source_yields(head) == Some(false))) }) .collect() @@ -2847,8 +2879,15 @@ fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[ }) }; words(b, b"continue", open + 1, start).into_iter().any(|at| { - // The start of the loop body also starts an expression. - if !b[open + 1..at].trim_ascii_end().last().is_none_or(|&c| matches!(c, b'{' | b'}' | b';' | b'>')) || in_macro(at) { + // The start of the loop body also starts an expression, and so do an assignment, an opening + // parenthesis, a comma, and a `return` or `break` operand (`let _: () = continue;`). + let before = b[open + 1..at].trim_ascii_end(); + let starts_expr = before.last().is_none_or(|&c| matches!(c, b'{' | b'}' | b';' | b'>' | b'(' | b',')) + || before.len().checked_sub(1).is_some_and(|i| is_assignment(before, i)) + || [b"return".as_slice(), b"break"] + .iter() + .any(|w| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|i| is_ident(before[i]))); + if !starts_expr || in_macro(at) { return false; } let nested = nested_loops(at); @@ -10607,6 +10646,47 @@ mod tests { [(2, "census")], "a labeled continue in a nested loop that runs skips the call" ); + assert_eq!( + census("'outer: for _ in &[1] { let _ = for _ in 0..0 { continue 'outer; }; app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue in an initializer loop that never runs does not skip the call" + ); + assert_eq!( + census("'outer: for _ in &[1] { let _ = for _ in 0..1 { continue 'outer; }; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in an initializer loop that runs skips the call" + ); + } + + #[test] + fn census_counts_a_continue_used_as_an_expression() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("for _ in &[1] { let _: () = continue; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue as an initializer skips the call" + ); + assert_eq!( + census("for _ in &[1] { let _ = (continue); app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue in parentheses skips the call" + ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!(continue); let _v = r#continue == 1; app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a macro or a raw identifier still does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { let _ = (for _ in 0..1 { let _: () = continue; }); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue in a grouped nested loop targets that loop" + ); + assert_eq!( + census("for _ in &[1] { macro_rules! m { (continue) => {}; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a named macro definition's matcher does not skip the call" + ); } #[test] From 8714ec7731d6b700cc52a76a234038470831e4b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:10:56 -0800 Subject: [PATCH 418/533] Scripts: rasterize refuses sources clipped differently, capture checks file identity - object.rasterize with ids refuses objects whose nearest clip group or clipped layer differs, before rendering: the image goes where the last object is, so mixed sources would be clipped by another object's path. - Document.rasterize reads the image id from the command's result inside the run's savepoint, so an id above 2^53 binds the new RasterItem and a missing id undoes the edit. - Document.imageCapture refuses a destination that is another name of an open document's file or a linked file (same device and inode, or same volume and file index), and on Unix any file with other hard links, which an in-place write would change under every name. - Docs: gaps.md and target-app-parity.md list what rasterizing and capturing still lack; mcp.md states the clipping rule, the hard-link rule and that a later OS write failure can leave some files written. --- crates/engine/src/cmd/menucmds.rs | 17 +++- .../engine/src/script/dom/raster_capture.rs | 67 ++++++++++++---- .../engine/src/tests/script_raster_capture.rs | 78 +++++++++++++++++++ docs/gaps.md | 6 +- docs/mcp.md | 14 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 161 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 4eba8c7235..7af1bae33d 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -124,7 +124,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline), ids?: [object id…] (these objects instead of the selection, each directly in a layer or group and not a clipping path of a clip group or clipped layer, unlocked in unlocked layers and groups, containing no locked descendants, off locked artboards, and visible in visible layers and groups; an object inside another listed one is left out, as from a selection; the nearest clip group or clipped layer around each object must be the same one, or none for all; the selection stays as it is, less the objects rasterized), clipBounds?: [x0, y0, x1, y1] (points, y down: only the part of the art's area inside this rectangle; a rectangle that misses it is refused; dimensions within floating-point error of whole pixels use that pixel count, and other fractional dimensions round up)} replace the selection with an embedded image (PNG; grayscale makes a gray PNG, and bitmap a 1-bit TIFF or, where it has transparency, a black-and-white gray PNG with alpha; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; an image larger than 64 Mpx or 32,768 px a side is refused; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), imageId (the image), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), @@ -1019,6 +1019,21 @@ fn rasterize_sources(s: &Session, p: &Value, cmd: &str) -> Result> { } roots.push(*id); } + // The image goes where the last object is, so every object must share its clipping context: + // the nearest clip group or clipped layer around it, or none. + let clipper = |id: NodeId| d.ancestry(id).and_then(|up| up.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(Node::clips))); + if let Some(first) = roots.first() { + let context = clipper(*first); + if let Some(other) = roots.iter().find(|id| clipper(**id) != context) { + return Err(bad( + cmd, + format!( + "id {} is clipped differently from id {}: the nearest clip group or clipped layer around each object must be the same one, or none for all", + other.0, first.0 + ), + )); + } + } Ok(vectorcraft_doc::Selection { objects: roots, ..Default::default() }.in_paint_order(d)) } diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 1eb66216a1..3a2100a148 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -25,8 +25,10 @@ //! `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with //! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 //! to 255. The file is written only where the script's `File` objects may write, and never over -//! an open document's file or a file one of them links. -//! Source paths outside the automation read roots are excluded before filesystem probes. +//! an open document's file or a file one of them links, under any of its names (a hard link +//! included); on Unix it is never written over a file that has other hard links. Source paths +//! outside both the automation read and write roots are excluded before +//! filesystem probes. //! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is //! drawn; the resolution is never lowered to make it fit. //! - `windowCapture` throws an error that says it is not available yet. @@ -38,8 +40,8 @@ use vectorcraft_geom::Rect; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, coordinate, current, frame, given, item_of, item_ref, - later, method, named, num, on_doc, returns, text, this_doc, with_doc, + Answer, Described, Doc, Host, Link, MAX_LISTED, STALE_ITEM, arg, boolean, class, command, command_value, coordinate, current, frame, given, + item_of, item_ref, later, method, named, num, on_doc, returns, text, this_doc, with_doc, }; /// The lowest resolution the option classes take, in pixels per inch. @@ -222,16 +224,14 @@ fn doc_rasterize(h: &Host, a: &[Data]) -> Answer { if let Some(r) = clip { p.insert("clipBounds".into(), json!([r.x0, r.y0, r.x1, r.y1])); } - let r = on_doc(h, doc.uid, true, |h| command(h, "object.rasterize", &Value::Object(p)))?; + // The image's id is read from the command's own result inside the run's savepoint, so an id + // that a script number cannot hold exactly still names the image, and a missing one undoes the edit. + let (r, image) = on_doc(h, doc.uid, true, |h| { + let (r, value) = command_value(h, "object.rasterize", &Value::Object(p))?; + let image = value.get("imageId").and_then(Value::as_u64).ok_or_else(|| HostError::Error("the image was not made".into()))?; + Ok((r, image)) + })?; super::save_open::command_warnings(h, "rasterize", &r); - let image = match &r { - Data::Object(o) => o.iter().find_map(|(k, v)| match (k.as_str(), v) { - ("imageId", Data::Number(n)) => super::whole(*n), - _ => None, - }), - _ => None, - }; - let image = image.ok_or_else(|| HostError::Error("the image was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok(item_ref(h, st, crate::NodeId(image))) @@ -343,6 +343,42 @@ fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { false } +/// Whether two existing paths name one file on disk, such as two hard links to it: the same device +/// and file number on Unix, or the same volume and file index on Windows. `false` when either is +/// missing. +fn same_identity(a: &std::path::Path, b: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((std::fs::metadata(a), std::fs::metadata(b)), (Ok(x), Ok(y)) if (x.dev(), x.ino()) == (y.dev(), y.ino())) + } + #[cfg(windows)] + { + same_file::is_same_file(a, b).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (a, b); + false + } +} + +/// Whether the existing file at `p` has more than one name on Unix: writing into it in place, when +/// its folder refuses a replacement, would change the file under its other names too. Always +/// `false` off Unix, where [`same_identity`] compares the protected files instead. +fn has_other_links(p: &std::path::Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.nlink() > 1) + } + #[cfg(not(unix))] + { + let _ = p; + false + } +} + /// Whether `other`, a spelling of `entry` in other letter case, finds `entry` itself and not a /// symbolic link or another file. fn finds_same(entry: &std::path::Path, other: &std::path::Path) -> bool { @@ -418,9 +454,12 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; let target = placed(&real); - if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s))) { + if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); } + if has_other_links(&real) { + return Err(HostError::Error(format!("imageCapture cannot write over a file that has other hard links: {path}"))); + } let p = json!({ "path": crate::cmd::findfiles::plain(real).to_string_lossy(), "format": "png", diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 057c022dea..6f1c6357f5 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -201,6 +201,46 @@ fn script_rasterize_rejects_a_clipping_path() { s.execute("object.rasterize", &json!({"ids": [a.0]})).unwrap(); } +/// The new `RasterItem` is bound to the image's exact id, also for an id above 2^53, which a +/// script number does not hold exactly. +#[test] +fn script_rasterize_binds_an_image_id_above_two_to_the_53() { + let (mut s, a, _) = doc(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, &format!("{RASTERIZE_A} var r = d.rasterize(a); vc.log(r.typename); r.name = 'img';")); + assert_eq!(out, [json!("RasterItem")]); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_none(), "the source art is replaced"); + let mut named = Vec::new(); + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + named.push((n.id, n.name.clone())); + } + }); + assert_eq!(named.len(), 1, "{named:?}"); + assert!(named[0].0.0 > 1u64 << 53, "{named:?}"); + assert_eq!(named[0].1.as_deref(), Some("img"), "the item names the image itself"); +} + +/// The image takes the place of the last object, so objects in different clipping contexts are +/// refused before anything changes. +#[test] +fn script_rasterize_rejects_sources_clipped_differently() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 20.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let undo = undo_steps(&s); + let e = s.execute("object.rasterize", &json!({"ids": [c.0, a.0]})).unwrap_err().to_string(); + assert!(e.contains("is clipped differently"), "{e}"); + assert!(*before == *s.active().unwrap().doc, "a refused call leaves the document as it was"); + assert_eq!(undo_steps(&s), undo); + assert!(s.active().unwrap().doc.node(c).is_some(), "the unclipped object stays"); +} + #[test] fn script_rasterize_disposes_several_sources_in_one_step() { let (mut s, a, b) = doc(); @@ -627,6 +667,44 @@ fn capture_rejects_bad_options_and_names() { let _ = std::fs::remove_dir_all(base); } +/// A second hard link to an open document's file names the same file, so a capture to it is refused. +#[test] +fn capture_refuses_a_hard_link_to_an_open_document() { + let base = folder("hard-link"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + let alias = dir.join("alias.png"); + if std::fs::hard_link(&source, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&alias).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a capture never writes over a file with other hard links, which an in-place write would +/// change under every name. +#[cfg(unix)] +#[test] +fn capture_refuses_a_file_with_other_hard_links() { + let base = folder("other-links"); + let (mut s, dir) = capture_doc(&base); + let other = dir.join("other.bin"); + std::fs::write(&other, b"kept").unwrap(); + let alias = dir.join("alias.png"); + std::fs::hard_link(&other, &alias).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); + assert!(e.contains("other hard links"), "{e}"); + assert_eq!(std::fs::read(&other).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_denied_or_source_path_writes_nothing() { let base = folder("denied"); diff --git a/docs/gaps.md b/docs/gaps.md index 1ba18317d8..6054399bc1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -868,8 +868,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi document's `fullName`, `path` and `saved`, and close it with `Document.close`. Scripts also have each document's linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`), and trace them with `trace()`, which gives the Image Trace object as a `PluginItem` with its - `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for, rasterizing and capturing - images are still missing. + `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for are still missing. + `Document.rasterize` and `Document.imageCapture` are there; `RasterizeOptions.convertSpotColors`, + `convertTextToOutlines` and `includeLayers` set to true, and `Document.windowCapture`, still throw an error that + says they are not available yet. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and diff --git a/docs/mcp.md b/docs/mcp.md index bf6bdf5099..68e27ec1f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3924,7 +3924,8 @@ through `$`: writes a blank image of that area. `rasterize` takes one page item or a list of at most 10,000; an object of another document, one listed twice, one inside another listed one, a path of a compound path, and one that is locked or in a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an - error, and nothing changes. An object containing locked descendants also throws an error. + error, and nothing changes. An object containing locked descendants also throws an error, as do objects whose + nearest clip group or clipped layer is not the same one (or none for all). Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With @@ -3934,7 +3935,8 @@ through `$`: `transparency` the image keeps its transparency; otherwise it is drawn on `matteColor` with `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0 to 255. The file is checked as a `File` opened for writing is checked, and a path that is an open document's file or a file one of them links throws an - error, also when that file is missing. The linked files are every place opening the document looks for a link's + error, also when that file is missing or when the path is another hard link to it. On Unix a path to a file that + has other hard links also throws an error. The linked files are every place opening the document looks for a link's file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS image's plate files beside each. Paths rejected by the document's path restrictions, and paths outside both the automation read and write roots, are left out of the comparison. Open documents and linked files that only @@ -11942,7 +11944,8 @@ without the objects it replaced. An object inside another listed one is left out listed twice, a layer, a path of a compound path or a part of another object that is not a group, a clip group's clipping path (give the clip group's id instead), a clipped layer's clipping path, and an object that is locked or in a locked layer or group or on a locked artboard, and an object that is hidden or in a hidden layer or group, are -refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) +refused, and nothing changes. The nearest clip group or clipped layer around each object must be the same one, or +none for all of them; objects clipped differently are refused, and nothing changes. `clipBounds: [x0, y0, x1, y1]` (points, y down) keeps only the part of the art's area inside that rectangle; a rectangle that misses the art is refused. Dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional dimensions round up. The result's @@ -12772,8 +12775,9 @@ or in `options` (`file.formatOptions {format}` lists them with their values): - `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to `-.` beside the file: that artboard and the art touching it. The result's `files` lists every file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files. - The save checks every destination before writing. If any destination is a directory, an existing read-only file, or access is refused, - it leaves every file unwritten. The same check applies to EPS saves that write multiple files. + The save checks every destination before writing. If any destination is a directory, an existing read-only file, or + one the file-access policy refuses, it leaves every file unwritten. The same check applies to EPS saves that write + multiple files. A write that the operating system refuses later can still leave some of the files written. - `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a brush's art shows embedded keeps its pixels either way. A `version` older than the current one saves the placed diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 948c4d9ecb..f35feb211d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1118,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. + - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 80569dc577e6f8b7b1e83bc0db4591b4de0b0271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:24:21 -0800 Subject: [PATCH 419/533] Scripts: deleting a clipping path cannot make a tracing remove(), the document's pageItems.removeAll() and textFrames.removeAll() release the mask of a clip group whose clipping path they delete. A clip group named Image Trace with an image next above its clipping path then became an ordinary group named as a tracing with an image first, which reads as a tracing. They now throw "Only Image Trace can make a tracing" and delete nothing in that case. docs/mcp.md names the removeAll() collections that release a mask and the ones that refuse to delete a clipping path instead. --- crates/engine/src/script/dom.rs | 26 ++++++++++- crates/engine/src/script/dom/text.rs | 9 +++- crates/engine/src/tests/script_dom_tracing.rs | 45 +++++++++++++++++++ docs/mcp.md | 10 +++-- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a0bd117d11..8168075b9b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2337,7 +2337,7 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); @@ -2346,7 +2346,8 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { // A clipping layer emptied of its art releases its mask, so art added later is not made its // clipping path. let released = masks_cleared_by(&st.doc, &ids); - (ids, refused, on_locked, released) + let tracing = release_makes_tracing(&st.doc, &released, &ids); + (ids, refused, on_locked, released, tracing) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2356,6 +2357,9 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -2851,6 +2855,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error(NOT_A_TRACING.into())); } let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); + // A clip group named as a tracing, released with an image left first, would become one too. + if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. let params = json!({"ids": [item.id.0], "keepEmpty": true}); paths::see_all_points(h); @@ -2873,6 +2881,20 @@ pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { .collect() } +/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups +/// an ordinary group named as a tracing with an image first in it, which would make it a tracing. +pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool { + if released.is_empty() { + return false; + } + let removed: std::collections::HashSet = removed.iter().copied().collect(); + released.iter().filter_map(|g| d.node(*g)).any(|g| { + matches!(g.kind, NodeKind::Group { .. }) + && g.name.as_deref() == Some(crate::cmd::TRACE_NAME) + && g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }) +} + /// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { for g in released { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0555782952..1a86a1b50e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1480,7 +1480,7 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { /// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); @@ -1489,7 +1489,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { // Type that clips a group or layer releases its mask, so the object above it is not made // the clipping path. let released = super::masks_cleared_by(&st.doc, &ids); - Ok::<_, HostError>((ids, refused, on_locked, released)) + let tracing = super::release_makes_tracing(&st.doc, &released, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1499,6 +1500,10 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } + // A clip group named as a tracing, released with an image left first, would become one. + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..0f6851d342 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1197,6 +1197,51 @@ fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and +/// `textFrames.removeAll()` refuse it when an image would be left first in the released group. +#[test] +fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("release-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\ + vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\ + d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 8e2c1b01fb..c2b52798e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3242,9 +3242,13 @@ through `$`: is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` - and delete nothing. `remove()`, and any collection's `removeAll()`, that deletes the clipping path of a clip group - or clipping layer also releases that clipping mask in the same undo step, so the object above the clipping path - does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. Setting `width` or `height` scales the object along + and delete nothing. `remove()`, the document's `pageItems.removeAll()` and any `textFrames.removeAll()` that + delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step, + so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping + path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they + throw `Only Image Trace can make a tracing` and delete nothing. The `removeAll()` of a layer's or group's + `pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described + above. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, From 95e2aa4804b046004584869052e977a6c2d1cf8c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:26:38 -0800 Subject: [PATCH 420/533] Tests: PDF import limits and optional content membership Add tests that fail when these PDF import paths break: - Optional content membership dictionaries: AllOn, AnyOff, AllOff and the default AnyOn decide which marked art the page walk skips, with groups given as an array or a single reference. Each shown path keeps the spot ink the walk found it painted in. - Tiling patterns and soft masks nested more than 8 levels deep open with their "nested too deeply" warnings. - The ink-space scan stops 32 levels into an object and after 4,096 spaces. - A one-ink image of more than 2^26 pixels is refused before its samples are decoded. --- crates/pdf/src/tests/import_color.rs | 60 +++++++++++++++++++++++++ crates/pdf/src/tests/import_fidelity.rs | 46 +++++++++++++++++++ crates/pdf/src/tests/import_layers.rs | 47 +++++++++++++++++++ 3 files changed, 153 insertions(+) diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index 086b711aec..a7e83e56f3 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() { assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true)); assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false)); } + +/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint +/// transform [`GOLD_TINT`]). +fn gold_space(spaces: &str) -> Space { + use craft::pdf::interpret::Function; + use craft::pdf::syntax::object::{FromBytes, Object}; + let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap()); + let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap(); + Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None) +} + +const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + +/// The scan for ink spaces looks 32 levels into an object and no deeper. +#[test] +fn ink_spaces_nested_past_the_scan_depth_are_not_found() { + let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]"); + let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels)); + assert_eq!(gold_space(&nested(20)), Space::Inks(0)); + assert_eq!(gold_space(&nested(40)), Space::Other); +} + +/// The scan keeps 4,096 ink spaces: a space after that many others is not found. +#[test] +fn ink_spaces_past_the_scan_count_are_not_found() { + let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>"; + let spaces = |n: usize| -> String { + let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect(); + format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]") + }; + assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095)); + assert_eq!(gold_space(&spaces(4096)), Space::Other); +} + +/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are +/// decoded; the same samples read at a smaller size are not. +#[test] +fn one_ink_images_past_the_pixel_cap_are_refused() { + use std::io::Write; + let side = 8193u32; + let row = (side as usize).div_ceil(8); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![0u8; row * side as usize]).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect(); + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap(); + let st = file + .objects() + .into_iter() + .find_map(|o| match o { + craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s), + _ => None, + }) + .unwrap(); + assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS)); + assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32])); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 731f18ff06..b009f56d1f 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -370,6 +370,52 @@ fn tiling_patterns_become_pattern_swatches() { assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]); } +/// Links in the chains of nested patterns and soft masks below: more than are read. +const CHAIN: usize = 12; + +/// The warnings of opening a page drawing `content` with `resources`, plus `objects`. +fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec { + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + open_with(&one_page(content, resources, &extra), |_| {}).warnings +} + +/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a +/// chain of them opens, with a warning. +#[test] +fn patterns_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let cells: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = match i + 1 < CHAIN { + true => (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f"), + false => (String::new(), "1 0 0 rg 0 0 5 5 re f"), + }; + stream(&format!("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}"); +} + +/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain +/// of them opens, with a warning. +#[test] +fn soft_masks_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let mask =|i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let groups: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = match i + 1 < CHAIN { + true => (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f"), + false => (String::new(), "1 1 1 rg 0 0 100 100 re f"), + }; + stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >> /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}"); +} + // ---------- text ---------- const HELVETICA: &str = diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 33ada6d549..3badde2181 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's +/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with +/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default +/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over +/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden. +#[test] +fn membership_dictionaries_show_art_by_their_policy() { + let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]"); + let both = format!("[{a} 0 R {b} 0 R]"); + let runs = [ + ("AllOn", format!("{both} /P /AllOn")), + ("AnyOff", format!("{both} /P /AnyOff")), + ("AllOff", format!("{both} /P /AllOff")), + ("AnyOn", both.clone()), + ("OffAlone", format!("{b} 0 R /P /AllOff")), + ("OnAlone", format!("{a} 0 R /P /AllOff")), + ]; + let memberships: Vec = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect(); + let first = first_extra(1) + 2; + // Every ink has the same tint transform: only the walk tells the interpreter's paths apart. + let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + let mut content = String::new(); + let (mut props, mut spaces) = (String::new(), String::new()); + for (i, (ink, _)) in runs.iter().enumerate() { + content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i); + props += &format!("/M{i} {} 0 R ", first + i); + spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] "); + } + let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) }; + let mut extra: Vec<&str> = vec![&objs[0], &objs[1]]; + extra.extend(memberships.iter().map(String::as_str)); + let options = ImportOptions { layers: false, ..Default::default() }; + let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap(); + assert_eq!(names(&r.document), ["Page 1"]); + let inks: Vec> = r.document.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + }) + .collect(); + let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string())); + assert_eq!(inks, shown, "{:?}", r.warnings); +} From dfc42bb10b1c09a76f3435383842291a93e05d43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:29:24 -0800 Subject: [PATCH 421/533] Tests: checked saves keep the original, compressed files capped on both paths Checked saves (used under folder roots and for script commands) had no test for a fill that fails or is canceled, for the copy of the old file going to the system's temporary folder when the folder refuses it, or for the path that writes in the system's temporary folder when the folder refuses the temporary file. Five tests cover them: - a failed fill and a canceled fill return their error, leave the file as it was and remove the temporary file - a refused rename in a folder that then takes no new file keeps the old copy in the system's temporary folder and removes it afterwards - a folder that takes no temporary file saves through the system's temporary folder, and a failed fill there leaves nothing behind - a compressed file with data after its JSON is refused one byte past its JSON cap when streamed, and one byte past its whole-file cap when unpacked whole The permission tests skip when running as root. --- crates/format/src/atomic.rs | 150 ++++++++++++++++++++++++++++++++++++ crates/format/src/unpack.rs | 30 ++++++++ 2 files changed, 180 insertions(+) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..c28e6d8091 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1413,6 +1413,156 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A checked write whose fill fails puts nothing in place: the error is returned, the file + /// keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_the_original_when_its_fill_fails() { + let (d, root, _) = checked_folders("checked-fill-fails"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let r = write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + assert_eq!(r.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write canceled while it fills puts nothing in place: the error is the + /// cancellation, the file keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_canceled_while_it_fills_keeps_the_original() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + let (d, root, _) = checked_folders("checked-cancel"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }, + under(&root), + ) + }); + assert!(r.as_ref().is_err_and(|e| e.get_ref().is_some_and(|e| e.is::())), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// Makes `folder` refuse new files (mode 0o555). `false`, with the folder writable again, when + /// a new file can still be created there (root ignores the mode). + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn refuse_new_files(folder: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o555)).unwrap(); + let probe = folder.join("probe"); + if std::fs::write(&probe, b"").is_ok() { + let _ = std::fs::remove_file(&probe); + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + return false; + } + true + } + + /// Files in the system's temporary folder whose names start with the temporary names a write + /// to a file named `name` uses. + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn system_temp_files(name: &str) -> Vec { + let prefix = format!(".{name}.{}-", std::process::id()); + std::fs::read_dir(std::env::temp_dir()) + .unwrap() + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string())) + .filter(|n| n.starts_with(&prefix)) + .collect() + } + + /// A checked write over a file whose folder refuses the rename and then any new file: the copy + /// of the file as it was goes to the system's temporary folder, the new content is copied into + /// the file, and that copy is removed afterwards. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_keeps_the_old_copy_outside_a_folder_that_takes_no_new_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-old-elsewhere.txt"; + let (d, root, _) = checked_folders("checked-old-elsewhere"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + let refused = std::cell::Cell::new(true); + let r = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"new")?; + RENAME_REFUSED.with(|c| c.set(true)); + refused.set(refuse_new_files(&folder)); + Ok(()) + }, + under(&root), + ); + RENAME_REFUSED.with(|c| c.set(false)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !refused.get() { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + r.unwrap(); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(!leftovers(&folder, name).iter().any(|n| n.ends_with(".old")), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that refuses the temporary file of a checked write but lets the file itself be + /// written: the content is written in the system's temporary folder and copied in, and nothing + /// is left behind. A failed fill there leaves the file as it was. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_saves_through_the_system_folder_when_its_folder_takes_no_temporary_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-no-temp.txt"; + let (d, root, _) = checked_folders("checked-no-temp"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + if !refuse_new_files(&folder) { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + let saved = write_atomic_checked(&folder.join(name), |f| f.write_all(b"new"), under(&root)); + let saved_content = std::fs::read(folder.join(name)).unwrap(); + let saved_temp = system_temp_files(name); + let failed = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + saved.unwrap(); + assert_eq!(saved_content, b"new"); + assert!(saved_temp.is_empty(), "{saved_temp:?}"); + assert_eq!(failed.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(leftovers(&folder, name).is_empty(), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index ec9623118c..e636aadf74 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -374,6 +374,36 @@ mod tests { assert!(matches!(Unpacked::within(&gz, json.len() as u64 - 1), Err(FormatError::TooBig))); } + /// A compressed file with data after its JSON is refused past its budget on both paths: the + /// JSON before the marker where the writer puts it, and the whole file when the marker is + /// elsewhere and the file is unpacked whole. + #[test] + fn a_compressed_file_with_data_is_capped_on_both_paths() { + let with_data = |json: &[u8]| { + let mut file = json.to_vec(); + file.extend(crate::BLOB_MAGIC); + file.extend([1u8; 64]); + file + }; + let mut json = br#"{"pad":""#.to_vec(); + json.extend(std::iter::repeat_n(b'x', 4096)); + json.extend(br#""}"#); + let streamed = gzip(&with_data(&json)); + let max_json = json.len() as u64; + let opened = Unpacked::within(&streamed, max_json).unwrap(); + assert!(matches!(opened.tail, Tail::Stream { .. }), "read as a stream"); + assert_eq!(opened.json(), json.as_slice()); + assert!(matches!(Unpacked::within(&streamed, max_json - 1), Err(FormatError::TooBig))); + // No `}` before the marker: unpacked whole, within the whole-file cap and not one byte past it. + let plain = with_data(b"1"); + let whole = gzip(&plain); + let max_whole = plain.len() as u64; + let opened = Unpacked::within_capped(&whole, 64, max_whole, MAX_BLOBS).unwrap(); + assert!(matches!(opened.tail, Tail::Whole(_)), "unpacked whole"); + assert_eq!(opened.json(), b"1"); + assert!(matches!(Unpacked::within_capped(&whole, 64, max_whole - 1, MAX_BLOBS), Err(FormatError::TooBig))); + } + #[test] fn entries_sharing_bytes_obey_the_limits_in_memory_too() { // Each entry within MAX_BLOB, together past MAX_BLOBS: many references to the same bytes. From 0ded72192bc419e1c253d6d6a0ebeb4a522141a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:33:58 -0800 Subject: [PATCH 422/533] Tests: cover the .ai reading limits for text data, meshes and variable libraries - The text engine reader reads dictionaries and lists nested 65 levels deep and stops at a 66th, both balanced, so only the depth limit can end the parse. - A row of 256 mesh patches is stitched into one mesh, and a row of 257 is not. - A variable library whose variableSets node writes its attributes and children before its name is still read when reading stops before the library: one variable and one data set with its text value. --- crates/eps/src/import/ai/mesh.rs | 11 +++++++++ crates/eps/src/import/ai/tests.rs | 37 +++++++++++++++++++++++++++++++ crates/eps/src/import/ate.rs | 6 +++++ 3 files changed, 54 insertions(+) diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 8e2a46c852..1fcdc67266 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -785,6 +785,17 @@ mod tests { } } + /// A row of patches with as many columns as a mesh keeps is stitched into one mesh; one more + /// column is not. + #[test] + fn a_mesh_with_more_lines_than_are_kept_is_not_stitched() { + for (n, kept) in [(MAX_LINES, true), (MAX_LINES + 1, false)] { + let r = Grid::new(n, 1).read([n as f64, 1.0]); + let at: Vec<(usize, usize)> = (0..n).map(|i| (0, i)).collect(); + assert_eq!(stitch(&r.cells, &at, 1, n).is_some(), kept, "{n} columns"); + } + } + /// A 2 × 2 mesh comes in as one mesh of 9 shared points, each where the patches put it, with /// the colours the separate patches had at every place. #[test] diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index fe425346d2..57c7e21442 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2799,6 +2799,43 @@ fn ai_variable_library_without_the_layers() { assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default()); } +/// A library whose `variableSets` node writes its children and attributes before its name is +/// still found on its own when reading stops before it. +#[test] +fn a_variable_library_named_after_its_children_is_read_when_reading_stops_early() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_text}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let value = xml_element("Team", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode("Home Team"))])]); + let set = xml_element( + "variableSet", + &[("locked", "none"), ("varSetName", "binding1")], + &[ + xml_element("variables", &[], &[xml_element("variable", &[("trait", "textcontent"), ("varName", "Team")], &[])]), + xml_element( + "v:sampleDataSets", + &[("xmlns", "&ns_custom;"), ("xmlns:v", "&ns_vars;")], + &[xml_element("v:sampleDataSet", &[("dataSetName", "Home")], &[value])], + ), + ], + ); + let named_first = xml_element("variableSets", &[("xmlns", "&ns_vars;")], &[set]); + // Move the name line from the top of the node to just before the line that closes it. + let name = "%_(variableSets) /String (xmlnode-nodename) ,\n"; + let body = named_first.strip_prefix(&format!("%_/XMLNode :\n{name}")).and_then(|b| b.strip_suffix("%_;\n")).unwrap_or_default(); + assert!(!body.is_empty(), "{named_first}"); + let named_last = format!("%_/XMLNode :\n{body}{name}%_;\n"); + let early = stream(&format!("LB\n{}{square}", variable_library_data(&named_last))); + assert!(read(early.as_bytes()).is_err()); + let found = variables(early.as_bytes(), &mut Names::default()); + assert!(found.present); + let names: Vec<&str> = found.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["Team"]); + assert_eq!(found.variables.datasets.len(), 1); + assert_eq!(found.variables.datasets[0].name, "Home"); + assert_eq!(found.variables.datasets[0].values.get("Team"), Some(&DataValue::Text("Home Team".into()))); +} + #[test] fn a_drawn_look_stands_for_its_object() { // The look (a group, with a part on `%_` lines for newer readers), then the object on `%_` diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 3fb4393b19..43cb3b35d2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -2361,6 +2361,12 @@ mod tests { } let deep = format!("/0 {}", "[".repeat(200)); assert!(read(deep.as_bytes()).is_none()); + // Balanced nesting: 65 levels are read, and a 66th ends the parse. + let nest = |open: &str, close: &str, n: usize| format!("/0 {}1{}", open.repeat(n), close.repeat(n)); + for (open, close) in [("<< /0 ", " >>"), ("[ ", " ]")] { + assert!(read(nest(open, close, MAX_DEPTH + 1).as_bytes()).is_some(), "{open}nested {} levels", MAX_DEPTH + 1); + assert!(read(nest(open, close, MAX_DEPTH + 2).as_bytes()).is_none(), "{open}nested {} levels", MAX_DEPTH + 2); + } } /// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the From 6fc066f6b2f4f795ab9a8dec823a219a3cb4da4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:34:09 -0800 Subject: [PATCH 423/533] Tests: cover aligned and pattern strokes in EPS, live art in legacy .ai and top-object grids No test failed when these writer paths broke: - EPS export of an inside or outside stroke: the clip to the path (or, even-odd, to everything outside it) before the stroke drawn at twice its width. - EPS export of a pattern stroke, written as its outline filled with the tiles instead of as a stroke. - The legacy .ai writer's live-object arm: a distorted image on a layer is written as its pieces with the live-art warning. - The .ai writer's top-object grid: the points inside the grid blended from the four sides, checked on a 2 x 2 and a 3 x 2 outline so a swapped row and column weight fails too. Each test fails with the code it covers broken and passes with it restored. --- crates/eps/src/ai_editing/writer/envelopes.rs | 57 +++++++++++++++++++ crates/eps/src/legacy_ai/tests.rs | 15 +++++ crates/eps/src/tests.rs | 55 ++++++++++++++++++ 3 files changed, 127 insertions(+) diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 72966faf81..c3249ed756 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -497,3 +497,60 @@ impl Writer<'_> { s.push_str("/End X!\n"); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A closed outline through `points`, each side a straight segment. + fn outline(points: &[(f64, f64)]) -> PathData { + let mut bp = kurbo::BezPath::new(); + for (i, &(x, y)) in points.iter().enumerate() { + if i == 0 { + bp.move_to((x, y)); + } else { + bp.line_to((x, y)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) + } + + fn assert_near(got: Option, want: (f64, f64)) { + let Some(got) = got else { panic!("no grid point") }; + assert!(got.distance(Point::new(want.0, want.1)) < 1e-9, "{got:?} is not {want:?}"); + } + + /// A top object with two segments on each side is written as a 2 × 2 grid whose middle point + /// blends the four sides' middles less the four corners. + #[test] + fn a_top_object_with_two_segments_a_side_gets_its_middle_point_from_the_sides() { + let path = outline(&[(30.0, 10.0), (100.0, 0.0), (170.0, 10.0), (180.0, 50.0), (170.0, 90.0), (100.0, 90.0), (30.0, 90.0), (30.0, 50.0)]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 2, 4, 6])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 2)); + // (100, 0) and (100, 90) halved, (30, 50) and (180, 50) halved, less the corners' mean. + assert_near(pts.get(4).map(|q| q.0), (105.0, 45.0)); + } + + /// Three segments across and two down: each middle point is weighted by its column across and + /// its row down, not the other way around. + #[test] + fn a_top_object_wider_than_it_is_tall_blends_by_column_across_and_row_down() { + let path = outline(&[ + (0.0, 0.0), + (40.0, -6.0), + (80.0, 4.0), + (120.0, 0.0), + (126.0, 40.0), + (120.0, 80.0), + (80.0, 86.0), + (40.0, 84.0), + (0.0, 80.0), + (-4.0, 40.0), + ]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 3, 5, 8])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 3)); + assert_near(pts.get(5).map(|q| q.0), (39.0 + 1.0 / 3.0, 39.0)); + assert_near(pts.get(6).map(|q| q.0), (82.0 + 2.0 / 3.0, 45.0)); + } +} diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index e43f2a1227..7a0685d80a 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -722,6 +722,21 @@ fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_place assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image"); } +/// A distorted image on a layer, which the format has no form for, is written as the pieces it is +/// drawn as, with a warning. +#[test] +fn a_distorted_image_on_a_layer_is_written_as_its_pieces() { + let mut doc = Document::new(200.0, 100.0); + let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0)); + art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + doc.insert(doc.default_layer(), usize::MAX, art).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == LIVE), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes).unwrap(); + assert!(text.lines().filter(|l| l.ends_with(" XI")).count() > 1, "the pieces, not one image"); +} + /// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group /// holding an image and an image; a layer `Above` holding an orange square. Without `images`, /// `Below` is empty. diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index dc40025954..aa14fcde37 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -426,6 +426,61 @@ fn strokes_keep_their_caps_joins_and_dashes() { assert!(page.contains("0 0 0 rg\n20 20 m\n80 20 l\n80 80 l\n20 80 l\n20 20 l\nh\nS\n"), "{page}"); } +/// The page for a square stroked 4 pt with `paint`, aligned `align`. +fn aligned_stroke_page(align: vectorcraft_doc::StrokeAlign, paint: impl FnOnce(&mut Document) -> Paint) -> String { + let d = doc_with(|d| { + let paint = paint(d); + let mut n = path(d, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, paint, 4.0); + for i in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = i { + s.align = align; + } + } + vec![n] + }); + page_of(&d, &opts(&d)) +} + +/// Where the first line of `page` that `matches` is. +fn line_at(page: &str, matches: impl Fn(&str) -> bool) -> Option { + page.lines().position(matches) +} + +/// A stroke inside or outside a closed path is drawn at twice its width, clipped first: inside to +/// the path, outside to everything but the path (even-odd), so only its own half shows. +#[test] +fn inside_and_outside_strokes_are_clipped_to_their_side_and_drawn_twice_as_wide() { + use vectorcraft_doc::StrokeAlign; + let black = |_: &mut Document| Paint::solid(Color::BLACK); + for (align, clip) in [(StrokeAlign::Inside, "W"), (StrokeAlign::Outside, "W*")] { + let page = aligned_stroke_page(align, black); + let clip_at = line_at(&page, |l| l == clip); + let width_at = line_at(&page, |l| l.starts_with("8 w ")); + let stroke_at = line_at(&page, |l| l == "S"); + assert!(clip_at.is_some() && clip_at < width_at && width_at < stroke_at, "{align:?}: {page}"); + let other = if clip == "W" { "W*" } else { "W" }; + assert_eq!(line_at(&page, |l| l == other), None, "{align:?}: {page}"); + } + // Centered: the width as set, with no clip. + let page = aligned_stroke_page(StrokeAlign::Center, black); + assert!(line_at(&page, |l| l.starts_with("4 w ")).is_some(), "{page}"); + assert_eq!(line_at(&page, |l| l == "W" || l == "W*"), None, "{page}"); +} + +/// A stroke painted with a pattern is written as the area it covers, filled with the pattern's +/// tiles, not as a stroke. +#[test] +fn a_pattern_stroke_is_written_as_its_filled_outline() { + let pattern = |d: &mut Document| { + let square = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(square)])); + Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY } + }; + let page = aligned_stroke_page(vectorcraft_doc::StrokeAlign::Center, pattern); + assert!(page.contains("0 0 1 rg"), "the tile is painted: {page}"); + assert_eq!(line_at(&page, |l| l == "S" || l.contains("strokepath") || l.contains(" w ")), None, "{page}"); +} + #[test] fn transparency_is_written_opaque_with_a_warning() { let d = doc_with(|d| { From 99c9b51324e6247f6937610da9cb7d3701bb030e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:36:00 -0800 Subject: [PATCH 424/533] Tests: cover rounding, Randomize, spirals, 3D boxes and full-turn arcs in configured shapes Adds six unit tests to the shapes module for behavior no test checked: - A Rounded star or polygon with Randomize 0 still gets handles on every anchor. - Rounding handles are 0.4 x Rounded of the side long and at right angles to the radius. - A spiral starts at its center and ends a radius away at the angle its turns reach. - Randomize keeps polygon and star vertex radii within 45% of their radius per unit, and moves at least one. - Every face of a parallel 3D box is a parallelogram with four distinct corners, seen from five directions. - An end angle within 1e-9 degrees of a full turn opens the whole shape for Arc instead of cutting it. --- crates/geom/src/shapes.rs | 95 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 2d23c4c3bc..3a3cc606c5 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -1697,4 +1697,99 @@ mod tests { let b3d = box3d(r, 30.0, 35.0, 0.0, true, true, true); assert!(!b3d.subpaths.is_empty() && b3d.subpaths.iter().all(|s| s.closed && s.anchors.len() == 4)); } + + /// Rounded with no Randomize still builds the rounded contour, for stars and polygons alike. + #[test] + fn rounded_shapes_without_randomize_have_handles_on_every_anchor() { + let star = star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.5, 0.0); + assert_eq!(star.anchor_count(), 10); + assert!(star.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "star: {star:?}"); + let poly = polygon_configured(Point::ZERO, 50.0, 6, 0.0, 0.5, 0.0); + assert_eq!(poly.anchor_count(), 6); + assert!(poly.subpaths[0].anchors.iter().all(|a| a.has_in() && a.has_out()), "polygon: {poly:?}"); + } + + /// A rounded square's handles run along the unit tangent at each corner: 0.4 × Rounded of the + /// side long, at right angles to the radius. + #[test] + fn rounding_handles_are_their_share_of_the_side_along_the_tangent() { + let radius = 50.0; + let path = polygon_configured(Point::ZERO, radius, 4, 0.0, 1.0, 0.0); + let side = radius * 2.0_f64.sqrt(); + let want = 0.4 * side; + assert_eq!(path.anchor_count(), 4); + for a in &path.subpaths[0].anchors { + let (h_out, h_in, out_from_center) = (a.h_out - a.p, a.p - a.h_in, a.p.to_vec2()); + assert!((h_out.hypot() - want).abs() < 1e-9, "out handle {} long, want {want}", h_out.hypot()); + assert!((h_in.hypot() - want).abs() < 1e-9, "in handle {} long, want {want}", h_in.hypot()); + assert!(h_out.dot(out_from_center).abs() < 1e-9, "out handle {h_out:?} is not at right angles to {out_from_center:?}"); + assert!(h_in.dot(out_from_center).abs() < 1e-9, "in handle {h_in:?} is not at right angles to {out_from_center:?}"); + } + } + + /// A spiral starts at its center (inner radius 0) and ends a radius away, at the angle its turns + /// reach: an eighth past three whole turns, clockwise on screen, is down and to the right. + #[test] + fn a_spiral_runs_from_its_center_to_the_radius_at_its_last_angle() { + let (center, radius) = (Point::new(50.0, 60.0), 100.0); + let sp = spiral_configured(center, radius, 3.125, 1.0, 0.0, true); + let anchors = &sp.subpaths[0].anchors; + let (first, last) = (anchors[0].p, anchors[anchors.len() - 1].p); + assert!(first.distance(center) < 1e-9, "first anchor {first:?}, center {center:?}"); + let diagonal = radius / 2.0_f64.sqrt(); + let want = Point::new(center.x + diagonal, center.y + diagonal); + assert!(last.distance(want) < 1e-9, "last anchor {last:?}, want {want:?}"); + assert!((last.distance(center) - radius).abs() < 1e-9); + } + + /// Randomize moves each vertex out or in by at most 45% of its radius per unit of Randomize, + /// and does move some. + #[test] + fn randomize_keeps_vertex_radii_within_their_range() { + let distances = |p: &PathData| p.subpaths[0].anchors.iter().map(|a| a.p.distance(Point::ZERO)).collect::>(); + let within = |d: f64, base: f64| d >= base * 0.55 - 1e-9 && d <= base * 1.45 + 1e-9; + + let poly = distances(&polygon_configured(Point::ZERO, 50.0, 8, 0.0, 0.0, 1.0)); + assert_eq!(poly.len(), 8); + assert!(poly.iter().all(|&d| within(d, 50.0)), "polygon radii {poly:?}"); + assert!(poly.iter().any(|&d| (d - 50.0).abs() > 1e-6), "Randomize moved no vertex: {poly:?}"); + + let star = distances(&star_configured(Point::ZERO, 50.0, 25.0, 5, 0.0, 0.0, 1.0)); + assert_eq!(star.len(), 10); + let (tips, inner): (Vec<_>, Vec<_>) = star.iter().enumerate().partition(|(i, _)| i % 2 == 0); + assert!(tips.iter().all(|&(_, &d)| within(d, 50.0)), "star tips {tips:?}"); + assert!(inner.iter().all(|&(_, &d)| within(d, 25.0)), "star inner points {inner:?}"); + assert!(star.iter().zip([50.0, 25.0].iter().cycle()).any(|(d, base)| (d - base).abs() > 1e-6), "{star:?}"); + } + + /// Every face of a box drawn without perspective is a parallelogram with four distinct + /// corners, seen from each side of the box. + #[test] + fn a_parallel_box_draws_its_faces_as_parallelograms() { + let r = Rect::new(0.0, 0.0, 100.0, 80.0); + for (ax, ay) in [(30.0, 35.0), (-30.0, 35.0), (30.0, -35.0), (-30.0, -35.0), (150.0, 215.0)] { + let b = box3d(r, ax, ay, 0.0, true, true, true); + assert!(!b.subpaths.is_empty()); + for sp in &b.subpaths { + let p: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(p.len(), 4); + let gap = (p[0].to_vec2() + p[2].to_vec2() - p[1].to_vec2() - p[3].to_vec2()).hypot(); + assert!(gap < 1e-6, "angles ({ax}, {ay}): face {p:?} is not a parallelogram"); + for i in 0..4 { + for j in i + 1..4 { + assert!(p[i].distance(p[j]) > 1e-6, "angles ({ax}, {ay}): face {p:?} repeats a corner"); + } + } + } + } + } + + /// An end angle a hair short of a full turn opens the whole shape for Arc instead of cutting it. + #[test] + fn a_span_within_rounding_of_a_full_turn_opens_the_whole_shape() { + let r = Rect::new(0.0, 0.0, 100.0, 60.0); + let mut opened = ellipse(r); + opened.subpaths[0].closed = false; + assert_eq!(apply_shape_arc(ellipse(r), r.center(), 0.0, -1e-10, EllipseMode::Arc), opened); + } } From e47fad86bcbdcdfa98fb00ea2e4370e98a06d03a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:41:13 -0800 Subject: [PATCH 425/533] Tests: path joins, Pathfinder refusals and unknown selection modes Adds engine tests for code that no test reached: - path.join with the same id twice and subpaths: the coincident junction anchors merge, the later-first order puts the joined subpath in the right place, and one undo brings back all three subpaths. - Join from direct-selected ends: both ends of one open subpath close only that subpath, and with both ends of one line and one end of another selected, Join takes the nearest pair of selected ends. - Pathfinder refuses an image alone ("select paths") and an anchor that is not a finite number ("invalid coordinates"), with no undo step. - path.setHandle and object.blend.spine.moveAnchor refuse link with symmetric (one row in each existing refusal table). - select.segments, select.anchorsMany, select.magicWand and path.curvatureEdit refuse an unknown mode or op and leave the selection, the document and the undo history unchanged. --- crates/engine/src/tests.rs | 33 +++++++++ crates/engine/src/tests/anchor_edit_work.rs | 1 + crates/engine/src/tests/blendspine.rs | 1 + crates/engine/src/tests/draw2.rs | 74 +++++++++++++++++++++ crates/engine/src/tests/pathops.rs | 48 +++++++++++++ 5 files changed, 157 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6aa26f2edc..d574869a02 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5188,6 +5188,39 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// The selection commands and Curvature edits refuse a mode or op they do not know, and leave the +/// selection, the document and the undo history as they were. +#[test] +fn an_unknown_selection_mode_or_curvature_op_is_refused_without_changes() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 30.0, 20.0); + let b = rect(&mut s, 50.0, 10.0, 30.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let objects = s.doc().unwrap().selection.objects.clone(); + let anchors = s.doc().unwrap().selection.anchors.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let mut wrong = vec![]; + for (cmd, p, says) in [ + ("select.segments", json!({"id": a.0, "segments": [[0, 0]], "mode": "bogus"}), "unknown mode"), + ("select.anchorsMany", json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "bogus"}), "unknown mode"), + ("select.magicWand", json!({"id": a.0, "mode": "bogus"}), "unknown mode"), + ("path.curvatureEdit", json!({"id": a.0, "op": "bogus", "anchor": 0, "x": 0, "y": 0}), "unknown op"), + ] { + match s.execute(cmd, &p) { + Err(e) if e.to_string().contains(says) => {} + other => wrong.push(format!("{cmd}: {other:?}")), + } + let st = s.doc().unwrap(); + let changed = st.selection.objects != objects || st.selection.anchors != anchors || st.doc != doc || st.history.undo.len() != undo; + if changed { + wrong.push(format!("{cmd} changed the selection, the document or the undo history")); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + /// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With /// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that /// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 38bb94a6f3..c640c08e26 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -225,6 +225,7 @@ fn a_linked_handle_makes_the_anchor_smooth() { json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "symmetric": true}), json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}), diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 7f7c7fffa4..88a5c7b4b1 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -456,6 +456,7 @@ fn a_linked_spine_handle_makes_the_point_smooth() { for bad in [ json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}), json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}), + json!({"anchor": 1, "handle": "out", "x": 60, "y": 40, "link": true, "symmetric": true}), json!({"anchor": 1, "x": 75, "y": 25, "link": true}), ] { assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 516e4fb3b0..3be402bb94 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -6802,6 +6802,80 @@ fn join_two_subpaths_of_same_path_node() { assert_eq!(pd.subpaths[0].anchors[3].p, Point::new(250.0, 0.0)); } +/// A path with one open two-anchor subpath per pair of points. +fn path_of_lines(s: &mut Session, lines: &[[Point; 2]]) -> NodeId { + let p = line(s, lines[0][0].x, lines[0][0].y, lines[0][1].x, lines[0][1].y); + let rest: Vec<_> = lines[1..].iter().map(|l| vectorcraft_geom::SubPath::polyline(l, false)).collect(); + s.edit("Add Subpaths", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(p).unwrap().kind { + path.subpaths.extend(rest); + } + Ok(()) + }) + .unwrap(); + p +} + +fn subpath_points(s: &Session, id: NodeId) -> Vec> { + path(s, id).subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p).collect()).collect() +} + +/// `path.join` with the same id twice and `subpaths` joins two subpaths of one path. Here the later +/// subpath comes first, so the earlier one is removed and the joined subpath takes the later one's +/// place, the coincident junction anchors become one, and the subpath between them stays as it was. +/// One undo step brings back all three subpaths. +#[test] +fn join_of_one_path_by_ids_and_subpaths_merges_the_junction_and_keeps_the_other_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(100.0, 0.0), pt(110.0, 0.0)], [pt(500.0, 0.0), pt(510.0, 0.0)], [pt(0.0, 0.0), pt(100.0, 0.0)]]); + let before = subpath_points(&s, p); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("path.join", &json!({"ids": [p.0, p.0], "subpaths": [2, 0], "ends": ["last", "first"]})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(500.0, 0.0), pt(510.0, 0.0)], vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(110.0, 0.0)]]); + assert!(path(&s, p).subpaths.iter().all(|sp| !sp.closed)); + assert_eq!(s.doc().unwrap().selection.objects, vec![p]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(subpath_points(&s, p), before); +} + +/// With both ends of one open subpath direct-selected, Join closes that subpath and leaves the +/// other open subpath of the same path as it is, instead of joining the two. +#[test] +fn join_with_both_ends_of_one_subpath_selected_closes_that_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(0.0, 0.0), pt(100.0, 0.0)], [pt(0.0, 50.0), pt(100.0, 50.0)]]); + s.execute("select.anchors", &json!({"id": p.0, "anchors": [[1, 0], [1, 1]], "mode": "set"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(0.0, 0.0), pt(100.0, 0.0)], vec![pt(0.0, 50.0), pt(100.0, 50.0)]]); + let pd = path(&s, p); + assert!(!pd.subpaths[0].closed, "the other subpath stays open"); + assert!(pd.subpaths[1].closed, "the subpath with both ends selected is closed"); +} + +/// With both ends of one line selected and only the first end of another, Join takes the nearest +/// pair of selected ends: the second line's unselected end is nearer but is not joined. +#[test] +fn join_with_both_ends_of_one_line_selected_takes_the_nearest_selected_pair() { + let mut s = session(); + let pt = Point::new; + let a = line(&mut s, 0.0, 0.0, 100.0, 0.0); + let b = line(&mut s, 300.0, 0.0, 105.0, 0.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + let joined = paths(&s); + assert_eq!(joined.len(), 1, "{joined:?}"); + let pts: Vec = joined[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(300.0, 0.0), pt(105.0, 0.0)]); +} + /// Direct-selecting 2 open endpoints in a complex compound path with multiple open segments joins only those 2. #[test] fn join_complex_compound_path_direct_endpoints() { diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 802748e407..a5a082058e 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -123,6 +123,54 @@ fn intersect_disjoint_is_error_and_no_change() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Pathfinder refuses a selection that holds no paths (an image alone) and paths with an anchor +/// that is not a finite number, and leaves the document and the undo history as they were. +#[test] +fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { + let mut s = session(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![0; 8])); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 2, + height: 2, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 0.0, 10.0, 10.0); + s.edit("Break", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(a).unwrap().kind { + path.subpaths[0].anchors[1].p.x = f64::NAN; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("invalid coordinates"), "{e}"); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some()); + assert!(s.doc().unwrap().doc.node(image).is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); From 03c3d8264b273204b1c12405153f6fbef63915b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:41:13 -0800 Subject: [PATCH 426/533] Tests: format the nested pattern and soft mask chains --- crates/pdf/src/tests/import_fidelity.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index b009f56d1f..5697e70bb2 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -386,11 +386,13 @@ fn patterns_nested_too_deeply_stop_with_a_warning() { let first = first_extra(1); let cells: Vec = (0..CHAIN) .map(|i| { - let (resources, content) = match i + 1 < CHAIN { - true => (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f"), - false => (String::new(), "1 0 0 rg 0 0 5 5 re f"), + let (resources, content) = if i + 1 < CHAIN { + (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f") + } else { + (String::new(), "1 0 0 rg 0 0 5 5 re f") }; - stream(&format!("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {resources} >>"), content) + let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10"; + stream(&format!("{cell} /Resources << {resources} >>"), content) }) .collect(); let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); @@ -402,14 +404,13 @@ fn patterns_nested_too_deeply_stop_with_a_warning() { #[test] fn soft_masks_nested_too_deeply_stop_with_a_warning() { let first = first_extra(1); - let mask =|i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); let groups: Vec = (0..CHAIN) .map(|i| { - let (resources, content) = match i + 1 < CHAIN { - true => (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f"), - false => (String::new(), "1 1 1 rg 0 0 100 100 re f"), - }; - stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >> /Resources << {resources} >>"), content) + let (resources, content) = + if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") }; + let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>"; + stream(&format!("{group} /Resources << {resources} >>"), content) }) .collect(); let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); From 252e2ef3d4207621ffbaab557f24296c9ff07c9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:43:53 -0800 Subject: [PATCH 427/533] Recolor Artwork: a waiting picker answer, excluded rows and removed group swatches - The pump applies a Color Picker answer only while the row is the one the picker answered; a row that ui.dialog.set changed in between takes neither the color nor the swatch, and the status line says the rows changed. - An excluded row offers no Tint slider, since recolor.apply skips its art; the row keeps its tint. - A row picked from a group swatch that groupColors removes (null) offers no Tint slider; its chip keeps the tinted color, which the art takes unlinked. - docs/mcp.md and the recolor.apply params say a null swatch is no swatch. --- crates/engine/src/cmd/recolor.rs | 2 +- crates/ui-egui/src/dialogs/color_picker.rs | 4 +- crates/ui-egui/src/dialogs/recolor.rs | 122 ++++++++++++++++++++- docs/mcp.md | 2 +- 4 files changed, 122 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 73d53945eb..52877ae542 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; with limitTo the library's swatch of the row's new color comes first; a global swatch of `group` that is rewritten with another color links nothing, and the row's art keeps the row's new color; a `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo or swatch, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`), swatch?: {name, library?: swatch library id or name; \"document\" (default)} (the swatch the new color was picked from: of the swatches with the name, the first with the row's new color (as a color key); while it is a global or spot swatch and there is no globalAdjust (or limitTo is given), the row's art takes the swatch as with limitTo, linked to it at its tints; a process swatch, or a swatch or library that is not there, links nothing; with limitTo the library's swatch of the row's new color comes first; a global swatch of `group` that is rewritten with another color links nothing, and the row's art keeps the row's new color; a null `swatch` is no swatch, and any other `swatch` that is not {name, library?} is an error)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], swatchesNotFound?: [names of rows' `swatch` that are not there, which linked nothing], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 9209c854e0..f45fadf201 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -321,7 +321,7 @@ pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::Dial } /// Why a picker's OK answers nothing over Recolor Artwork. -fn rows_changed() -> String { +pub(super) fn rows_changed() -> String { tl!("The Recolor Artwork rows changed while the Color Picker was open").to_string() } @@ -436,6 +436,8 @@ fn finish( { super::recolor::answer_swatch(dialogs, *parent, key, swatch); } + // The pump applies the answer later; it drops it when the row changed in between. + super::recolor::answer_row(dialogs, *parent, open.row.clone()); if !super::save_for_web::take_palette_pick(app, *parent, key, open.start, r.picked.color) { dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 83d815c561..01860accb2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1529,9 +1529,12 @@ struct RowFeed { impl RowFeed { fn of(app: &VectorcraftApp, d: &Fields, links: &RowLinks, row: &Value) -> RowFeed { let to = to_color(row); - let spot = to.filter(|_| d.bool("__art")).and_then(|c| linked_spot(app, d, links, row, &c)); + // `recolor.apply` skips an excluded row, so its art links no spot swatch and Tint has nothing to set. + let spot = to.filter(|_| d.bool("__art") && !excluded(row)).and_then(|c| linked_spot(app, d, links, row, &c)); + // A swatch OK removes from the group links nothing afterwards, so the row offers no Tint. + let tint_swatch = spot.as_ref().filter(|w| !links.removed.contains(&w.name)).map(|w| w.name.clone()); let color = spot.as_ref().and_then(|w| w.paint.color()).or(to).unwrap_or_default(); - RowFeed { shown: new_shown(app, d, links, row), linked: linked(app, color), spot: spot.map(|w| w.name) } + RowFeed { shown: new_shown(app, d, links, row), linked: linked(app, color), spot: tint_swatch } } } @@ -1741,6 +1744,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if let Some(d) = host.get_mut_by_id::(id) && let Some((row, c)) = d.picked.take() { + // A row that changed between the picker's OK and this pass takes neither the colour nor the swatch. + if let Some(was) = d.picked_row.take() + && rows(&d.fields).get(row) != Some(&was) + { + d.picked_swatch = None; + app.status(super::color_picker::rows_changed()); + return; + } // A colour picked as RGB keeps the model of the row's new colour (CMYK in a CMYK document). let picked = Color::rgb(c.r, c.g, c.b); let was = rows(&d.fields).get(row).and_then(to_color); @@ -1863,6 +1874,16 @@ pub(super) fn answer_swatch(dialogs: &craft::ui::shell::WindowDialogs, parent: D }); } +/// The row as it was when the Color Picker's OK answered it, which the pump compares with the row +/// before it gives the row the answer. +pub(super) fn answer_row(dialogs: &craft::ui::shell::WindowDialogs, parent: DialogId, identity: Option) { + dialogs.with(|host| { + if let Some(d) = host.get_mut_by_id::(parent) { + d.picked_row = identity; + } + }); +} + /// Row `key` of Recolor Artwork `parent`, every field of it, or `None` when `parent` is not Recolor /// Artwork or has no such row. A Color Picker opened for the row answers it only while this is unchanged. pub(super) fn row_identity(dialogs: &craft::ui::shell::WindowDialogs, parent: DialogId, key: &str) -> Option { @@ -1971,6 +1992,9 @@ pub(crate) struct RecolorDialog { /// The row and the swatch the picker's colour was picked from ([`answer_swatch`]), until the pump /// gives the row that colour. picked_swatch: Option<(usize, Option<(Value, Color)>)>, + /// The answered row as it was when the picker answered ([`answer_row`]); the pump drops the + /// answer when the row has changed since. + picked_row: Option, /// The Color Theme Picker's canvas tool, which the canvas runs while the picker is on. theme_tool: edit_tab::ThemePickTool, } @@ -1990,6 +2014,7 @@ impl RecolorDialog { color_request: None, picked: None, picked_swatch: None, + picked_row: None, theme_tool: edit_tab::ThemePickTool::default(), } } @@ -2616,6 +2641,7 @@ fn new_shown(app: &VectorcraftApp, d: &Fields, links: &RowLinks, row: &Value) -> // `recolor.apply` skips an excluded row, so without a library its chip takes no Global Adjust. let effective = if excluded(row) && links.library.is_none() { to } else { links.effective_color(&to) }; if d.bool("__art") + && !excluded(row) && let Some(c) = linked_spot(app, d, links, row, &to).and_then(|w| w.paint.color()) { spot_tinted(app, c, row_tint(row)) @@ -2707,6 +2733,8 @@ struct RowLinks { library: Option<(vectorcraft_color::recolor::Palette, Vec)>, adjust: GlobalAdjust, rewritten: Vec, + /// The names of the color group's global swatches that OK's rewrite removes ([`removed_from_group`]). + removed: Vec, } impl RowLinks { @@ -2714,7 +2742,7 @@ impl RowLinks { let lib = d.str("limitTo"); let library = if lib.is_empty() { None } else { limit_palette_before_preview(app, &lib).zip(limit_swatches(app, &lib)) }; let rewritten = rewritten_to_another(app, d, library.as_ref().map(|(palette, _)| palette)); - Self { library, adjust: global_adjust(adjust_values(d)), rewritten } + Self { library, adjust: global_adjust(adjust_values(d)), rewritten, removed: removed_from_group(app, d) } } /// The color `recolor.apply` gives the art for new color `c`: `c` after the Global Adjust, @@ -2814,6 +2842,23 @@ fn rewritten_to_another(app: &VectorcraftApp, d: &Fields, palette: Option<&vecto .collect() } +/// The names of the color group's global swatches that OK's rewrite removes (a `null` in +/// `groupColors` of [`apply_params`]). `recolor.apply` gives art linked to one its color at its +/// tint and no link, so its row's chip keeps the tint and the row offers no Tint slider. +fn removed_from_group(app: &VectorcraftApp, d: &Fields) -> Vec { + let p = apply_params(d); + let (Some(group), Some(colors)) = (p["group"].as_str(), p["groupColors"].as_array()) else { return Vec::new() }; + let Some(doc) = doc_before_preview(app) else { return Vec::new() }; + let Some(g) = doc.swatch_groups.iter().find(|g| g.name == group) else { return Vec::new() }; + g.swatches + .iter() + .filter(|w| w.paint.color().is_some()) + .zip(colors) + .filter(|(w, v)| v.is_null() && w.global && !w.is_reserved()) + .map(|(w, _)| w.name.clone()) + .collect() +} + /// The name and library key of `row`'s `swatch` when it is `{name, library?}` with a name, as /// `recolor.apply` reads it. fn swatch_ref(row: &Value) -> Option<(&str, &str)> { @@ -4706,6 +4751,57 @@ mod tests { assert_eq!(row_shown(&rc.app(), &adjusted, 0).0, None, "no Tint under a Global Adjust"); } + /// A Color Picker answer that waits for the pump goes only to the row it answered: a row that + /// `ui.dialog.set` changed in between takes neither the color nor the swatch, and the status + /// line says why. An unchanged row takes both. + #[test] + fn a_waiting_picker_answer_skips_a_row_that_changed() { + let mut rc = gray_with_ink(json!([{"from": ["rgb 128 128 128"], "to": "rgb 128 128 128"}])); + let green = Srgba { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }; + let answer = |rc: &Recolor, was: Value| { + rc.with_dialog(|_, d| { + d.picked = Some((0, green)); + d.picked_swatch = Some((0, Some((json!({"name": "Ink", "library": "document"}), Color::cmyk(0.0, 1.0, 0.0, 0.0))))); + d.picked_row = Some(was); + }) + .unwrap(); + }; + let was = rc.rows()[0].clone(); + answer(&rc, was); + let changed = json!([{"from": ["rgb 128 128 128"], "to": "rgb 0 0 255"}]); + rc.with_dialog(|_, d| { + d.fields.fields.insert("rows".into(), changed.clone()); + }) + .unwrap(); + rc.frame(); + let r = rc.rows()[0].clone(); + assert_eq!(r["to"], changed[0]["to"], "the changed row keeps its color: {r}"); + assert!(r.get(SWATCH).is_none(), "and takes no swatch: {r}"); + assert!(rc.app().ui.status.contains("rows changed"), "{}", rc.app().ui.status); + let was = rc.rows()[0].clone(); + answer(&rc, was); + rc.frame(); + let r = rc.rows()[0].clone(); + assert_eq!(r[SWATCH], json!({"name": "Ink", "library": "document"}), "an unchanged row takes the answer: {r}"); + } + + /// An excluded row keeps its picked spot swatch and tint, but `recolor.apply` skips its art, so + /// the row offers no Tint slider. + #[test] + fn an_excluded_row_offers_no_tint() { + let rows = json!([{"from": ["rgb 128 128 128"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": "document"}, "tint": 40.0}]); + let mut rc = gray_with_ink(rows.clone()); + let fields = rc.fields(); + assert_eq!(row_shown(&rc.app(), &fields, 0).0.as_deref(), Some("Ink"), "Tint while the row recolors"); + let mut excluded = rows; + excluded[0]["exclude"] = json!(true); + rc.set("rows", excluded).unwrap(); + rc.settled(); + let fields = rc.fields(); + assert_eq!(row_shown(&rc.app(), &fields, 0).0, None, "no Tint for an excluded row"); + assert_eq!(rc.rows()[0]["tint"], json!(40.0), "the row keeps its tint"); + } + /// A swatch picked for a row under Limit to Library, whose color the library snaps to another /// one, is not kept: the row's new color is no longer the swatch's color. #[test] @@ -4805,10 +4901,10 @@ mod tests { #[test] fn the_effective_color_takes_the_global_adjust_without_a_library() { let red = Color::rgb(1.0, 0.0, 0.0); - let darker = RowLinks { library: None, adjust: global_adjust([0.0, -50.0, 0.0, 0.0]), rewritten: Vec::new() }; + let darker = RowLinks { library: None, adjust: global_adjust([0.0, -50.0, 0.0, 0.0]), rewritten: Vec::new(), removed: Vec::new() }; assert_eq!(darker.effective_color(&red), darker.adjust.apply(red)); assert_ne!(darker.effective_color(&red), red, "brightness -50 darkens the color"); - let plain = RowLinks { library: None, adjust: global_adjust([0.0; 4]), rewritten: Vec::new() }; + let plain = RowLinks { library: None, adjust: global_adjust([0.0; 4]), rewritten: Vec::new(), removed: Vec::new() }; assert_eq!(plain.effective_color(&red), red); } @@ -4856,6 +4952,22 @@ mod tests { rc.settled(); let fields = rc.fields(); assert_eq!(row_shown(&rc.app(), &fields, 1), (None, ink), "no Tint slider and the full color once Ink takes green"); + // A row with no new color removes Ink from the group (`null` in `groupColors`). + rc.set("rows", json!([{"from": ["cmyk 0 100 0 0"], "to": null}, rows("")[1].clone()])).unwrap(); + rc.settled(); + let fields = rc.fields(); + assert_eq!(apply_params(&fields)["groupColors"][0], Value::Null, "{}", apply_params(&fields)); + assert_eq!(row_shown(&rc.app(), &fields, 1), (None, shown), "no Tint slider, and the chip at 40% once Ink is removed"); + // OK gives the gray square that 40% tint of the ink, with no link. + let mut app = rc.app(); + let _ = app.session.cancel_interaction(); + app.session.execute(CMD, &apply_params(&fields)).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let nodes = doc.layers.iter().filter_map(|l| l.children()).flatten(); + let paints: Vec<_> = nodes.map(|n| doc.node(n.id).unwrap().appearance.fill_paint()).collect(); + let at_chip = |c: &Color| ColorKey::of(c) == ColorKey::of(&shown); + let unlinked = paints.iter().any(|p| matches!(p, vectorcraft_color::Paint::Solid { color, swatch: None, .. } if at_chip(color))); + assert!(unlinked, "the art takes the chip's color unlinked: {paints:?}"); } /// The new colors of the rows. diff --git a/docs/mcp.md b/docs/mcp.md index c80b69db1e..ce203a3080 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6837,7 +6837,7 @@ other recolored art does. A row whose new color is picked from a global or spot swatch in the Color Picker's swatch list in Recolor Artwork carries it when the dialog has art and no earlier solid swatch (other than a linked tint) in the same library has the same name and color, so with no Limit to Library the art still takes the swatch picked; the dialog drops a row's `swatch` when the row's new color changes. A -`swatch` that is not `{name, library?}` is an error. `recolor.randomize` +`swatch` of `null` is the same as no `swatch`; any other `swatch` that is not `{name, library?}` is an error. `recolor.randomize` moves a row's `tint` and `swatch` with its new color and removes them from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo step (art linked to its global swatches follows); a `null` in `colors` removes the group's swatch at that place, and given the group's own colors in order and no new name, it records no undo step. A color key (`recolor.colors`) that From 00cb293b9749c4055d4a27c4fe3c177a37525018 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:54:45 -0800 Subject: [PATCH 428/533] Tests: bent type on a path and the fallback file size limit - A rectangle bent along a circle keeps its corners at the ends of its step, its baseline edge on the circle and its other edge on the circle its height along the normal, with and without a rise off the path. A straight path and a glyph with no advance leave the outline as it is. - The file search for a character no loaded font covers loads a font that covers it, and skips the same font padded to 41 MiB. --- crates/text/src/fontdb.rs | 27 ++++++++++++ crates/text/src/layout/on_path.rs | 72 ++++++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f2a7e4835e..30b95066b5 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -190,6 +190,33 @@ mod alias_tests { assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); } + /// The file search for a character no loaded font covers skips font files over 40 MiB + /// without reading them, and loads the same font at its own length. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_skips_font_files_over_40_mib() { + use crate::{FileFontInfo, FileGlyph, build_file_font}; + use kurbo::Shape; + let pua = '\u{E123}'; + let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let font = build_file_font(&info, &[glyph]).unwrap(); + let search = |name: &str, bytes: &[u8]| { + let dir = std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + std::fs::write(dir.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let found = db.system_fallback(pua); + std::fs::remove_dir_all(&dir).unwrap(); + found + }; + assert!(search("small", &font), "a font at its own length is loaded"); + let mut padded = font.clone(); + padded.resize(41 << 20, 0); + assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 54e4125e88..2fd95fd6b2 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, #[cfg(test)] mod tests { - use super::longest_start_tried; + use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried}; + use vectorcraft_geom::{Rect, shapes}; + + /// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline. + fn block(w: f64, h: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((w, 0.0)); + p.line_to((w, h)); + p.line_to((0.0, h)); + p.close_path(); + p + } + + fn end_points(path: &BezPath) -> Vec { + path.elements() + .iter() + .filter_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), + PathEl::ClosePath => None, + }) + .collect() + } + + /// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge + /// follows a circle `h` farther along the path's normal; its corners stay at the ends of its + /// step along the path. Moving it off the path (`rise`) moves both edges by the same amount. + #[test] + fn an_outline_bent_along_a_circle_follows_it() { + let (center, r) = (Point::new(100.0, 100.0), 100.0); + let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + let (w, h, s) = (40.0, 20.0, 30.0); + let (p0, d0) = ap.at(s); + let (p1, _) = ap.at(s + w); + // Which way the path's normal points: away from the center (+1) or towards it (-1). + let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum(); + let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r); + for rise in [0.0, 5.0] { + let bend = GlyphBend { s, step: w, advance: w, rise }; + let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline"); + let points = end_points(&bent); + let (base, top) = (r + side * rise, r + side * (rise + h)); + let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)]; + for c in corners { + assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}"); + } + // The edges are cut into pieces that stay between the two circles; a straight chord + // between the corners would pass inside the inner one. + assert!(points.len() > 8, "rise {rise}: {} points", points.len()); + let (inner, outer) = (base.min(top), base.max(top)); + for p in &points { + let d = p.distance(center); + assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}"); + } + let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count(); + assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle"); + } + } + + /// A path that does not turn under the glyph, and a glyph with no advance, leave the outline + /// as it is. + #[test] + fn an_outline_on_a_straight_path_is_not_bent() { + let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0))); + let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none()); + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some()); + let no_advance = GlyphBend { advance: 0.0, ..bend }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none()); + } /// The longest start that fits is found among the ones tried; past the tries, a binary search /// finds one that fits, with as many more tries as halvings of the rest. From d29d2d03dae6504ba283952f5e5f3b759b534e82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:00:46 -0800 Subject: [PATCH 429/533] Tests: harmony labels and DXF miles and kilometers - rules_parse_by_id_and_label reads a few shown labels back through parse(label(h)). The labels are written in vectorcraft-color and the ids come from craft-libs, so a label that drifts from its id no longer parses. - units_choose_the_default_scale covers $INSUNITS 3 (miles) and 7 (kilometers), which have no unit of their own and read as millimeters at their scale. --- crates/cad/src/import/tests.rs | 6 ++++++ crates/color/src/harmony.rs | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index ae5b2d5804..5faad39835 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -140,6 +140,12 @@ fn units_choose_the_default_scale() { assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); } + // Miles and kilometers have no unit of their own, so they read as millimeters at their scale. + for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] { + let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap(); + assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); + assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); + } let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document; assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect); let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap(); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 75a5fdc2a5..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -197,6 +197,11 @@ mod tests { assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); + // The labels are written here and the ids come from the framework: a few shown labels read + // back as their rules. + for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] { + assert_eq!(parse(label(h)), Some(h), "{}", label(h)); + } } #[test] From cd172d1e7728f0fc48fb4e18a81ff4a0c22dddad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:08:00 -0800 Subject: [PATCH 430/533] Tests: cover import limits, .af blend fallback and action.batch destinations - PSD slices: a version 7 or 8 descriptor that lists more than 10,000 slices, objects nested 17 deep and lists nested 17 deep are refused with a warning, and 16 levels of either still open. - .pcraft: a 12000 x 12000 canvas leaves the preview with the "too large to combine" note before any layer is read. - .af files: Multiply keeps its blend mode, and Linear Light imports as Normal with one warning however many objects use it. - action.batch: an unknown destination is refused, and destination "folder" without destinationFolder is refused before any file opens. --- crates/engine/src/cmd/fileio/action_batch.rs | 12 ++++++++ .../engine/src/cmd/fileio/affinity/nodes.rs | 29 +++++++++++++++++++ .../engine/src/cmd/fileio/tests_pcraftread.rs | 8 +++++ .../engine/src/cmd/fileio/tests_psdslices.rs | 20 +++++++++++++ 4 files changed, 69 insertions(+) diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index aa3be78e2a..9beed7e8a2 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -872,6 +872,7 @@ mod tests { ("source", json!(1), "`source` must be a string"), ("source", json!("files"), "`source` must be `folder` or `datasets`"), ("destination", json!(true), "`destination` must be a string"), + ("destination", json!("nowhere"), "`destination` must be `none`, `saveAndClose` or `folder`"), ("folder", json!(5), "`folder` must be a string"), ("label", json!(5), "`label` must be a string"), ("datasetFileNaming", json!(3), "`datasetFileNaming` must be a string"), @@ -895,6 +896,17 @@ mod tests { .to_string(); assert!(e.contains("`destinationFolder` must be a string"), "{e}"); assert!(s.active().is_none(), "no file was opened"); + // Saving to a folder needs the folder. + let e = s + .execute( + "action.batch", + &json!({"folder": src.to_string_lossy(), "destination": "folder", "commands": [{"command": "object.unlockAll"}]}), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("`destinationFolder` is required when destination is `folder`"), "{e}"); + assert!(s.active().is_none(), "no file was opened"); + assert_eq!(std::fs::read_dir(&src).unwrap().count(), 1, "nothing was written next to the source file"); } #[cfg(unix)] diff --git a/crates/engine/src/cmd/fileio/affinity/nodes.rs b/crates/engine/src/cmd/fileio/affinity/nodes.rs index 36734dbe39..a6961c28c2 100644 --- a/crates/engine/src/cmd/fileio/affinity/nodes.rs +++ b/crates/engine/src/cmd/fileio/affinity/nodes.rs @@ -288,4 +288,33 @@ mod tests { assert!(!path_in_range(&path(&[(0.0, 0.0), (f64::NAN, 0.0)]), k)); assert!(!path_in_range(&path(&[(0.0, 0.0), (1.0, 1.0)]), Affine::scale(1.0e9))); } + + fn blended(blend: Blend) -> af::Node { + af::Node { + class: vectorcraft_affinity::stream::Tag::of(b"GrpN"), + name: String::new(), + visible: true, + locked: false, + opacity: 1.0, + blend, + kind: Kind::Group, + mask: None, + pixel_mask: None, + effects: vec![], + children: vec![], + } + } + + /// A blend mode VectorCraft has keeps it; one it lacks imports as Normal with one warning. + #[test] + fn blend_modes_map_or_import_as_normal_with_a_warning() { + let group = || NodeKind::Group { children: vec![], clip: false }; + let mut b = Builder::new(1.0); + assert_eq!(b.base(&blended(Blend::Multiply), group()).blend, BlendMode::Multiply); + assert!(b.warnings.is_empty(), "{:?}", b.warnings); + for _ in 0..2 { + assert_eq!(b.base(&blended(Blend::LinearLight), group()).blend, BlendMode::Normal); + } + assert!(b.warnings.len() == 1 && b.warnings[0].contains("Linear Light"), "{:?}", b.warnings); + } } diff --git a/crates/engine/src/cmd/fileio/tests_pcraftread.rs b/crates/engine/src/cmd/fileio/tests_pcraftread.rs index 444ba06606..ba46f8040b 100644 --- a/crates/engine/src/cmd/fileio/tests_pcraftread.rs +++ b/crates/engine/src/cmd/fileio/tests_pcraftread.rs @@ -215,6 +215,14 @@ fn layers_that_cant_be_combined_leave_the_preview_with_a_note() { assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains(said), "{said}: {w:?}"); } + // A canvas whose combined pixels would take more memory than one image may use leaves the + // preview, saying so before any layer is read. + let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); + b.size = (12_000, 12_000); + let (r, _, pixels) = place(&b.bytes()); + let w = warnings(&r); + assert!(pixels.width() == 30 && w.len() == 1 && w[0].contains("too large to combine"), "{w:?}"); + // A preview of the canvas's own size is not reduced, so nothing is said. let mut b = Bundle::new(vec![layer(true, "Multiply", 1.0, &raster(&rgba8([0; 4])), "")]); b.size = (30, 20); diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index ded0f137b3..fce524598e 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -374,6 +374,11 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // The count follows the version, the bounds and the group's name. ([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"), (v7(8, vec![D::Long(3)]), "other than a slice"), + // A descriptor's list of more slices than are read, refused before any is looked at. + (v7(7, (0..10_001).map(|_| D::Long(0)).collect()), "more than the 10000 read"), + // Objects, and lists, nested one level deeper than are read. + (deep(17, |d| D::Obj(vec![("in", d)])), "nests too deep"), + (deep(17, |d| D::List(vec![d])), "nests too deep"), // A whole record whose name is longer than a slice's text may be. (v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"), ]; @@ -395,6 +400,21 @@ fn slices_that_cant_be_read_warn_and_the_file_still_opens() { // A file without slices opens without a word about them. let (s, r) = open(&psd(true), json!({})); assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}"); + // Objects and lists nested as deep as are read come in. + for data in [deep(16, |d| D::Obj(vec![("in", d)])), deep(16, |d| D::List(vec![d]))] { + let (_, r) = open(&with_resource(&psd(false), 1050, &data), json!({})); + assert!(warnings(&r).is_empty(), "{r}"); + } +} + +/// Resource 1050 in version 7 with no slices, whose descriptor also holds `levels` values nested +/// one in another by `wrap`, around a long. +fn deep(levels: usize, wrap: fn(D) -> D) -> Vec { + let nested = (0..levels).fold(D::Long(0), |d, _| wrap(d)); + let mut b = 7u32.to_be_bytes().to_vec(); + b.extend(16u32.to_be_bytes()); + b.extend(descriptor(&[("deep", nested), ("slices", D::List(vec![]))])); + b } #[test] From 44405e3e4eb8c619f014d45bd3872ccf9bf9a558 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:09:09 -0800 Subject: [PATCH 431/533] Tests: cover geom arc, straightness, quad length and anchor table checks Adds tests that fail when these checks break: - circular_arc returns None for a 60 degree cubic whose ends are at radii 100 and 105 from where their normals cross. - The near-straight limit in osculating grows with the segment's speed: a 300 pt segment that bends by 1e-9 pt is straight, and one that bends by 1e-3 pt is curved. - has_length is false for a quadratic whose three points coincide and true when its middle point lies off its ends. - Anchors::table_bytes counts both the chunk table and the running totals, for a short list and for a list split unevenly by an insert. Removes the unused From<&[Anchor]> impl for Anchors. Nothing in the workspace converts a slice to Anchors. --- crates/geom/src/anchors.rs | 25 +++++++++++++++++++------ crates/geom/src/bez.rs | 11 +++++++++++ crates/geom/src/curvature.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 3b9f4aa9bd..78cfe5509a 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -554,12 +554,6 @@ impl From> for Anchors { } } -impl From<&[Anchor]> for Anchors { - fn from(s: &[Anchor]) -> Self { - Self::from(s.to_vec()) - } -} - impl From<[Anchor; N]> for Anchors { fn from(s: [Anchor; N]) -> Self { Self::from(Vec::from(s)) @@ -892,4 +886,23 @@ mod tests { moved.remove(0); assert_eq!(before.pairs_not_shared(&moved).count(), 10_000); } + + /// The table bytes take in both tables: at least what the chunk table and the running totals + /// hold, and at most what they have reserved. A short list has no running totals; a list split + /// unevenly by an insert has both. + #[test] + fn table_bytes_count_the_chunk_table_and_the_running_totals() { + let (chunk, total) = (size_of::>>(), size_of::()); + let within = |a: &Anchors| { + let held = a.chunks.len() * chunk + a.ends.len() * total; + let reserved = a.chunks.capacity() * chunk + a.ends.capacity() * total; + (held..=reserved).contains(&a.table_bytes()) + }; + let short = Anchors::from(line(5)); + assert!(short.ends.is_empty() && within(&short), "{}", short.table_bytes()); + let mut uneven = Anchors::from(line(CHUNK)); + uneven.insert(10, Anchor::corner(Point::ZERO)); + assert!(uneven.chunks.len() == 2 && uneven.ends.len() == 2, "{:?}", uneven.ends); + assert!(within(&uneven), "{}", uneven.table_bytes()); + } } diff --git a/crates/geom/src/bez.rs b/crates/geom/src/bez.rs index 8f6b3c4a0a..6565c7d68e 100644 --- a/crates/geom/src/bez.rs +++ b/crates/geom/src/bez.rs @@ -106,4 +106,15 @@ mod tests { assert_eq!(tangent(&c[0], 1.0), Vec2::new(0.0, 1.0)); assert_eq!(unit(Vec2::ZERO), Vec2::new(1.0, 0.0)); } + + /// A quadratic whose three points coincide has no length; one whose middle point lies off its + /// coinciding ends has length. + #[test] + fn a_quad_has_length_unless_its_points_coincide() { + use kurbo::{Point, QuadBez}; + let (p, q) = (Point::new(3.0, 4.0), Point::new(9.0, -2.0)); + assert!(!has_length(&PathSeg::Quad(QuadBez::new(p, p, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, q, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, p, q)))); + } } diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index aea7afde1d..0a56d6101c 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -316,6 +316,33 @@ mod tests { assert!(curvature_circle(s, 0.25, false).is_ok()); } + /// A segment that bends by a billionth of a point over 300 points is straight: the limit grows + /// with the segment's speed, so a fast segment needs a larger bend to count as curved. A bend + /// a million times larger is curved. + #[test] + fn a_fast_segment_that_barely_bends_is_straight() { + let nearly = |dy: f64| CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, dy), Point::new(200.0, 0.0), Point::new(300.0, 0.0)); + assert_eq!(curvature_circle_with(nearly(1e-9), 0.5, false, false), Err(NoCircle::Straight)); + assert_eq!(osculating(nearly(1e-9), 0.5), Err(NoCircle::Straight)); + assert!(curvature_circle_with(nearly(1e-3), 0.5, false, false).is_ok()); + } + + /// The ends of a 60° cubic at radii 100 and 105 from where their normals cross are not the + /// cubic of a circular arc, even with handles of the right length for the mean radius; the + /// same cubic with both ends at radius 100 is one. + #[test] + fn ends_at_different_radii_are_not_a_circular_arc() { + let turn = 60f64.to_radians(); + let arc = |r3: f64, mean: f64| { + let handle = 4.0 / 3.0 * (turn / 4.0).tan() * mean; + let (p0, p3) = (Point::new(100.0, 0.0), Point::new(r3 * turn.cos(), r3 * turn.sin())); + CubicBez::new(p0, p0 + Vec2::new(0.0, handle), p3 - Vec2::new(-turn.sin(), turn.cos()) * handle, p3) + }; + assert_eq!(circular_arc(arc(105.0, 102.5)), None); + let (center, radius) = circular_arc(arc(100.0, 100.0)).unwrap(); + assert!(center.distance(Point::ORIGIN) < 1e-9 && (radius - 100.0).abs() < 1e-9, "{center:?} {radius}"); + } + /// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points /// that are not finite and a `t` outside 0 to 1 have no curvature circle. #[test] From 7a066e53b8857cbf00d0545f378e67ca044b947f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:14:29 -0800 Subject: [PATCH 432/533] Tests: cover the limits and package errors of placing Word documents Placing a .docx or .doc file had guards that no test reached, so removing or loosening any of them left every test passing: - malformed_docx_fails_cleanly now checks the messages for a package with no end record, an encrypted part, an unknown compression method and ZIP64 end-record values, and that 100,002 empty paragraphs fail with "too much text or formatting". - docx_parts_in_utf16_with_a_byte_order_mark_place_their_text places a main part in UTF-16LE and UTF-16BE after a byte-order mark. - docx_based_on_chains_stop_at_a_cycle_and_after_32_styles places a paragraph in a style whose basedOn chain loops, and chains of 32 and 33 styles where only the last style sets a size. - docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out nests runs in smart tags and table rows in content controls 70 and 60 levels deep. - malformed_doc_fails_cleanly refuses a .doc WordDocument stream whose directory entry gives 64 MB plus one byte. Each new check fails with the guard it covers broken. --- crates/engine/src/tests/textimport.rs | 88 +++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index 891e7a6ba0..7af09c95e8 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -489,6 +489,9 @@ fn malformed_docx_fails_cleanly() { let store = |files: &[(&str, &[u8])]| cmd::fileio::zip::store(files).unwrap(); let document = |body: &str| format!(r#"{body}"#); assert!(place(&mut s, "a.docx", b"Plain words, not a package").is_err(), "a .docx file that isn't a ZIP archive"); + // A .docx file that starts with a local file header and has no end record. + let e = place(&mut s, "a.docx", b"PK\x03\x04 and nothing after the first header").unwrap_err(); + assert!(e.contains("isn't a ZIP package"), "{e}"); let e = place(&mut s, "a.docx", &store(&[("readme.txt", b"x")])).unwrap_err(); assert!(e.contains("no main document part"), "{e}"); let e = place(&mut s, "a.zip", &store(&[("readme.txt", b"x")])).unwrap_err(); @@ -531,6 +534,29 @@ fn malformed_docx_fails_cleanly() { longer[central + 20..central + 24].copy_from_slice(&packed.to_le_bytes()); let e = place(&mut s, "a.docx", &longer).unwrap_err(); assert!(e.contains("damaged"), "{e}"); + // A file whose directory record sets the encryption flag (bit 0) or names a compression method other than stored + // or deflated, and an end record with the values that mean a ZIP64 record holds the real ones. + let words = || store(&[("word/document.xml", document("words").as_bytes())]); + let record = |zip: &[u8]| zip.windows(4).position(|w| w == 0x0201_4b50u32.to_le_bytes()).unwrap(); + let mut encrypted = words(); + let at = record(&encrypted); + encrypted[at + 8] |= 1; + let e = place(&mut s, "a.docx", &encrypted).unwrap_err(); + assert!(e.contains("`word/document.xml` in the Word document is encrypted"), "{e}"); + let mut method = words(); + let at = record(&method); + method[at + 10..at + 12].copy_from_slice(&99u16.to_le_bytes()); + let e = place(&mut s, "a.docx", &method).unwrap_err(); + assert!(e.contains("uses compression method 99"), "{e}"); + let mut zip64 = words(); + let end = zip64.len() - 22; + zip64[end + 10..end + 12].copy_from_slice(&0xFFFFu16.to_le_bytes()); + let e = place(&mut s, "a.docx", &zip64).unwrap_err(); + assert!(e.contains("uses ZIP64 records"), "{e}"); + // One paragraph more than placed type takes: a paragraph is written when the next one starts, so 100,002 + // paragraphs write 100,001. + let e = place(&mut s, "a.docx", &store(&[("word/document.xml", document(&"".repeat(100_002)).as_bytes())])).unwrap_err(); + assert!(e.contains("too much text or formatting"), "{e}"); // Containers nested past the depth read are skipped, and a part nested deeper still is refused. let nested = |n: usize| { let deep = format!("{}deep{}", "".repeat(n), "".repeat(n)); @@ -549,6 +575,60 @@ fn malformed_docx_fails_cleanly() { assert_eq!(s.doc().unwrap().history.undo.len(), 2, "failed places leave no undo step"); } +#[test] +fn docx_parts_in_utf16_with_a_byte_order_mark_place_their_text() { + let mut s = session(); + let xml = format!(r#"Grüße 東京"#); + for (bom, le) in [([0xFF, 0xFE], true), ([0xFE, 0xFF], false)] { + let part = [&bom[..], &utf16(&xml, le)].concat(); + let zip = cmd::fileio::zip::store(&[("word/document.xml", &part[..])]).unwrap(); + let r = s.execute("file.place", &json!({"name": "a.docx", "dataBase64": vectorcraft_format::base64_encode(&zip)})).unwrap(); + assert_eq!(placed(&s, &r).0, "Grüße 東京", "little-endian: {le}"); + } +} + +/// A style's `w:basedOn` chain stops at a style already in it, and takes in at most 32 styles. +#[test] +fn docx_based_on_chains_stop_at_a_cycle_and_after_32_styles() { + let mut styles = String::from(concat!( + r#""#, + r#""#, + )); + // S0 is based on S1, S1 on S2, and so on to S32, the only one that sets a size. + for i in 0..32 { + styles += &format!(r#""#, i + 1); + } + styles += r#""#; + let para = |style: &str, text: &str| format!(r#"{text}"#); + let body = [para("A", "cycle"), para("S1", "thirty-two"), para("S0", "thirty-three"), "plain".into()].concat(); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "styles.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, &styles))})).unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("not type") }; + let size = |word: &str| t.runs.iter().find(|r| r.text.contains(word)).map(|r| r.style.size); + assert_eq!(t.paragraph_styles()[0].justify, vectorcraft_doc::Justify::Center, "A takes its own alignment"); + assert_eq!(size("cycle"), Some(20.0), "A takes the size of B, which is based on A"); + assert_eq!(size("thirty-two"), Some(20.0), "a chain of 32 styles takes in the last one"); + assert_ne!(size("thirty-three"), Some(20.0), "a chain of 33 styles leaves the last one out"); + assert_eq!(size("thirty-three"), size("plain")); +} + +/// Run containers and table rows nested more than 64 deep are left out; ones nested 60 deep are placed. +#[test] +fn docx_run_containers_and_table_rows_nested_past_the_depth_read_are_left_out() { + let wrap = |n: usize, open: &str, close: &str, inner: &str| format!("{}{inner}{}", open.repeat(n), close.repeat(n)); + let run = |text: &str| format!("{text}"); + let tagged = |n: usize, text: &str| wrap(n, "", "", &run(text)); + let row = |n: usize, text: &str| { + let tr = format!("{}", run(text)); + format!("{}", wrap(n, "", "", &tr)) + }; + let body = format!("{}{}{}{}{}", tagged(70, "deep "), tagged(60, "kept "), run("shallow"), row(70, "deep row"), row(60, "kept row")); + let mut s = session(); + let r = s.execute("file.place", &json!({"name": "nested.docx", "dataBase64": vectorcraft_format::base64_encode(&docx(&body, ""))})).unwrap(); + assert_eq!(placed(&s, &r).0, "kept shallow\nkept row"); +} + /// The bytes of the Prls `prls`: each sprm and its operand. fn prls(prls: &[(u16, &[u8])]) -> Vec { prls.iter().flat_map(|(sprm, op)| sprm.to_le_bytes().into_iter().chain(op.iter().copied())).collect() @@ -927,6 +1007,14 @@ fn malformed_doc_fails_cleanly() { assert!(e.contains("compound file structure is damaged"), "{e}"); let e = place(&mut s, "a.doc", &compound_file(&[("WordDocument", &[0; 900])])).unwrap_err(); assert!(e.contains("doesn't start with a file information block"), "{e}"); + // A WordDocument stream whose directory entry gives one byte more than 64 MB is refused from that length, before + // any of it is read. The stream length is at byte 120 of the entry, which starts with the stream's name. + let mut large = compound_file(&[("WordDocument", &[0; 4096])]); + let name = utf16("WordDocument", true); + let entry = large.windows(name.len()).position(|w| w == name).unwrap(); + large[entry + 120..entry + 128].copy_from_slice(&((64u64 << 20) + 1).to_le_bytes()); + let e = place(&mut s, "a.doc", &large).unwrap_err(); + assert!(e.contains("too large to place (its WordDocument stream holds more than 64 MB)"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { nfib: 0x0065, ..words() }.build()).unwrap_err(); assert!(e.contains("Word 6.0 or Word 95"), "{e}"); let e = place(&mut s, "a.doc", &Word97 { flags: 0x0100, ..words() }.build()).unwrap_err(); From c2d242eafa41cc127987f0121d1ad50b94aebd39 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:09:24 -0800 Subject: [PATCH 433/533] Tests: cover PDF mesh shadings, restroked glyphs, repeated masks and spot midpoints Adds tests for PDF import and export paths that no test reached: - A tensor-product patch mesh (type 7) imports as the gradient mesh of its boundary, the same mesh a Coons patch over that boundary gives. - A triangle mesh (type 4) imports as one gradient mesh per triangle, each corner in its vertex's color. - Tensor and triangle meshes over the 16,384-patch limit import as a flat gray with a warning. - The last glyph of a run stroked again in another color splits off into its own run; the glyph before it keeps its stroke. - A masked CMYK image drawn twice at two sizes keeps its opacity mask both times, fitted to each drawing; with a mask that hides nothing it has no mask either time. - A one-spot-ink gradient with an off-center midpoint exports a stop at the midpoint with the mean tint, still as a Separation shading. Each test fails with the code it covers broken. --- crates/engine/src/tests/linked_stops.rs | 10 ++++ crates/pdf/src/tests/cmykimages.rs | 50 ++++++++++++++++ crates/pdf/src/tests/import_fidelity.rs | 79 +++++++++++++++++++++++++ crates/pdf/src/tests/textstroke.rs | 19 ++++++ 4 files changed, 158 insertions(+) diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index a0f001afe6..4aa7d4c2a1 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -133,6 +133,16 @@ fn spot_gradients_export_as_separation_shadings() { assert!(pdf.contains("/ShadingType 2") && pdf.contains("/Separation/Ink/DeviceCMYK"), "an Ink → paper gradient is a Separation shading"); // Its function runs over the tints: 80 % (204 / 255) to 0 %. assert!(pdf.contains("/C0[0.8]/C1[0]"), "the shading's tints"); + // An off-center midpoint adds a stop there at the mean tint, still in the one spot ink. + run( + &mut s, + "paint.editGradient", + json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80, "midpoint": 30}, {"offset": 1, "color": "#ffffff"}]}), + ); + let (pdf, _) = pdf_of(&s); + assert!(pdf.contains("/Separation/Ink/DeviceCMYK") && !pdf.contains("/DeviceN"), "still one spot ink"); + let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 24)).collect(); + assert!(pdf.contains("/C0[0.8]/C1[0.4]") && pdf.contains("/C0[0.4]/C1[0]"), "the tints through the midpoint: {functions:?}"); // Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning. run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); let (pdf, warnings) = pdf_of(&s); diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index ef20585154..fc9f306ffe 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -331,6 +331,56 @@ fn masked_cmyk_images_keep_their_inks_and_carry_the_mask_as_an_opacity_mask() { assert!(masked(&r.document)[0].1.is_none()); } +/// A masked CMYK image drawn twice, at two sizes, carries its opacity mask both times: the same +/// mask image, fitted to each drawing. Drawn twice with a mask that hides nothing, it has no mask +/// either time. +#[test] +fn a_masked_cmyk_image_drawn_twice_keeps_its_mask_both_times() { + let z = |data: &[u8]| crate::output::deflate(data).unwrap(); + let file = |mask: &[u8]| { + let content = "q 50 0 0 50 10 10 cm /Im0 Do Q q 30 0 0 20 100 40 cm /Im0 Do Q"; + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>".to_vec(), + stream("", content.as_bytes()), + stream( + &format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "/SMask 6 0 R /Filter /FlateDecode")), + &z(&flat([0, 102, 255, 0], 4)), + ), + stream("/Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8", mask), + ]) + }; + let images = |d: &Document| { + let NodeKind::Layer { children, .. } = &d.layers[0].kind else { panic!() }; + children.iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).cloned().collect::>() + }; + let r = import_with_report(&file(&[255, 128, 255, 128]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + let mut keys = vec![]; + for n in &drawn { + let mask = n.extras().mask.as_ref().expect("an opacity mask on each drawing"); + let NodeKind::Image(a) = &mask.art.kind else { panic!("mask art is an image: {:?}", mask.art.kind) }; + assert_eq!((a.width, a.height), (2, 2)); + assert!(near(n.geometric_bounds(), mask.art.geometric_bounds()), "{:?} {:?}", n.geometric_bounds(), mask.art.geometric_bounds()); + keys.push(a.key.clone()); + } + assert_eq!(keys[0], keys[1], "one mask image"); + assert!(drawn[0].geometric_bounds() != drawn[1].geometric_bounds(), "two sizes"); + let r = import_with_report(&file(&[255; 4]), &ImportOptions::default()).unwrap(); + let drawn = images(&r.document); + assert_eq!(drawn.len(), 2); + assert!(drawn.iter().all(|n| n.extras().mask.is_none()), "a mask that hides nothing adds none, either time"); +} + +fn near(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6), + _ => false, + } +} + /// Every image blob a document's art uses (mask art included). fn all_images(d: &Document) -> Vec<&ImageBlob> { let mut keys = vec![]; diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 731f18ff06..852507f96a 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -712,6 +712,85 @@ fn a_mesh_shading_of_thousands_of_patches_becomes_gradient_meshes() { assert_eq!(all(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Mesh(_))).count(), 5000); } +/// The gradient meshes a page drawing shading `sh` (`/Sh0 sh`) comes in as, with the import's +/// warnings. +fn meshes_of(sh: &str) -> (Vec, Vec) { + let s = first_extra(1); + let r = open_with(&one_page("/Sh0 sh", &format!("/Shading << /Sh0 {s} 0 R >>"), &[sh]), |_| {}); + let meshes = all(&r.document).into_iter().filter_map(|n| if let NodeKind::Mesh(m) = n.kind { Some(m) } else { None }).collect(); + (meshes, r.warnings) +} + +/// A tensor-product patch mesh shading's dictionary for [`tensor_patch`] data. +const TENSOR_MESH: &str = "/ShadingType 7 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One tensor patch over the same boundary as [`coons_patch`], with its four inner points far +/// outside it at (250, 250). +fn tensor_patch() -> Vec { + let mut data = coons_patch(); + let colors = data.split_off(1 + 24); + data.extend([250; 8]); + data.extend(colors); + data +} + +/// A triangle mesh shading's dictionary (types 4 and 5 share their vertex layout). +const TRIANGLE_MESH: &str = "/ShadingType 4 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 /Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode"; + +/// One triangle: red at (10, 10), green at (90, 10), blue at (50, 90), each vertex with flag 0. +fn triangle() -> Vec { + [[0, 10, 10, 255, 0, 0], [0, 90, 10, 0, 255, 0], [0, 50, 90, 0, 0, 255]].concat() +} + +/// A tensor-product patch mesh (type 7) comes in as the gradient mesh of its boundary, the same +/// mesh a Coons patch over that boundary gives: its inner points do not move it. +#[test] +fn a_tensor_patch_mesh_becomes_the_gradient_mesh_of_its_boundary() { + let (tensor, warnings) = meshes_of(&stream(TENSOR_MESH, &hex(&tensor_patch()))); + let [m] = tensor.as_slice() else { panic!("one mesh: {tensor:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + assert!((at(0, 0).p - kurbo::Point::new(10.0, 90.0)).hypot() < 0.01, "{:?}", at(0, 0).p); + assert!((at(1, 1).p - kurbo::Point::new(90.0, 10.0)).hypot() < 0.01, "{:?}", at(1, 1).p); + assert_eq!(at(0, 0).color.to_rgb(), [1.0, 0.0, 0.0]); + assert_eq!(at(1, 0).color.to_rgb(), [0.0, 1.0, 0.0]); + assert_eq!(at(1, 1).color.to_rgb(), [0.0, 0.0, 1.0]); + assert_eq!(at(0, 1).color.to_rgb(), [1.0, 1.0, 1.0]); + let (coons, _) = meshes_of(&stream(COONS_MESH, &hex(&coons_patch()))); + assert_eq!(Some(m), coons.first(), "the mesh of a Coons patch over the same boundary"); +} + +/// A triangle mesh (types 4 and 5) comes in as one gradient mesh per triangle, a patch whose last +/// two corners are the triangle's third vertex, each corner in its vertex's color. +#[test] +fn a_triangle_mesh_becomes_a_gradient_mesh() { + let (meshes, warnings) = meshes_of(&stream(TRIANGLE_MESH, &hex(&triangle()))); + let [m] = meshes.as_slice() else { panic!("one mesh: {meshes:?} {warnings:?}") }; + assert_eq!((m.rows, m.cols), (1, 1)); + let at = |r, c| &m.points[m.idx(r, c)]; + // PDF y 10 is page y 90. + let want = [((0, 0), (10.0, 90.0), [1.0, 0.0, 0.0]), ((1, 0), (90.0, 90.0), [0.0, 1.0, 0.0]), ((1, 1), (50.0, 10.0), [0.0, 0.0, 1.0])]; + for ((r, c), (x, y), color) in want { + assert!((at(r, c).p - kurbo::Point::new(x, y)).hypot() < 0.01, "({r}, {c}): {:?}", at(r, c).p); + assert_eq!(at(r, c).color.to_rgb(), color, "({r}, {c})"); + } + assert_eq!(at(0, 1).p, at(1, 1).p, "the third vertex closes the patch"); +} + +/// A tensor patch or triangle mesh of more patches than the importer reads is not a gradient mesh: +/// it comes in as a flat gray, with a warning. +#[test] +fn a_tensor_or_triangle_mesh_over_the_patch_limit_is_a_flat_gray() { + let over = 16_385; + let tensor: Vec = std::iter::repeat_n(tensor_patch(), over).flatten().collect(); + let triangles: Vec = std::iter::repeat_n(triangle(), over).flatten().collect(); + for (name, sh) in [("tensor", stream(TENSOR_MESH, &hex(&tensor))), ("triangle", stream(TRIANGLE_MESH, &hex(&triangles)))] { + let (meshes, warnings) = meshes_of(&sh); + assert!(meshes.is_empty(), "{name}: {} meshes", meshes.len()); + assert!(warnings.iter().any(|w| w.contains("flat grey")), "{name}: {warnings:?}"); + } +} + /// A stroke painted with a mesh shading (how Illustrator writes a freeform gradient on a stroke) /// is the mesh clipped to the area the stroke paints, dashes included, not a flat grey. #[test] diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index 109685c9c7..01b4035be5 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -556,6 +556,25 @@ fn a_glyph_stroked_again_where_it_was_drawn_stays_one_type_object() { } } +/// The last glyph of a run stroked again where it was drawn, in another stroke color, splits off +/// into its own run with that stroke; the glyphs before it keep theirs. +#[test] +fn the_last_glyph_stroked_again_in_another_color_splits_off_with_that_stroke() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + // Helvetica's A is 667 units wide, so in 48-point type B stands at 20 + 32.016. + let content = "0 0 0 RG 1 1 0.8 rg 3 w BT /F1 48 Tf 1 0 0 1 20 80 Tm 2 Tr (AB) Tj 1 0 0 RG 1 Tr 1 0 0 1 52.016 80 Tm (B) Tj 0 Tr ET"; + let resources = "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>"; + let d = import(&pdf(&[PdfPage { resources: resources.into(), ..PdfPage::new(300.0, 200.0, content) }], None)).unwrap(); + let mut types = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + types.push(t.runs.iter().map(|r| (r.text.clone(), !r.style.fill.is_none(), r.style.stroke.color())).collect::>()); + } + }); + let want = [vec![("A".to_string(), true, Some(Color::BLACK)), ("B".to_string(), true, Some(Color::rgb(1.0, 0.0, 0.0)))]]; + assert_eq!(types, want); +} + /// A stroke pass longer than the importer holds at once ([`MAX_HELD`] strokes) goes over its own /// operator's glyphs, filled right before it, also when an operator before it filled the same /// glyphs at the same places: `A` and 4,095 `B`s filled, then `A` and 4,096 `B`s filled and From 284ce3e3d47bdef0b76665e9dbe696842fa8a9e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:19:20 -0800 Subject: [PATCH 434/533] Find and Replace: ui.dialog.confirm presses the button the action field names Since the dialog moved to the craft UI framework, `ui.dialog.confirm` on Find and Replace was refused ("the dialog refuses OK"), and `ui.inspect` listed no `action` field, although the params text and docs/mcp.md describe both. - `ui.inspect` lists the open dialog's `action`, `find` until a set changes it. - `ui.dialog.set` takes `action` (as `field`/`value` or in `fields`): find, replace, replaceFind, replaceAll or done. Any other value is an error, and nothing in the request is set. - `ui.dialog.confirm`, or a set with `action: "confirm"`, presses that button as a click does and puts `action` back to find. Replace and Replace & Find find a match when Find Next has reached none; done closes the dialog. A set whose fields are refused presses nothing. --- crates/ui-egui/src/control.rs | 5 + crates/ui-egui/src/dialogs/find_replace.rs | 148 ++++++++++++++++++ .../ui-egui/src/dialogs/find_replace/tests.rs | 101 ++++++++++++ crates/ui-egui/src/state.rs | 5 + 4 files changed, 259 insertions(+) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bfe9f1991c..4bbfe819ff 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -153,6 +153,7 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + crate::dialogs::find_replace::show_action(app, &mut dialogs); // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { open.insert(0, strip); @@ -1463,6 +1464,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if let Some(r) = crate::dialogs::script_window::dialog_method(app, method, ¶ms) { return wrap(r); } + // Find and Replace presses the button its `action` field names and stays open. + if let Some(r) = crate::dialogs::find_replace::dialog_method(app, ctx, method, ¶ms) { + return wrap(r); + } // `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the // framework's method does not take. let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 78a24f8868..cb987773ff 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -17,6 +17,8 @@ //! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's //! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the //! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame. +//! Automation presses the buttons through the dialog's `action` field and `ui.dialog.confirm` +//! ([`dialog_method`]). use craft::text::find::FindOptions; use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons}; @@ -109,6 +111,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result) { let (matched, match_message) = refresh_match(app, &form.query); + let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { if let Some(d) = host.get_mut::() { if let Some(message) = message.or(match_message) { @@ -351,5 +361,143 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } +/// The values the `action` field takes: the button `ui.dialog.confirm` presses. +const ACTIONS: [&str; 5] = ["find", "replace", "replaceFind", "replaceAll", "done"]; + +/// The `action` field a `ui.dialog.set` gives, as `field` and `value` or as an item of `fields`, taken +/// out of `params`: `Ok(None)` when it gives none, an error when it is not one of [`ACTIONS`]. +fn take_action(params: &mut Value) -> Result, String> { + let Some(o) = params.as_object_mut() else { return Ok(None) }; + let mut given = None; + if o.get("field").and_then(Value::as_str) == Some("action") { + if o.contains_key("fields") { + return Err("`fields` takes the place of `field` and `value`".into()); + } + o.remove("field"); + given = Some(o.remove("value").unwrap_or(Value::Null)); + } + let mut only_action = false; + if let Some(list) = o.get_mut("fields").and_then(Value::as_array_mut) { + let is_action = |item: &Value| item.get("field").and_then(Value::as_str) == Some("action"); + if let Some(last) = list.iter().rev().find(|item| is_action(item)) { + given = Some(last.get("value").cloned().unwrap_or(Value::Null)); + } + let before = list.len(); + list.retain(|item| !is_action(item)); + only_action = list.is_empty() && before > 0; + } + // A list that held only `action` sets nothing else. + if only_action { + o.remove("fields"); + } + match given { + None => Ok(None), + Some(Value::String(a)) if ACTIONS.contains(&a.as_str()) => Ok(Some(a)), + Some(_) => Err("`action` must be find, replace, replaceFind, replaceAll or done".into()), + } +} + +/// The open dialog as `ui.inspect` lists it, `{id, parent, key, fields}` with its `action`, or null. +fn listed(app: &VectorcraftApp) -> Value { + let Some(dialogs) = app.dialogs() else { return Value::Null }; + let mut open = dialogs.with(|host| craft::automation::dialogs::inspect(host)); + show_action(app, &mut open); + let id = dialogs.with(|host| host.get::().map(|d| d.id().value().to_string())); + open.as_array().and_then(|open| open.iter().find(|d| id.as_deref().is_some_and(|id| d["id"] == id)).cloned()).unwrap_or(Value::Null) +} + +/// Adds the `action` field to the open Find and Replace dialog in `ui.inspect`'s `dialogs`. +pub(crate) fn show_action(app: &VectorcraftApp, dialogs: &mut Value) { + let Some(id) = app.dialogs().and_then(|d| d.with(|host| host.get::().map(|d| d.id().value().to_string()))) else { return }; + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); + let shown = dialogs.as_array_mut().and_then(|open| open.iter_mut().find(|d| d["id"] == id.as_str())); + if let Some(fields) = shown.and_then(|d| d.get_mut("fields")).and_then(Value::as_object_mut) { + fields.insert("action".into(), json!(action)); + } +} + +/// `ui.dialog.set` and `ui.dialog.confirm` (`method`) on the open Find and Replace dialog, when +/// `params.dialog` names it: a set takes the `action` field, and `ui.dialog.confirm`, or a set with +/// `action: "confirm"`, presses the button it names (`find` when none is set) and leaves `action` at +/// `find` again. Every other request is the host's, as is a set that gives no `action` field and +/// does not confirm: `None`. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Option> { + if !matches!(method, "ui.dialog.set" | "ui.dialog.confirm") { + return None; + } + let dialogs = app.dialogs()?; + let ours = dialogs.with(|host| { + let id = host.get::().map(StackDialog::id); + id.is_some() && craft::automation::dialogs::dialog_id(host, params).ok() == id + }); + if !ours { + return None; + } + let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] }; + let mut params = params.clone(); + let answer = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { Some(json!("confirm")) }; + let given = if method == "ui.dialog.set" { + match take_action(&mut params) { + Ok(given) => given, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let confirm = match answer.as_ref().map(Value::as_str) { + None => false, + Some(Some("confirm")) => true, + // Cancel closes it as the host closes any dialog. + Some(Some("cancel")) if given.is_none() => return None, + Some(Some("cancel")) => false, + Some(_) => return Some(Err("`action` must be confirm or cancel".into())), + }; + if given.is_none() && !confirm { + return None; + } + if let Err(e) = craft::automation::protocol::Params(¶ms).only(None, keys) { + return Some(Err(e)); + } + // The other fields are set first, all or none, as the host sets and checks them. + let sets = ["field", "value", "fields"].iter().any(|k| params.get(k).is_some()); + if sets && let Some(Err(e)) = dialogs.with(|host| craft::automation::dialogs::dialog_method(host, ctx, "ui.dialog.set", ¶ms)) { + return Some(Err(e)); + } + if let Some(given) = given { + app.ui.find_action = Some(given); + } + if answer.as_ref().and_then(Value::as_str) == Some("cancel") { + dialogs.with(|host| host.cancel::(ctx)); + return Some(Ok(Value::Null)); + } + Some(if confirm { press(app, ctx) } else { Ok(listed(app)) }) +} + +/// Presses the button the `action` field names, as a click on it does, and leaves `action` at +/// `find`. Replace and Replace & Find find a match when Find Next has reached none with the Find +/// text and the switches as they are now. Done closes the dialog → the dialog as listed, or null +/// once closed; a refusal is the dialog's message and the error. +fn press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result { + let action = app.ui.find_action.take().unwrap_or_else(|| "find".into()); + let dialogs = app.dialogs().ok_or("no window")?; + let form = dialogs.with(|host| host.get::().map(form)).ok_or("no hosted dialog is open")?; + if action == "done" { + dialogs.with(|host| host.cancel::(ctx)); + return Ok(Value::Null); + } + let found = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); + let ran = match action.as_str() { + "replace" | "replaceFind" if found => replace(app, &form, action == "replaceFind"), + "replaceAll" => replace_all(app, &form), + _ => find(app, &form), + }; + let message = match &ran { + Ok(m) => Some(m.clone()), + Err(e) => Some(said(e)), + }; + report(app, &form, message); + ran.map(|_| listed(app)) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index e90efe3f8a..81e550c77a 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -97,6 +97,107 @@ fn selected(p: &Panel) -> Vec { p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() } +/// A control request answered at once → its result, or its error. +fn control(p: &Panel, method: &str, params: Value) -> Result { + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(&mut p.app(), p.ctx(), &req) else { panic!("{method} answered later") }; + match r.get("error") { + Some(e) if !e.is_null() => Err(e.as_str().map_or_else(|| e.to_string(), str::to_string)), + _ => Ok(r["result"].clone()), + } +} + +/// The open Find and Replace dialog's `action`, as `ui.inspect` lists it. +fn listed_action(p: &Panel) -> Value { + let r = control(p, "ui.inspect", json!({})).unwrap(); + let open = r["dialogs"].as_array().cloned().unwrap_or_default(); + open.last().map(|d| d["fields"]["action"].clone()).unwrap_or(Value::Null) +} + +fn set_action(p: &Panel, action: &str) { + control(p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": action})).unwrap(); +} + +/// `ui.inspect` lists the dialog's `action`, `find` until a set changes it. `ui.dialog.confirm` +/// presses the button it names, as a click does, keeps the dialog open and puts `action` back to +/// find. Replace and Replace & Find find a match when Find Next reached none; done closes it. +#[test] +fn confirm_presses_the_button_the_action_names() { + let (app, ids) = app_with(&["cat cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find")); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let before = undo_steps(&p); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "find runs without an action set"); + assert!(message(&p).starts_with("1 / 3"), "{}", message(&p)); + + set_action(&p, "replace"); + assert_eq!(listed_action(&p), json!("replace")); + let shown = control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(plain(&p, ids[0]), "dog cat cat", "replace changes the match found"); + assert_eq!((undo_steps(&p), listed_action(&p)), (before + 1, json!("find"))); + assert_eq!(shown["fields"]["action"], json!("find")); + + // Replace & Find with no match found finds one and changes nothing. + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog cat cat".to_string(), Some((ids[0], 4, 7)))); + set_action(&p, "replaceFind"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!((plain(&p, ids[0]), matched(&p)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)))); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": "replaceAll", "action": "confirm"})).unwrap(); + assert_eq!((plain(&p, ids[0]), message(&p)), ("dog dog dog".to_string(), "Matches replaced: 1".to_string())); + assert_eq!(undo_steps(&p), before + 3); + + // A set and confirm in one request closes the dialog with done. + let done = json!([{"field": "action", "value": "done"}]); + let closed = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": done, "action": "confirm"})).unwrap(); + assert_eq!(closed, Value::Null); + assert!(!is_open(&p)); +} + +/// An `action` that names no button is refused when it is set, as are the fields set with it, and +/// `action` stays as it was. A set and confirm whose set is refused presses no button. +#[test] +fn an_action_that_names_no_button_is_refused() { + let (app, ids) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = "`action` must be find, replace, replaceFind, replaceAll or done"; + for v in [json!("jump"), json!(3), json!(null), json!("Replace")] { + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "action", "value": v})); + assert_eq!(r, Err(refusal.to_string()), "{v}"); + } + let fields = json!([{"field": "replace", "value": "dog"}, {"field": "action", "value": "skip"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err(refusal.to_string())); + assert_eq!((field(&p, "replace"), listed_action(&p)), (json!(""), json!("find"))); + // A field the dialog refuses leaves `action` as it was. + let fields = json!([{"field": "matchCase", "value": "yes"}, {"field": "action", "value": "replaceAll"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert!(r.is_err(), "{r:?}"); + assert_eq!(listed_action(&p), json!("find")); + // A request with a key the method does not take is refused. + assert!(control(&p, "ui.dialog.confirm", json!({"dialog": "top", "action": "replace"})).is_err()); + // A set the host refuses presses nothing, even with `action: "confirm"`. + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "action", "value": "replaceAll"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + for bad in [json!({"fields": {}}), json!({"value": 1}), json!({"field": "nope", "value": 1})] { + let mut request = bad.clone(); + request["dialog"] = json!("top"); + request["action"] = json!("confirm"); + assert!(control(&p, "ui.dialog.set", request).is_err(), "{bad}"); + assert_eq!((plain(&p, ids[0]), listed_action(&p)), ("cat".to_string(), json!("replaceAll")), "{bad}"); + } + assert!(is_open(&p)); +} + #[test] fn a_cached_match_cannot_replace_text_restored_by_revert() { let (mut app, ids) = app_with(&["Needle Needle"]); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 990d245bc3..19ef45dbbc 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -732,6 +732,10 @@ pub struct UiState { /// Edit › Find Next goes on from while the dialog is closed. Not saved. #[serde(skip)] pub last_find: Option, + /// The open Find and Replace dialog's `action` field, the button `ui.dialog.confirm` presses + /// ([`crate::dialogs::find_replace::dialog_method`]); `None` is `find`. Not saved. + #[serde(skip)] + pub find_action: Option, /// The notes of the last open that gave any, or of the last save or export, with the status /// text that names the first of them: hovering that text lists them when there are several. /// Not saved. @@ -1530,6 +1534,7 @@ impl Default for UiState { status_sets: 0, replace_font_warning: None, last_find: None, + find_action: None, status_notes: None, startup_notes: Vec::new(), status_kept: None, From 314682ef6f7a97f5bd65c000a7ebaad394ee6cac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:20:45 -0800 Subject: [PATCH 435/533] EPS import: tests for LZW data, skipped image data, save limits and cvs text Adds tests for interpreter paths that no test reached: - LZWDecode: the PDF 32000 example (a code that is the entry it adds), 12 KB of data whose table grows through 9- to 12-bit codes and is cleared, and a code past the end of the table as an ioerror. - An image too large to hold whose data is LZW or run-length: the data is measured and skipped, and the art after it is read. - clipsave and gsave keep up to 1,000 saved states; the next one is a limit error. - A sampled function may hold 4096 x 4096 samples and no more (limitcheck on Size). - currenthsbcolor when green or blue is the largest channel, and gray. - cvs text of reals, booleans, names, operators and other objects, and cvrs radix text with uppercase digits, negative numbers as 32-bit two's complement, and a radix outside 2 to 36 refused. --- crates/eps/src/import/tests.rs | 33 ++++++++++++++++ crates/eps/src/import/tests_generators.rs | 16 ++++++++ crates/eps/src/import/tests_images.rs | 48 ++++++++++++++++++++++- 3 files changed, 96 insertions(+), 1 deletion(-) diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index f920a1c364..63793ff690 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -1061,6 +1061,20 @@ fn clipsave_and_cliprestore_bring_the_clip_back() { assert!(matches!(o[0].kind, NodeKind::Path { .. }), "{:?}", o[0].kind); } +/// `clipsave` and `gsave` each keep up to 1,000 saved states. One more is a limit error: the +/// square drawn before it stays, and the one after it is left out. +#[test] +fn clipsave_and_gsave_stop_at_a_thousand_saved_states() { + for (op, why) in [("clipsave", "too many saved clips"), ("gsave", "too many saved graphics states")] { + let r = read(&format!("0 0 10 10 rectfill 1000 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 2, "{op}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains(why)), "{op}: {:?}", r.warnings); + let r = read(&format!("0 0 10 10 rectfill 1001 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 1, "{op}: {:?}", r.warnings); + assert!(r.warnings.first().is_some_and(|w| w.contains(why)), "{op}: {:?}", r.warnings); + } +} + #[test] fn languagelevel_is_an_integer_and_runs() { // #234. @@ -1099,6 +1113,25 @@ fn intervals_share_their_arrays_and_strings() { ); } +/// `cvs` writes the text of each kind of object (PLRM 3rd ed., `cvs`): a real keeps a decimal +/// point, booleans, names and operators their names, other objects `--nostringval--`. `cvrs` +/// writes a number in a radix from 2 to 36 with uppercase digits, a negative one as its 32-bit +/// two's complement, and refuses any other radix. +#[test] +fn cvs_and_cvrs_write_the_text_of_each_kind() { + check("/s 16 string def 3.0 s cvs (3.0) eq"); + check("/s 16 string def 2.5 s cvs (2.5) eq"); + check("/s 16 string def true s cvs (true) eq"); + check("/s 16 string def /abc s cvs (abc) eq"); + check("/s 16 string def /add load s cvs (add) eq"); + check("/s 16 string def [1] s cvs (--nostringval--) eq"); + check("/s 16 string def 255 16 s cvrs (FF) eq"); + check("/s 16 string def 10 2 s cvrs (1010) eq"); + check("/s 16 string def 0 2 s cvrs (0) eq"); + check("/s 16 string def -1 16 s cvrs (FFFFFFFF) eq"); + check("/s 16 string def { 10 1 s cvrs } stopped { 10 37 s cvrs } stopped and"); +} + #[test] fn resourceforall_enumerates_matching_names() { // #234. diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 63859b3e52..17df25cd9c 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -861,6 +861,11 @@ fn probing_operators_answer() { "/n 0 def 0 0 moveto 10 0 lineto { pop pop /n n 1 add def } { pop pop /n n 2 add def } { 6 { pop } repeat } {} pathforall n 3 eq", ); super::tests::check("1 0 0 setrgbcolor currenthsbcolor 1 eq exch 1 eq and exch 0 eq and"); + // Green largest: hue (2 + (b - r) / d) / 6 = 5/12; blue largest: (4 + (r - g) / d) / 6 = 9/12; + // each with saturation 0.8 and brightness 1. Gray has no hue and no saturation. + super::tests::check("0.2 1 0.6 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 5 sub abs 1e-5 lt and"); + super::tests::check("0.6 0.2 1 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 9 sub abs 1e-5 lt and"); + super::tests::check("0.5 setgray currenthsbcolor 0.5 sub abs 1e-6 lt exch 0 eq and exch 0 eq and"); super::tests::check("currentcacheparams counttomark 2 eq exch pop exch pop exch pop"); super::tests::check("cachestatus 7 { pop } repeat true"); super::tests::check("currentcolorrendering /ColorRenderingType known"); @@ -997,6 +1002,17 @@ fn hostile_patterns_glyphs_and_shadings_end() { /Function << /FunctionType 0 /Domain [0 1] /Range [0 1] /Size [99999999] /BitsPerSample 8 /DataSource () >> >> shfill", ); assert!(r.warnings[0].contains("rangecheck in `shfill`: a sampled function"), "{:?}", r.warnings); + // A sampled function of two inputs may hold 2^24 samples (4096 × 4096), and no more. + let sized = |size: &str| { + read(&format!( + "0 0 1 1 rectfill << /ShadingType 1 /ColorSpace /DeviceGray \ + /Function << /FunctionType 0 /Domain [0 1 0 1] /Range [0 1] /Size [{size}] /BitsPerSample 8 /DataSource () >> >> shfill" + )) + }; + let r = sized("4096 4096"); + assert!(!r.warnings.iter().any(|w| w.contains("limitcheck")), "{:?}", r.warnings); + let r = sized("4096 4097"); + assert!(r.warnings[0].contains("limitcheck in `shfill`: Size"), "{:?}", r.warnings); // Procedures nesting through operators that run them end at the nesting limit. for body in ["/f { { f } exec } def f", "/f { true { f } if } def f", "/f { 1 { f } repeat } def f", "/f { { f } stopped } def f"] { assert!(import(&super::tests::eps(body)).is_err(), "{body}"); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 87a7560bfd..2324de4eb4 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -148,6 +148,35 @@ fn filters_read_the_file_they_were_made_over() { ); } +/// LZW data (`LZWDecode`, `EarlyChange` 1, PDF 32000 §7.4.4.2) decodes: the specification's +/// example, whose third code is the entry that code adds; data long enough that the table grows +/// past 511, 1023 and 2047 entries (9-, 10-, 11- and 12-bit codes) and is cleared and grown again; +/// and a code past the end of the table is an `ioerror`, the art after it left out. +#[test] +fn lzw_data_decodes_at_every_code_width() { + super::tests::check("<800B6050220C0C8501> /LZWDecode filter 20 string readstring pop (-----A---B) eq"); + let mut x = 0x2545_F491_u32; + let data: Vec = (0..12_000) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 24) as u8 + }) + .collect(); + let lzw = craft_stream_codecs::lzw::encode(&data, true); + super::tests::check(&format!( + "/f <{}> /LZWDecode filter def f {} string readstring exch <{}> eq and f read {{ pop false }} {{ true }} ifelse and", + hex(&lzw), + data.len(), + hex(&data) + )); + // A clear-table code, then code 300 while the table ends at 257. + let r = read("0 0 10 10 rectfill <804B00> /LZWDecode filter 4 string readstring 20 20 10 10 rectfill"); + assert_eq!(super::tests::objects(&r.document).len(), 1, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("ioerror") && w.contains("LZWDecode")), "{:?}", r.warnings); +} + /// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from /// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through /// the Decode array. Gray and RGB images stay PNGs. @@ -656,7 +685,8 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// An image too large to read even at a lower resolution (its samples are more data than the /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader -/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is +/// measured without keeping it. #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; @@ -666,6 +696,20 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); flate.extend(&zeros); flate.extend(format!("\n{after}").as_bytes()); + // The same through LZW, which counts the codes up to its end-of-data code. + let mut lzw = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true)); + lzw.extend(format!("\n{after}").as_bytes()); + // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of + // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in + // 200 and every run repeats 200, so a count that lands on a wrong byte reads each 200 as a + // run's length and stays off by one. + let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); + run_length.extend([2, 200, 200, 200]); + run_length.extend([129u8, 200].repeat((300 << 20) / 128)); + run_length.push(128); + run_length.extend(format!("\n{after}").as_bytes()); for program in [ format!( "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ @@ -673,6 +717,8 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { ) .into_bytes(), flate, + lzw, + run_length, ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); From 0ff5dc45d8073aa95e4a57d38d8880e3bad99f32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:21:29 -0800 Subject: [PATCH 436/533] Hyphenation: the dialog disables the options that do not apply to the paragraphs The Paragraph panel menu's Hyphenation dialog left every row editable. Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone and Hyphenate Capitalized Words now take input only while the Hyphenation checkbox is checked, as the Hyphenation tab of Paragraph Style Options already does. Hyphenation Zone applies only to a single-line composer, so it is disabled when every paragraph in scope uses another composer; when the paragraphs disagree it stays available. Automation is refused on a disabled row as it is on screen. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/hyphenation.rs | 112 +++++++++++++++++++--- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 +- 4 files changed, 103 insertions(+), 16 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index acbbb5d151..13417a7ea2 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1591,7 +1591,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "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", + "{} 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; the fields after hyphenate take input only while it is true, and hyphenationZone, which only a single-line composer uses, never while every paragraph uses another composer): OK runs text.setFormat with the values that changed, as one undo step; an error with no type selected", ), ( "ui.tateChuYokoSettings", diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index 4e9fae0914..b1f3894c55 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -3,14 +3,16 @@ //! Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone and Hyphenate Capitalized //! Words. The dialog opens on the values the Paragraph panel shows (blank fields and dashed //! checkboxes where paragraphs in scope disagree). OK runs `text.setFormat` with the values that -//! changed, as one undo step, and paragraphs that differ keep the values left alone. +//! changed, as one undo step, and paragraphs that differ keep the values left alone. The options +//! below the checkbox take input only while Hyphenation is on, and Hyphenation Zone, which applies +//! only to a single-line composer, is disabled when every paragraph in scope uses another composer. //! //! Fields: `hyphenate`, `wordsLongerThan` (letters, 1..25), `afterFirst` and `beforeLast` //! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and //! `hyphenateCapitalized`, as `text.setFormat` takes them. use craft::ui::contract::Bind; -use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; // PLAN: assumed paths of `UnitKind` and `LengthUnits` use craft::ui::runtime::env::{LengthUnits, UnitKind}; use serde_json::{Map, Value, json}; @@ -27,18 +29,21 @@ const FLAGS: [&str; 2] = ["hyphenate", "hyphenateCapitalized"]; const NUMBERS: [(&str, i64, i64); 5] = [("wordsLongerThan", 1, 25), ("afterFirst", 1, 15), ("beforeLast", 1, 15), ("hyphenLimit", 0, 25), ("hyphenationZone", 0, 0)]; -/// The rows of the dialog; the zone is shown in `lengths`. -fn rows(lengths: LengthUnits) -> Vec { +/// The rows of the dialog; the zone is shown in `lengths`. Every row below the checkbox takes input +/// only while Hyphenation is on, and Hyphenation Zone is disabled when `zone` is false. +fn rows(lengths: LengthUnits, zone: bool) -> Vec { + let on = |param: Param| param.enabled_when(FLAGS[0], FieldValue::Bool(true)); let count = - |(key, lo, hi): (&str, i64, i64), label, default, unit| Param::new(key, label, ParamKind::int(Some(lo), Some(hi), default)).unit(unit); + |(key, lo, hi): (&str, i64, i64), label, default, unit| on(Param::new(key, label, ParamKind::int(Some(lo), Some(hi), default)).unit(unit)); + let zone_row = on(Param::number(NUMBERS[4].0, tl!("Hyphenation Zone:"), 0.0, 1.0, 2).length(lengths).bounds(Some(0.0), None)); vec![ Param::new(FLAGS[0], tl!("Hyphenation"), ParamKind::bool(false)), count(NUMBERS[0], tl!("Words Longer Than:"), 5, UnitKind::Letters), count(NUMBERS[1], tl!("After First:"), 3, UnitKind::Letters), count(NUMBERS[2], tl!("Before Last:"), 3, UnitKind::Letters), count(NUMBERS[3], tl!("Hyphen Limit:"), 0, UnitKind::Hyphens), - Param::number(NUMBERS[4].0, tl!("Hyphenation Zone:"), 0.0, 1.0, 2).length(lengths).bounds(Some(0.0), None), - Param::new(FLAGS[1], tl!("Hyphenate Capitalized Words"), ParamKind::bool(true)), + if zone { zone_row } else { zone_row.disabled() }, + on(Param::new(FLAGS[1], tl!("Hyphenate Capitalized Words"), ParamKind::bool(true))), ] } @@ -76,11 +81,12 @@ pub fn open(app: &mut VectorcraftApp) -> Result { set_shared(&mut fields, NUMBERS[2].0, crate::panels::paragraph::shared_hyphenation_field(app, |h| h.before_last).map(i64::from)); set_shared(&mut fields, NUMBERS[3].0, crate::panels::paragraph::shared_hyphenation_field(app, |h| h.hyphen_limit).map(i64::from)); set_shared(&mut fields, NUMBERS[4].0, crate::panels::paragraph::shared_hyphenation_zone(app)); + let zone = crate::panels::paragraph::shared_para(app, |p| p.composer.is_single_line()) != Some(false); let initial = fields.clone(); let ctx = app.ui_ctx.clone().ok_or("no window")?; let lengths = crate::canvas::rulers::general_lengths(app); let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { - ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields)) + ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths, zone)).values(Bind::bound(fields)) }); super::host::open_held(app, dialog, move |app, result| { let mut p = params(&result.fields, &initial); @@ -230,18 +236,20 @@ mod tests { assert_eq!(before.number("wordsLongerThan"), Some(5.0)); assert_eq!(before.bool("hyphenate"), Some(false)); assert!(before.is_mixed("afterFirst")); + // The counts take input once Hyphenation is on. + click(&mut app, &mut frame, enabled.center()); + settle(&mut app, &mut frame); + let checked = draft(&app, &ctx)["hyphenate"].as_bool(); click(&mut app, &mut frame, count.center()); press(&mut app, &mut frame, Key::A, Modifiers::COMMAND); frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]); press(&mut app, &mut frame, Key::Tab, Modifiers::NONE); settle(&mut app, &mut frame); - let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64(); - click(&mut app, &mut frame, enabled.center()); let inspected = draft(&app, &ctx); let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool()); - eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}"); - if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { - failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}")); + eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after checkbox {checked:?}, after typing {kept:?}"); + if checked != Some(true) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { + failures.push(format!("{lang} {answer}: {checked:?}, {kept:?}")); } assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); if answer == "ui.dialog.confirm" { @@ -293,6 +301,7 @@ mod tests { #[test] fn hyphenation_dialog_sets_the_paragraphs_options() { let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "composer": "singleLine"})).unwrap(); app.run("ui.hyphenation", json!({})).unwrap(); let f = driver::fields(&app); assert_eq!((f.bool("hyphenate"), f.number("wordsLongerThan"), f.number("hyphenLimit")), (Some(false), Some(5.0), Some(0.0))); @@ -322,6 +331,7 @@ mod tests { app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap(); app.run("ui.hyphenation", json!({})).unwrap(); assert!(driver::fields(&app).is_mixed("afterFirst")); + driver::set(&mut app, "hyphenate", json!(true)); driver::set(&mut app, "beforeLast", json!(4)); driver::ok(&mut app); let (first, second) = paras(&app, id); @@ -337,6 +347,82 @@ mod tests { assert!(!driver::is_open(&app)); } + /// The options below the checkbox take input only while Hyphenation is on, on screen and through + /// automation, including while the paragraphs in scope disagree on Hyphenation. + #[test] + fn hyphenation_options_take_input_only_with_hyphenation_on() { + let options = [ + ("Words Longer Than", "wordsLongerThan", json!(8)), + ("After First", "afterFirst", json!(2)), + ("Before Last", "beforeLast", json!(4)), + ("Hyphen Limit", "hyphenLimit", json!(2)), + ("Hyphenation Zone", "hyphenationZone", json!(12)), + ("Hyphenate Capitalized Words", "hyphenateCapitalized", json!(false)), + ]; + for mixed in [false, true] { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "composer": "singleLine"})).unwrap(); + if mixed { + app.run("text.setFormat", json!({"ids": [id], "hyphenate": true, "start": 5, "end": 5})).unwrap(); + } + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.hyphenation", json!({})).unwrap(); + panel.frame(); + assert_eq!(driver::fields(&panel.app()).is_mixed("hyphenate"), mixed); + for (label, key, value) in &options { + assert!(!panel.enabled(label), "mixed {mixed}: {label} takes input with Hyphenation off"); + assert!(driver::try_set(&mut panel.app(), key, value.clone()).is_err(), "mixed {mixed}: automation set {key}"); + } + driver::set(&mut panel.app(), "hyphenate", json!(true)); + panel.frame(); + for (label, key, value) in &options { + assert!(panel.enabled(label), "mixed {mixed}: {label} is disabled with Hyphenation on"); + driver::try_set(&mut panel.app(), key, value.clone()).unwrap_or_else(|e| panic!("mixed {mixed}: {key} refused: {e}")); + } + driver::ok(&mut panel.app()); + let want = HyphenationOptions { words_longer_than: 8, after_first: 2, before_last: 4, hyphen_limit: 2, zone: 12.0, capitalized: false }; + let (first, second) = paras(&panel.app(), id); + for p in [first, second] { + assert!(p.hyphenate && p.hyphenation == want, "mixed {mixed}: {p:?}"); + } + } + } + + /// Hyphenation Zone applies only to a single-line composer: it is disabled while every paragraph + /// in scope uses another composer, and takes input when any of them uses a single-line one. The + /// other options stay available either way. + #[test] + fn hyphenation_zone_takes_input_only_with_a_single_line_composer() { + let cases = [ + (["everyLine", "everyLine"], false), + (["standardEveryLine", "everyLine"], false), + (["singleLine", "singleLine"], true), + (["standardSingleLine", "standardSingleLine"], true), + (["everyLine", "standardSingleLine"], true), + ]; + for (composers, zone) in cases { + let (mut app, id) = app(); + app.run("text.setFormat", json!({"ids": [id], "hyphenate": true})).unwrap(); + for (at, composer) in [0, 5].into_iter().zip(composers) { + app.run("text.setFormat", json!({"ids": [id], "composer": composer, "start": at, "end": at})).unwrap(); + } + let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("ui.hyphenation", json!({})).unwrap(); + panel.frame(); + assert_eq!(panel.enabled("Hyphenation Zone"), zone, "{composers:?}: Hyphenation Zone on screen"); + assert!(panel.enabled("Words Longer Than"), "{composers:?}"); + let set = driver::try_set(&mut panel.app(), "hyphenationZone", json!(36)); + assert_eq!(set.is_ok(), zone, "{composers:?}: automation set the zone: {set:?}"); + driver::set(&mut panel.app(), "wordsLongerThan", json!(7)); + driver::ok(&mut panel.app()); + let want = if zone { 36.0 } else { 0.0 }; + let (first, second) = paras(&panel.app(), id); + for p in [first, second] { + assert_eq!((p.hyphenation.zone, p.hyphenation.words_longer_than), (want, 7), "{composers:?}"); + } + } + } + #[test] fn hyphenation_confirm_keeps_the_opening_selection() { let (mut app, first) = app(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e131421a2a..8b3b04a93e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1592,7 +1592,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "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", + "{} 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; the fields after hyphenate take input only while it is true, and hyphenationZone, which only a single-line composer uses, never while every paragraph uses another composer): OK runs text.setFormat with the values that changed, as one undo step; an error with no type selected", ), ( "ui.tateChuYokoSettings", diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..f77b041d47 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14178,7 +14178,8 @@ The letter and line counts are rounded, and every value is clamped to its range. listed word. The options are saved with the paragraph (`hyphenation` in `para`) only when they differ from the defaults, and paragraph styles carry them (`paraStyle.new {attrs: {hyphenation: {words_longer_than: 8}}}`). One undo step. `ui.hyphenation` opens the Hyphenation dialog on the values the Paragraph panel shows; OK sends the values that -changed. The UI command `type.hyphenate` (Cmd+Alt+Shift+H, in remote mode `press_key {key: "H", mods: {cmd: true, +changed. The options below the Hyphenation checkbox take input only while it is checked, and Hyphenation Zone is +disabled while no paragraph in scope uses a single-line composer. The UI command `type.hyphenate` (Cmd+Alt+Shift+H, in remote mode `press_key {key: "H", mods: {cmd: true, alt: true, shift: true}}` or `invoke_menu`) does what the Hyphenate checkbox does: it turns `hyphenate` off when every paragraph of the selected type (or every paragraph the Type tool's selection touches) hyphenates, else on, and returns the new value. From 9ec2f5c4bd964a9e8924d95fd5ec9e59bc717751 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:26:18 -0800 Subject: [PATCH 437/533] Tests: cover three undo group paths no test reached - A document added outside a command while edit.undoGroup.begin is open joins the group: its two edits are one "Job" step, and one undo takes both back (Session::add_document). - Canceling a group rewrites a batch's journal entry: a dropped step that left another document in front becomes document.activate with that index, so the edit made after the group replays in the same document (keep_batch_steps). - Renaming a graph design to its own name succeeds and records no undo step, and the design list stays the same. Each test fails with the covered lines removed. --- crates/engine/src/cmd/graph/tests.rs | 5 +++ crates/engine/src/tests/journal.rs | 58 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b41415ef02..95aa571b48 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6891,6 +6891,11 @@ fn new_design_rename_delete_and_select_unused() { assert_eq!(spec(&s, id).series_markers, [Some("Dot".to_string()), Some("Dot".to_string())]); assert!(s.execute("graph.design", &json!({"rename": "Dot", "to": "New Design 2"})).is_err(), "taken"); assert!(s.execute("graph.design", &json!({"rename": "Nope", "to": "X"})).is_err()); + // Renaming a design to its own name succeeds and records no undo step. + let (steps, designs) = (s.doc().unwrap().history.undo.len(), s.execute("graph.design", &json!({})).unwrap()["designs"].clone()); + assert_eq!(s.execute("graph.design", &json!({"rename": "Dot", "to": "Dot"})).unwrap()["name"], "Dot"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], designs); // Delete several at once. s.execute("graph.design", &json!({"delete": ["Dot", "New Design 2"]})).unwrap(); assert_eq!(s.execute("graph.design", &json!({})).unwrap()["designs"], json!([])); diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 0b35b2f772..35f86fa582 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -966,6 +966,45 @@ fn canceling_an_undo_group_keeps_a_batchs_steps_in_other_documents() { assert_eq!(r.active_index(), s.active_index()); } +/// A batch step in the canceled group that leaves another document in front (switching to the +/// grouped document measures its type again in its own composite font) is dropped from the batch's +/// journal entry and replaced by that switch, so the edit made after the group replays in the +/// document it was made in. +#[test] +fn canceling_an_undo_group_keeps_the_switch_of_a_dropped_batch_step() { + let mut s = Session::new(); + let fonts = |size: i32| { + let parts = json!({"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono", "size": size}}); + json!({"fonts": [{"name": "CF Undo Group", "parts": parts}]}) + }; + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(50)).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab", "size": 20, "font": "CF Undo Group"})).unwrap(); + s.execute("file.new", &json!({"created": null})).unwrap(); + s.execute("type.compositeFonts.set", &fonts(75)).unwrap(); + let objects = |s: &Session| s.documents().iter().map(|d| d.doc.node_count()).collect::>(); + let before = objects(&s); + let activate = |index: usize| json!({"command": "document.activate", "params": {"index": index}}); + let steps = json!([rect_step(10), activate(0)]); + for (id, p) in [ + ("document.activate", json!({"index": 0})), + ("edit.undoGroup.begin", json!({})), + ("shape.rectangle", rect_step(50)["params"].clone()), + ("document.activate", json!({"index": 1})), + ("command.batch", json!({ "commands": steps })), + ("edit.undoGroup.end", json!({"cancel": true})), + ("shape.rectangle", rect_step(30)["params"].clone()), + ] { + s.execute(id, &p).unwrap(); + } + assert_eq!(objects(&s), vec![before[0] + 1, before[1] + 1]); + let (_, batch) = s.journal.iter().find(|(id, _)| id == "command.batch").unwrap(); + assert_eq!(batch["commands"], json!([steps[0], activate(0)])); + let r = replayed(&s); + assert_eq!(documents(&r), documents(&s)); + assert_eq!(r.active_index(), s.active_index()); +} + /// The edits made in an undo group (a scrubbed numeric field, #400) are one undo step, journaled /// one by one; a cancelled group undoes them and leaves the journal as it was. #[test] @@ -1074,6 +1113,25 @@ fn an_undo_group_begun_by_command_opens_in_each_document_created_before_its_end( assert!(s.doc().unwrap().undo_group.is_none()); } +/// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a document added outside a command (a +/// template the app opens itself) opens an undo group with the begun group's name too: its edits are +/// one undo step there. +#[test] +fn an_undo_group_begun_by_command_opens_in_a_document_added_outside_a_command() { + let mut s = Session::new(); + let rect = json!({"x": 10, "y": 10, "width": 100, "height": 50}); + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + s.execute("edit.undoGroup.begin", &json!({"label": "Job"})).unwrap(); + s.add_document(vectorcraft_doc::Document::new(400.0, 300.0), None); + s.execute("shape.rectangle", &rect).unwrap(); + s.execute("shape.ellipse", &rect).unwrap(); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + assert_eq!(labels(&s), ["Job"]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(objects(&s), 0, "one undo takes back both edits"); +} + /// Between `edit.undoGroup.begin` and `edit.undoGroup.end`, a command that creates a document and /// edits it (a `command.batch`) keeps its edits as an undo step of its own in that document, and the /// edits after it are the group's step. A cancel undoes only those, keeps the document and the From 74e71090260350f6e7be1a4291194b574c8e0f8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:28:43 -0800 Subject: [PATCH 438/533] Scripts: the look for changed path points after each command is charged After a script reads a path's points, each command makes the run look through the changed layers and groups of the document for those paths. That look was not counted toward the script's operation budget, so a loop of commands on a large layer did unbounded work. It now charges the objects it looks at, as the layer scans in layers.rs do. - The look pairs each object with the one of the same id under the same parent now, and lists the document once for a group that moved, so no object is searched for through the whole document. - A document none of whose read paths remain is no longer looked at. The look was added in #9288. --- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/paths.rs | 66 +++++++++++++++++---- crates/engine/src/script/mod.rs | 4 +- crates/engine/src/tests/script_dom_paths.rs | 36 +++++++++++ docs/mcp.md | 3 + 5 files changed, 100 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 10b37a0799..6dedc0acfe 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -424,7 +424,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { /// Notes the changes a command made to the points of the paths the run has read /// ([`paths::see_all_points`]). -pub(super) fn see_points(h: &Host) { +pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> { paths::see_all_points(h) } @@ -1063,7 +1063,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res /// is made active, so bounds it reads take in type that the switch measured again (in the /// document's own composite fonts, [`Session::set_active`]). fn edit_item_with(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { - paths::see_all_points(h); + paths::see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f)); h.dom.editing.set(kept); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index cb23b429b0..4ec845ebc1 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -862,7 +862,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if clipping { return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0))); } - see_all_points(h); + see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; @@ -1376,38 +1376,67 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the /// object model's own, and their points stay valid. A document that is the one the run last looked -/// at is skipped, as are its paths. -pub(super) fn see_all_points(h: &super::Host) { - let keys: Vec<(u64, u64)> = { +/// at is skipped, as are its paths. The look is charged by the objects it looks at. +pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> { + let (keys, looked_at): (Vec<(u64, u64)>, u64) = { let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); + let mut looked_at = 0u64; docs.retain(|uid, before| { let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); if after.is_some_and(|after| Arc::ptr_eq(before, after)) { return true; } + // A document none of whose paths the run still holds points of is not looked at; reading + // points again keeps it as it is then. + if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) { + return false; + } // Editing a path in an Objects on Path group can move the other paths in the group, so // the outermost such group is looked at in place of the path. + // Each node is paired with the node of the same id under the same parent now, so that no + // node is searched for through the whole document. let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { Some(item) => { let group = before .ancestry(item.id) .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))); - node_arc(before, group.unwrap_or(item.id)).into_iter().collect() + let id = group.unwrap_or(item.id); + node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))).into_iter().collect() } - None => before.layers.iter().collect(), + None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at), }; - while let Some(node) = todo.pop() { - if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + // A group that moved to another parent keeps its node, so a node with children that is + // not found under its old parent is looked for among all the nodes now, listed once. + let mut all: Option>> = None; + while let Some((node, mut now)) = todo.pop() { + looked_at += 1; + if now.is_none() + && node.children().is_some() + && let Some(d) = after + { + let all = all.get_or_insert_with(|| { + let mut m = std::collections::HashMap::new(); + let mut stack: Vec<&Arc> = d.layers.iter().collect(); + while let Some(n) = stack.pop() { + m.insert(n.id, n); + stack.extend(n.children().into_iter().flatten()); + } + looked_at += m.len() as u64; + m + }); + now = all.get(&node.id).copied(); + } + if now.is_some_and(|n| Arc::ptr_eq(node, n)) { continue; } if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) { keys.push((*uid, node.id.0)); } if let Some(children) = node.children() { - todo.extend(children); + todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at)); } } if let Some(after) = after { @@ -1417,8 +1446,11 @@ pub(super) fn see_all_points(h: &super::Host) { false } }); - keys + (keys, looked_at) }; + if looked_at > 0 { + h.charge_call(looked_at)?; + } let editing = h.dom.editing.get(); for (uid, id) in keys { let own = || match editing { @@ -1431,6 +1463,20 @@ pub(super) fn see_all_points(h: &super::Host) { }; see_points(h, (uid, id), own); } + Ok(()) +} + +/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the +/// nodes of `after` it looks at. +fn paired<'a>( + before: &'a [Arc], + after: Option<&'a Vec>>, + looked_at: &mut u64, +) -> Vec<(&'a Arc, Option<&'a Arc>)> { + let after = after.map_or(&[][..], Vec::as_slice); + *looked_at += after.len() as u64; + let now: std::collections::HashMap> = after.iter().map(|n| (n.id, n)).collect(); + before.iter().map(|n| (n, now.get(&n.id).copied())).collect() } fn points_at(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0890a75fcd..987e80e4a5 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1513,8 +1513,10 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: dom::after_command(host, before); // Style objects follow only a command that is kept. if crossed.is_ok() { - dom::see_points(host); + // The command stays kept when the look at its changes passes a limit, which ends the run. + let seen = dom::see_points(host); dom::after_kept_command(host); + seen?; } else { session.borrow_mut().script_style_trail = StyleTrail::default(); } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 1e4a123d09..49795b667e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1089,6 +1089,42 @@ fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); } +/// After a run reads a path's points, each command makes the run look through the document's +/// changed layers for paths whose points it read, and that look is charged by the objects it +/// looks at: a loop of commands on a large layer ends at the limit on data passed to commands. +#[test] +fn looking_for_changed_points_after_each_command_is_charged() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut last = NodeId(0); + for i in 0..2000 { + last = rect(&mut s, f64::from(i % 40) * 10.0, f64::from(i / 40) * 5.0, 4.0, 4.0); + } + s.execute("select.none", &json!({})).unwrap(); + let source = format!( + "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor.length);\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["log"], json!([2])); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let e = run(&mut s, &source).map(|r| r.to_string()); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = e.map(|r| panic!("100 commands, each followed by a look at 2,000 objects, ran: {r}")).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + // Once the path whose points the run read is gone, later commands look for nothing. + let source = format!( + "var p = app.activeDocument.pathItems[1]; vc.log(p.pathPoints[0].anchor.length); p.remove();\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let r = run(&mut s, &source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2])); +} + #[test] fn point_edits_are_written_before_the_next_other_member_reads() { let (mut s, a, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..4b63cb5191 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3686,6 +3686,9 @@ through `$`: `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. An exception applies when editing another path in an Objects on Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`. + After each command, the script checks each document that holds a path whose points it still holds: it goes down + through every layer and group the command changed and counts each object directly inside them, changed or not, toward + the script's operation budget. Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point, and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment From 206fc9684f2e41266d3ae851b52105f9f427b21f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:34:29 -0800 Subject: [PATCH 439/533] Tests: remove the fallback size test's folder when the test panics The folder sits in a guard that removes it on drop, so a panic in the write or the search no longer leaves the 41 MiB file in the temporary directory. The normal path still removes it explicitly and fails on an error. --- crates/text/src/fontdb.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 30b95066b5..78ff31af5f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -201,14 +201,21 @@ mod alias_tests { let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; let font = build_file_font(&info, &[glyph]).unwrap(); + // Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } let search = |name: &str, bytes: &[u8]| { - let dir = std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("Pua.ttf"), bytes).unwrap(); - let db = FontDb::with_font_dirs(vec![dir.clone()]); + let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir(&dir.0).unwrap(); + std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.0.clone()]); let found = db.system_fallback(pua); - std::fs::remove_dir_all(&dir).unwrap(); + std::fs::remove_dir_all(&dir.0).unwrap(); found }; assert!(search("small", &font), "a font at its own length is loaded"); From 41ad2f933948bc53676c50ff41d7a641f544ab41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:20:29 -0800 Subject: [PATCH 440/533] Tests: cover the script gate's checked writes and three file-size limits - A checked write to a real path passes a script gate only inside its write folder, and only when every gate chained to it passes too. - Stored plug-ins past the store's byte budget are listed as failed, and a stored file larger than what is left of the budget is skipped. - library.import refuses a file over 512 MB from its size, before it is opened. - An arrowheads file over 64 MB lists no heads and reports why. --- crates/engine/src/file_access.rs | 27 ++++++++++ crates/engine/src/tests/arrowheads.rs | 17 +++++++ crates/engine/src/tests/library.rs | 23 +++++++++ crates/engine/src/tests/plugins.rs | 72 +++++++++++++++++++++++++++ 4 files changed, 139 insertions(+) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 55c06cc130..2c5cb09ee6 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -1572,4 +1572,31 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/x.svg")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } + + /// A checked write to a real path passes a script gate only inside the gate's write folder, and + /// only when every gate chained to it passes the path too. + #[cfg(unix)] + #[test] + fn a_checked_write_to_a_real_path_passes_every_chained_gate() { + let (base, _) = folders("check-real"); + let base = std::fs::canonicalize(&base).unwrap(); + let gate = |dir: &str| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join(dir)), + documents: vec![], + held: vec![], + linked: LinkedFiles::default(), + also: None, + }; + let (inside, outside) = (base.join("out/new.svg"), base.join("outside/new.svg")); + let denied = |p: &Path| Err(format!("Script file access denied: {}", p.display())); + assert_eq!(gate("out").check_real(&inside, Access::Write), Ok(())); + assert_eq!(gate("out").check_real(&outside, Access::Write), denied(&outside)); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&inside)), Ok(()), "the running command's gate passes it"); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&outside)), denied(&outside), "the running command's gate refuses it"); + let chained = gate("out").followed_by(Arc::new(gate("outside"))); + assert_eq!(chained.check_real(&inside, Access::Write), denied(&inside), "the chained gate refuses it"); + assert_eq!(chained.check_real(&outside, Access::Write), denied(&outside), "the first gate refuses it"); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/engine/src/tests/arrowheads.rs b/crates/engine/src/tests/arrowheads.rs index 0cdc3312ff..656f034be7 100644 --- a/crates/engine/src/tests/arrowheads.rs +++ b/crates/engine/src/tests/arrowheads.rs @@ -444,3 +444,20 @@ fn a_group_used_as_the_clipping_path_adds_none_of_its_own_fills() { let b = read.heads[0].path.bounds().unwrap(); assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the square alone: {b:?}"); } + +/// An arrowheads file over the size limit is refused from its size: no heads are listed, and the +/// error says why. +#[test] +fn an_arrowheads_file_over_the_size_limit_lists_no_heads() { + let dir = folder("too-big"); + let file = dir.join(arrowheads::FILE_NAME); + // Sparse: no data blocks are written. + std::fs::File::create(&file).unwrap().set_len(arrowheads::MAX_FILE_BYTES + 1).unwrap(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.to_string_lossy().to_string()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(list["arrowheads"], json!([])); + let error = list["error"].as_str().unwrap_or_default(); + assert!(error.contains(&format!("larger than {} MB", arrowheads::MAX_FILE_BYTES >> 20)), "{list}"); +} diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index cf5fc3c269..1ee23ef47d 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -1299,3 +1299,26 @@ fn a_library_is_exported_to_a_file_and_imported_from_it() { v.libraries.set_dir(Some(folder)); assert_eq!(groups(&mut v), [("Logos".into(), refs(&[("graphic", &g)]))]); } + +/// A library file over 512 MB is refused from its size before it is opened: the file here cannot +/// be opened at all, so only the size check gives this error. +#[cfg(unix)] +#[test] +fn a_library_file_over_the_size_limit_is_refused_before_it_is_read() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("vc-library-too-big-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("big.vclibrary"); + // Sparse: no data blocks are written. + std::fs::File::create(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + // A process that may read any file (root) opens it: nothing to check. + let opened = std::fs::File::open(&path).is_ok(); + let r = (!opened).then(|| session().execute("library.import", &json!({"path": path.to_string_lossy()}))); + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + let _ = std::fs::remove_dir_all(&dir); + let Some(r) = r else { return }; // root opened the file: the size check is not what refuses it + let e = r.err().unwrap_or_else(|| panic!("the file was imported")).to_string(); + assert!(e.contains("the file is larger than 512 MB"), "{e}"); +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 54c599d5fd..42728c7fa6 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2739,6 +2739,78 @@ fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() { assert!(vectorcraft_plugins::registry::remove(id)); } +/// Sets the bytes the stored plug-ins of this thread's stores may read together, and puts the +/// usual budget back when dropped, a failed assertion included. +struct StoreBudget; + +impl StoreBudget { + fn set(bytes: u64) -> Self { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(bytes)); + StoreBudget + } +} + +impl Drop for StoreBudget { + fn drop(&mut self) { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE)); + } +} + +/// The failure listed for each stored file of `folder`, as (file name, reason), sorted. +fn stored_failures_in(folder: &std::path::Path) -> Vec<(String, String)> { + let mut rows: Vec<(String, String)> = crate::store::failed_stored_plugins(folder) + .into_iter() + .map(|(p, why)| (p.file_name().unwrap().to_string_lossy().into_owned(), why)) + .collect(); + rows.sort(); + rows +} + +/// Once the stored plug-ins have used up the bytes a store may read, the stored files after them +/// are listed as failed and are not installed. +#[test] +fn stored_plugins_past_the_store_budget_are_listed_as_failed() { + let (folder, first) = store_with("plugin-budget-used-up", "test.engine.budgetused.a"); + for id in ["test.engine.budgetused.b", "test.engine.budgetused.c"] { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + std::fs::write(folder.0.join(format!("{id}.wasm")), module).unwrap(); + } + let len = std::fs::metadata(&first).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len); + s.attach_plugin_store(folder.0.clone()); + } + let installed: Vec = + ["a", "b", "c"].iter().map(|n| vectorcraft_plugins::registry::get(&format!("test.engine.budgetused.{n}")).is_some()).collect(); + let failed = stored_failures_in(&folder.0); + for n in ["a", "b", "c"] { + vectorcraft_plugins::registry::remove(&format!("test.engine.budgetused.{n}")); + } + assert_eq!(installed, [true, false, false], "only the first file fits the budget"); + let why = format!("the stored plug-ins hold more than {} bytes together", crate::store::MAX_PLUGIN_STORE); + let expected: Vec<(String, String)> = ["b", "c"].iter().map(|n| (format!("test.engine.budgetused.{n}.wasm"), why.clone())).collect(); + assert_eq!(failed, expected); +} + +/// A stored file longer than the bytes the store may still read is skipped and listed as failed. +#[test] +fn a_stored_plugin_larger_than_the_store_budget_is_skipped() { + let id = "test.engine.budgetsmall"; + let (folder, module) = store_with("plugin-budget-small", id); + let len = std::fs::metadata(&module).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len - 1); + s.attach_plugin_store(folder.0.clone()); + } + let installed = vectorcraft_plugins::registry::remove(id); + assert!(!installed, "a file over the budget is not read"); + let failed = stored_failures_in(&folder.0); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].1.contains(&format!("larger than {} bytes", len - 1)), "{failed:?}"); +} + /// A stored file replaced after its module loaded, by one of the same length with the same modified /// time, is skipped: its content no longer holds the module. That holds for a file modified moments /// ago and for one modified an hour ago. From 5292a3630c482ba4d3b169e44ebf695f91c20562 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:45:17 -0800 Subject: [PATCH 441/533] EPS import: test embedded Type 1 lexing and CIDFont metrics, glyph directories and data limit Four tests cover embedded-font code paths that no test reached: - The Type 1 encrypted-part lexer steps over strings with escaped and nested parentheses, nested procedures holding comments and strings, comments, hexadecimal strings and dictionaries, and does not take CharStrings written inside a string, a procedure or a comment for the font's. - A CIDFont's Metrics entries (a number, [sbx wx] and [sbx sby wx wy]) replace the glyph widths; an entry of another length keeps them. - A GlyphDirectory array or dictionary draws the same glyphs as the binary data section. - A StartData count over 64 MiB is refused before it is read. --- crates/eps/src/import/tests_cid.rs | 113 +++++++++++++++++++++++---- crates/eps/src/import/tests_type1.rs | 36 ++++++++- 2 files changed, 132 insertions(+), 17 deletions(-) diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index b44a5410ee..e79dc37dd2 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -50,10 +50,7 @@ fn hex(b: &[u8]) -> String { /// triangle (500 across, 400 high) 500 wide drawn by a subroutine, encrypted (dictionary 1, /// `lenIV` 4). The binary data section, written in hexadecimal when `hex_data`. fn cid_font(hex_data: bool) -> Vec { - let empty = cs(&[(&[0, 500], 13), (&[], 14)]); - let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); - let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)])); - let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)])); + let [empty, square, triangle] = cid_glyphs(); // The offset table: FDArray index (1 byte) and offset (2 bytes) of CIDs 0 to 2 and the end. let table = 4 * 3; let offsets = [table, table + empty.len(), table + empty.len() + square.len(), table + empty.len() + square.len() + triangle.len()]; @@ -65,16 +62,7 @@ fn cid_font(hex_data: bool) -> Vec { data.extend(empty); data.extend(square); data.extend(triangle); - let mut out = format!( - "/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\ - /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\ - /FontBBox [0 0 1000 1000] def\n/FDArray [\n\ - 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\ - 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\ - ] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n", - hex(&subr) - ) - .into_bytes(); + let mut out = cid_font_head().into_bytes(); if hex_data { out.extend(format!("(Hex) {} StartData\n{}>\n", data.len(), hex(&data)).into_bytes()); } else { @@ -85,6 +73,46 @@ fn cid_font(hex_data: bool) -> Vec { out } +/// The charstrings of [`cid_font`]'s CIDs 0 to 2, as its data holds them. +fn cid_glyphs() -> [Vec; 3] { + let empty = cs(&[(&[0, 500], 13), (&[], 14)]); + let square = cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)]); + let triangle = encrypt(&cs(&[(&[0, 500], 13), (&[0], 10), (&[], 14)])); + [empty, square, triangle] +} + +/// [`cid_font`] up to its glyph data: the CIDFont dictionary, its FDArray and its offset table's +/// layout. +fn cid_font_head() -> String { + let subr = encrypt(&cs(&[(&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 11)])); + format!( + "/CIDInit /ProcSet findresource begin\n20 dict begin\n/CIDFontName /TestCID def /CIDFontType 0 def\n\ + /CIDSystemInfo 3 dict dup begin /Registry (Test) def /Ordering (Shapes) def /Supplement 0 def end def\n\ + /FontBBox [0 0 1000 1000] def\n/FDArray [\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV -1 def end def currentdict end\n\ + 4 dict begin /FontMatrix [0.001 0 0 0.001 0 0] def /Private 2 dict dup begin /lenIV 4 def /Subrs [<{}>] def end def currentdict end\n\ + ] def\n/CIDMapOffset 0 def /FDBytes 1 def /GDBytes 2 def /CIDCount 3 def\n", + hex(&subr) + ) +} + +/// [`cid_font`] with its glyphs in a `GlyphDirectory` (each entry the FDArray index byte and the +/// charstring: PLRM 3rd ed., §5.11.3) instead of a binary data section, as an array +/// indexed by CID or as a dictionary keyed by CID, defined with `defineresource`. Its own matrix +/// is the identity, as its FDArray matrices give glyph space. +fn cid_font_in_a_directory(dict: bool) -> String { + let entries: Vec = cid_glyphs().iter().zip([0u8, 0, 1]).map(|(g, fd)| format!("<{:02x}{}>", fd, hex(g))).collect(); + let directory = if dict { + format!("<< {} >>", entries.iter().enumerate().map(|(cid, e)| format!("{cid} {e}")).collect::>().join(" ")) + } else { + format!("[ {} ]", entries.join(" ")) + }; + format!( + "{}/FontMatrix [1 0 0 1 0 0] def /GlyphDirectory {directory} def\nCIDFontName currentdict end /CIDFont defineresource pop end\n", + cid_font_head() + ) +} + /// CMap `/Test-H`: one-byte codes 00–7F and two-byte codes 8000–FFFF; A and B are CIDs 1 and 2, /// <8001> CID 2, and codes 00–1F without a character take CID 1 as their notdef. const CMAP: &str = "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\ @@ -121,6 +149,63 @@ fn type0_cidfonts_draw_their_charstrings_through_the_cmap() { } } +/// `font` and the CMap, then `body`, as an EPS file. +fn program_with(font: &str, body: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n{font}{CMAP}{body}\nshowpage\n%%EOF\n").into_bytes() +} + +/// Widths in a CIDFont's `Metrics` dictionary replace its glyphs' own (PLRM 3rd ed., §5.9.2): a +/// number is the width, a 2-element entry `[sbx wx]` gives its second element and a 4-element +/// entry `[sbx sby wx wy]` its third. An entry of another length keeps the glyph's width. +#[test] +fn cidfont_metrics_replace_the_glyph_widths() { + let with = |metrics: &str| { + String::from_utf8(cid_font(true)).unwrap().replace("/CIDCount 3 def", &format!("/CIDCount 3 def /Metrics << {metrics} >> def")) + }; + let width = |font: &str, s: &str, w: f64| check(&format!("{font}{CMAP} /TestFont 50 selectfont {s} stringwidth pop {w} sub abs 0.01 lt")); + let font = with("0 250 1 [0 700] 2 [0 0 800 0]"); + // At 50 points an em: 700 units for A (CID 1), 800 for B (CID 2), 250 for CID 0. + width(&font, "(A)", 35.0); + width(&font, "(B)", 40.0); + width(&font, "<9041>", 12.5); + // A 3-element entry keeps the square's 600 units. + width(&with("1 [0 700 0]"), "(A)", 30.0); + // The triangle is drawn where the square's new width ends, 700 units on, not 600. + let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show")).unwrap(); + let p = paths(&r); + assert_eq!(p.len(), 2, "{p:?} {:?}", r.warnings); + assert!((p[1].x0 - 45.0).abs() < 0.01 && (p[1].width() - 25.0).abs() < 0.01, "{p:?}"); +} + +/// A Type 0 CIDFont whose glyphs are in a `GlyphDirectory`, an array or a dictionary, draws the +/// same glyphs as the same font with its glyphs in a binary data section. +#[test] +fn glyph_directories_draw_the_glyphs_a_data_section_does() { + let show = "/TestFont 50 selectfont 10 20 moveto (AB) show"; + let want = paths(&import(&program(false, show)).unwrap()); + assert_eq!(want.len(), 2, "{want:?}"); + for dict in [false, true] { + let r = import(&program_with(&cid_font_in_a_directory(dict), show)).unwrap(); + assert!(r.warnings.is_empty(), "{dict}: {:?}", r.warnings); + let p = paths(&r); + assert_eq!(p.len(), 2, "{dict}: {p:?}"); + assert!(p.iter().zip(&want).all(|(a, b)| super::tests::near(*a, *b)), "{dict}: {p:?} {want:?}"); + } +} + +/// A binary data section longer than a font's data may be (64 MiB) is refused before it is read. +#[test] +fn start_data_over_the_glyph_data_limit_is_refused() { + let font = String::from_utf8(cid_font(true)).unwrap(); + let font = format!("{}(Binary) 70000000 StartData abc\n", &font[..font.find("(Hex)").unwrap()]); + let r = import(&program_with(&font, "/TestFont 50 selectfont 10 20 moveto (AB) show")); + let said = match &r { + Ok(r) => r.warnings.join("\n"), + Err(e) => e.clone(), + }; + assert!(said.contains("a font's data is too large"), "{said}"); +} + /// Codes take as many bytes as their codespace range says; codes without a character take their /// notdef mapping's CID, else CID 0 (PLRM 3rd ed., §5.11.5). #[test] diff --git a/crates/eps/src/import/tests_type1.rs b/crates/eps/src/import/tests_type1.rs index 21ff20abec..6221da60f3 100644 --- a/crates/eps/src/import/tests_type1.rs +++ b/crates/eps/src/import/tests_type1.rs @@ -47,6 +47,11 @@ fn font(encoding: &str, hex: bool) -> Vec { /// [`font`] with subroutines `subrs` and, when given, charstring `a` for A. fn font_with(encoding: &str, hex: bool, subrs: &[Vec], a: Option>) -> Vec { + font_private(encoding, hex, subrs, a, b"") +} + +/// [`font_with`] with `extra` in the encrypted part, after `Subrs` and before `CharStrings`. +fn font_private(encoding: &str, hex: bool, subrs: &[Vec], a: Option>, extra: &[u8]) -> Vec { let square = a.unwrap_or_else(|| cs(&[(&[0, 600], 13), (&[100, 0], 21), (&[400, 0], 5), (&[0, 500], 5), (&[-400, 0], 5), (&[], 9), (&[], 14)])); let triangle = cs(&[(&[0, 500], 13), (&[0, 0], 21), (&[500, 0], 5), (&[-250, 400], 5), (&[], 9), (&[], 14)]); let notdef = cs(&[(&[0, 250], 13), (&[], 14)]); @@ -61,7 +66,9 @@ fn font_with(encoding: &str, hex: bool, subrs: &[Vec], a: Option>) - private.extend(e); private.extend(b" NP\n"); } - private.extend(b"readonly def\n2 index /CharStrings 4 dict dup begin\n"); + private.extend(b"readonly def\n"); + private.extend(extra); + private.extend(b"2 index /CharStrings 4 dict dup begin\n"); for (name, glyph) in [(".notdef", ¬def), ("A", &square), ("B", &triangle), ("g1", &triangle)] { let e = encrypt(glyph, 4330); private.extend(format!("/{name} {} RD ", e.len()).into_bytes()); @@ -163,8 +170,13 @@ fn laid_out(t: &TextObject) -> Vec<(vectorcraft_geom::Rect, f64, bool)> { /// font's own advances (no tracking makes up for a stand-in's), not in the fallback font. #[test] fn embedded_type1_type_draws_with_the_files_glyphs() { - let r = program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show"); - let t = &texts(&r)[0]; + draws_the_files_glyphs(&program(OWN, false, "/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show")); +} + +/// "AB" in `/TestOne` drawn with the file's glyphs: the square and the triangle, B starting where +/// A's 600 units end. +fn draws_the_files_glyphs(r: &crate::Imported) { + let t = &texts(r)[0]; assert!(t.file_fonts.is_some(), "{:?}", r.warnings); let glyphs = laid_out(t); assert_eq!(glyphs.len(), 2); @@ -178,6 +190,24 @@ fn embedded_type1_type_draws_with_the_files_glyphs() { assert!(t.runs.iter().all(|r| r.style.tracking == 0.0), "{:?}", t.runs); } +/// The encrypted part's other definitions are stepped over whole when looking for its +/// `CharStrings`: strings with escaped and nested parentheses, nested procedures holding comments +/// and strings, comments, hexadecimal strings and dictionaries. `CharStrings` written inside a +/// string or a comment, with a charstring of its own, isn't taken for the font's. +#[test] +fn the_encrypted_parts_other_definitions_are_stepped_over() { + let extra: &[u8] = b"/OtherSubrs [ { (a\\) } (b) {c) { % } ( {\n} } ] ND\n\ + /p { {} (}) /CharStrings 2 dict dup begin /A 1 RD x ND end } def\n\ + /x <0A 0b\n 1F> def\n\ + /d << /k (() /CharStrings 2 dict) /m << >> >> def\n\ + % /CharStrings 2 dict dup begin /A 1 RD x ND end\n\ + (/CharStrings 2 \\( dict dup begin /A 1 RD x ND end) pop\n"; + let head = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); + let body = b"/TestOne findfont 50 scalefont setfont 10 20 moveto (AB) show\nshowpage\n%%EOF\n".to_vec(); + let r = import(&[head, font_private(OWN, false, &[], None, extra), body].concat()).unwrap(); + draws_the_files_glyphs(&r); +} + /// A family whose regular style the file carries but whose bold it only names: the regular is /// drawn in the kept font and the bold in the fallback font, and the warning says both. #[test] From 2bf98c9acd57fb3042defbfe271fa5af866537f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:49:33 -0800 Subject: [PATCH 442/533] Gradient: an unfinished field value stays with the stop, point or gradient it was typed for The Gradient panel's number fields kept an unfinished value when the panel switched to another stop, midpoint, freeform point or object with the same value. With stop 2 selected, typing `20+` into Opacity and then selecting stop 3 left `20+` in the field, and typing `1` with Enter gave stop 3 21% instead of 1%. Location, Angle, Aspect Ratio, Repeats and a freeform point's Opacity and Spread did the same. Each of these fields now passes what it edits to `NumberField::edit_target`: the gradient behind the active proxy (`Session::gradient_owner`), the selected objects and symbol part, and the selected stop, midpoint or point. When that key changes, the field drops the unfinished text and shows the new target's value. `StopOwner` derives `Eq` and `Hash` so it can be part of the key. --- crates/engine/src/cmd/gradient.rs | 4 +- crates/ui-egui/src/panels/gradient.rs | 32 +++++- crates/ui-egui/src/panels/gradient/tests.rs | 116 ++++++++++++++++++++ 3 files changed, 146 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 01e0a5a732..2a32f3b7e6 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -88,8 +88,8 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art, /// picking a part of the instance, toggling the proxy, picking another item or choosing such a /// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint -/// diamond by it as well ([`Session::gradient_owner`]). -#[derive(Clone, Copy, Debug, PartialEq)] +/// diamond and its fields' unfinished values by it as well ([`Session::gradient_owner`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct StopOwner { /// The active document's uid, which stays the same when its tab moves. doc: Option, diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index c75d2f7c80..5feb4b231a 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -291,6 +291,15 @@ fn selected_mid(app: &VectorcraftApp, stops: usize) -> Option { (app.session.selected_stop().is_none() && i + 1 < stops && owner == app.session.gradient_owner()).then_some(i) } +/// What the panel's number fields edit: the gradient behind the active proxy +/// ([`vectorcraft_engine::Session::gradient_owner`]) on the selected objects and the selected part of a symbol +/// instance. Each field passes it to [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value +/// left unfinished in the field is dropped when another one is selected. +fn field_target(app: &VectorcraftApp) -> egui::IdSalt { + let selection = app.session.active().map(|st| (&st.selection.objects, st.selection.symbol_part.as_ref().map(|p| (p.instance, &p.path)))); + egui::IdSalt::new((app.session.gradient_owner(), selection)) +} + /// A stored fraction as the percent a field shows, without the `f32` noise (`0.3` is `30`, not `30.000001`). fn percent(v: f32) -> f64 { (f64::from(v) * 1e6).round() / 1e4 @@ -430,6 +439,7 @@ fn angle_field(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, placed: .range(-180.0..=180.0) .presets(&presets) .enabled(placed) + .edit_target(field_target(app)) .show(ui); apply_number(app, &field.edit, |app, a, phase| edit(app, json!({"angle": a}), phase)); } @@ -446,8 +456,13 @@ fn aspect_field(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, placed let mirror = g.geom.map_or(1.0, |x| if x.is_mirrored() && kind == GradientKind::Conic { -1.0 } else { 1.0 }); let asp = g.geom.map_or(100.0, |x| (x.aspect.abs() * 1000.0).round() / 10.0); let presets = number_presets(&ASPECT_PRESETS, "%"); - let field = - NumberField::new(tl!("Aspect Ratio"), Bind::given(Some(asp))).unit("%").range(0.5..=f64::MAX).presets(&presets).enabled(radial).show(ui); + let field = NumberField::new(tl!("Aspect Ratio"), Bind::given(Some(asp))) + .unit("%") + .range(0.5..=f64::MAX) + .presets(&presets) + .enabled(radial) + .edit_target(field_target(app)) + .show(ui); apply_number(app, &field.edit, |app, a, phase| edit(app, json!({"aspect": a * mirror}), phase)); }); } @@ -492,6 +507,7 @@ fn spread_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr .commit_decimals(0) .presets(&presets) .enabled(is_grad && !current.is_pad()) + .edit_target(field_target(app)) .show(ui); apply_number(app, &repeats.edit, |app, r, phase| edit(app, json!({"repeats": r.round()}), phase)); }); @@ -596,11 +612,12 @@ fn freeform_rows(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) { Text::new(p.color.to_hex().to_uppercase()).shade(Shade::Muted).show(ui); } }); + let target = (field_target(app), sel); Row::new().show(ui, |ui, _| { for (label, key, value) in [(tl!("Opacity"), "opacity", point.map(|p| p.opacity)), (tl!("Spread"), "spread", point.map(|p| p.spread))] { // Blank while no point is selected. let shown = value.map(|v| (f64::from(v) * 1000.0).round() / 10.0); - let field = NumberField::new(label, Bind::given(shown)).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); + let field = NumberField::new(label, Bind::given(shown)).range(0.0..=100.0).unit("%").enabled(sel.is_some()).edit_target(target).show(ui); if let Some(Some(v)) = field.edit.events.committed() && let Some(i) = sel { @@ -696,12 +713,18 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } }); } + let target = field_target(app); // In a narrow panel the row wraps; each caption stays on the line of its field. Row::new().wrap(true).show(ui, |ui, _| { Row::new().show(ui, |ui, _| { Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); - let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); + let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))) + .range(0.0..=100.0) + .unit("%") + .enabled(sel.is_some()) + .edit_target((target, sel)) + .show(ui); apply_number(app, &opacity.edit, |app, v, phase| { let Some(i) = sel else { return }; let mut v2 = stops.clone(); @@ -722,6 +745,7 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo .range(0.0..=100.0) .unit("%") .enabled(sel.is_some() || mid.is_some()) + .edit_target((target, sel, mid)) .show(ui); apply_number(app, &location.edit, |app, v, phase| { let v = (v / 100.0) as f32; diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 00c56f82a2..3ad8f26f0b 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -192,6 +192,22 @@ impl Rig { self.fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text(text).key(Key::Enter, Modifiers::NONE).settle(); } + /// The text the field named `label` shows. + fn text(&self, label: &str) -> Option { + self.fixture.tree().value_of(self.target(label).node).map(str::to_owned) + } + + /// Type `text` over the text of the field named `label` without committing it. + fn type_unfinished(&mut self, label: &str, text: &str) { + let field = self.target(label); + self.fixture.click(&field).key(Key::A, Modifiers::COMMAND).type_text(text).settle(); + } + + /// Type `text` into the focused field and commit it with Enter. + fn finish(&mut self, text: &str) { + self.fixture.type_text(text).key(Key::Enter, Modifiers::NONE).settle(); + } + /// Drag from `from` and release at `to`. fn drag(&mut self, from: Pos2, to: Pos2) { self.fixture.drag_at(from, to - from).settle(); @@ -280,6 +296,106 @@ fn a_selected_stop_and_a_picked_diamond_stay_selected_when_the_document_tab_move assert_eq!(rig.number("Location"), Some(30.0), "Location still shows the midpoint"); } +/// An unfinished Opacity or Location value belongs to the stop or midpoint it was typed for: after another stop, a +/// midpoint or another object's stop is selected, the field shows the new target's value, even where it is the same, +/// and further typing starts a new value instead of finishing the old expression. +#[test] +fn an_unfinished_stop_value_does_not_reach_another_stop() { + let stops = json!([ + {"offset": 0, "color": "#ffffff"}, + {"offset": 0.5, "color": "#808080"}, + {"offset": 0.5, "color": "#404040"}, + {"offset": 1, "color": "#000000"} + ]); + let mut app = app(json!({"gradient": {"stops": stops.clone()}})); + let a = app.session.active().unwrap().selection.objects[0]; + let b = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + let stops_of = |rig: &Rig, id: NodeId| match rig.app().session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + Paint::Gradient(g) => g.gradient.stops.iter().map(|s| (s.offset, s.opacity)).collect::>(), + p => panic!("expected a gradient fill, got {p:?}"), + }; + let mut rig = Rig::new(app); + + rig.type_unfinished("Opacity", "20+"); + rig.app().run("gradient.selectStop", json!({"index": 2})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Opacity").as_deref(), Some("100 %"), "Opacity shows the other stop's value"); + rig.finish("1"); + let opacities: Vec = stops_of(&rig, a).into_iter().map(|(_, o)| o).collect(); + assert_eq!(opacities, [1.0, 1.0, 0.01, 1.0], "the typing gives the other stop 1%, not 20+1"); + + rig.type_unfinished("Location", "20+"); + rig.app().run("gradient.selectStop", json!({"index": 1})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Location").as_deref(), Some("50 %"), "Location shows the other stop's location"); + rig.finish("1"); + let offsets: Vec = stops_of(&rig, a).into_iter().map(|(o, _)| o).collect(); + assert_eq!(offsets, [0.0, 0.01, 0.5, 1.0], "the other stop moves to 1%, not to 21%"); + + // Two midpoints, both at 50%. + let pick_mid = |rig: &Rig, i: usize| { + let mut app = rig.app(); + app.run("gradient.selectStop", json!({"index": null})).unwrap(); + app.ui.gradient_panel.mid_selected = Some((i, app.session.gradient_owner())); + }; + pick_mid(&rig, 0); + rig.fixture.settle(); + rig.type_unfinished("Location", "20+"); + pick_mid(&rig, 2); + rig.fixture.settle(); + assert_eq!(rig.text("Location").as_deref(), Some("50 %"), "Location shows the other midpoint"); + + // The same stop of another object's gradient. + rig.app().run("gradient.selectStop", json!({"index": 0})).unwrap(); + rig.fixture.settle(); + rig.type_unfinished("Opacity", "20+"); + rig.app().run("select.set", json!({"ids": [b]})).unwrap(); + rig.app().run("gradient.selectStop", json!({"index": 0})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Opacity").as_deref(), Some("100 %"), "Opacity shows the other object's stop"); + rig.finish("1"); + let b = NodeId(b.as_u64().unwrap()); + assert_eq!((stops_of(&rig, a)[0].1, stops_of(&rig, b)[0].1), (1.0, 0.01), "the other object's stop takes 1%"); +} + +/// An unfinished value in a freeform point's Opacity or Spread field does not reach the next point selected, and one +/// in Angle does not reach another object's gradient. +#[test] +fn an_unfinished_point_or_angle_value_does_not_reach_a_new_target() { + let mut app = app(json!({"gradient": {}})); + let a = app.session.active().unwrap().selection.objects[0]; + let b = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + let mut rig = Rig::new(app); + + let angle = rig.text("Angle"); + rig.type_unfinished("Angle", "20+"); + rig.app().run("select.set", json!({"ids": [b]})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Angle"), angle, "Angle shows the other object's angle"); + + rig.app().run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); + let points = + |rig: &Rig| fill(&rig.app()).freeform.map(|f| f.points.iter().map(|p| (p.opacity, p.spread)).collect::>()).unwrap_or_default(); + let before = points(&rig); + for (n, label) in ["Opacity", "Spread"].into_iter().enumerate() { + rig.app().run("paint.freeform.selectPoint", json!({"index": 0})).unwrap(); + rig.fixture.settle(); + rig.type_unfinished(label, "20+"); + rig.app().run("paint.freeform.selectPoint", json!({"index": 1})).unwrap(); + rig.fixture.settle(); + assert!(!rig.text(label).is_some_and(|t| t.contains('+')), "{label} shows the other point's value, not {:?}", rig.text(label)); + rig.finish("1"); + let now = points(&rig); + let value = |p: (f32, f32)| if n == 0 { p.0 } else { p.1 }; + assert_eq!((value(now[0]), value(now[1])), (value(before[0]), 0.01), "{label}: the other point takes 1%, not 20+1"); + } +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored (the field's value times the mirror's sign). #[test] From b7db67145546d7ee70a4adbcca633c0bf607bf61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:50:50 -0800 Subject: [PATCH 443/533] Tests: cover the theme picker's masks and blends, and pie legend contrast past the wedge limit - recolor.pickTheme with an enabled clipping opacity mask: white mask art over one of three squares lets only that square's color through, black mask art hides all three, and inside a curved clip group the masked art shows only where the mask and the clipping path both let it. - recolor.pickTheme with a blend: a marquee over a middle step returns the colors of both end objects, also when a clip group around the blend hides the end objects. - Pie legend labels past the wedge measurement limit take the contrast most of their series' wedges show (2 of 3 dark gives dark, 1 of 3 gives light). The limit is read through a thread-local in tests, as the Extrude & Bevel face limit is; the shipped limit is unchanged. --- crates/engine/src/cmd/graph.rs | 4 +- crates/engine/src/cmd/graph/series.rs | 26 +++++++++- crates/engine/src/cmd/graph/tests.rs | 54 +++++++++++++++++++++ crates/engine/src/tests/recolor.rs | 70 +++++++++++++++++++++++++++ 4 files changed, 150 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f348a97f3c..5096e146ac 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -47,8 +47,6 @@ pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; #[cfg(test)] use generate::generate; -#[cfg(test)] -use series::default_series_color; pub(crate) use series::{ LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, @@ -57,6 +55,8 @@ pub(crate) use series::{ is_graph_line, is_series_group, label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, wedge_shades, }; +#[cfg(test)] +use series::{WEDGE_BUDGET, default_series_color, legend_on_dark}; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 7371961c20..550f72c478 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1113,7 +1113,7 @@ fn redrawn_on_dark(n: &Node, g: &GraphSpec) -> Option> { /// on, which lies inside its wedge: the wedge holding it of the series the label names (the nearest one when none holds /// it), or of any series when the label names none. When the wedges of the series a label names are all dark or all /// light, the label's place does not matter. -fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap { +pub(super) fn legend_on_dark(n: &Node, g: &GraphSpec) -> HashMap { wedge_contrast(&legend_labels(n), &pie_wedges(n), g) } @@ -1134,6 +1134,28 @@ fn label_anchor(text: &vectorcraft_doc::TextObject, name: &str, g: &GraphSpec, l text.xf * vectorcraft_geom::Point::new(0.0, middle - ls * 0.35) } +/// Most wedges [`wedge_contrast`] measures for one pie's legend labels together. +const WEDGE_MEASUREMENTS: usize = 1 << 20; + +#[cfg(test)] +thread_local! { + /// The limit [`wedge_budget`] gives on this thread: [`WEDGE_MEASUREMENTS`] unless a test sets a lower one, so that a + /// test of the limit uses a small pie. + pub(super) static WEDGE_BUDGET: std::cell::Cell = const { std::cell::Cell::new(WEDGE_MEASUREMENTS) }; +} + +/// Most wedges [`wedge_contrast`] measures: [`WEDGE_MEASUREMENTS`]. +#[cfg(not(test))] +fn wedge_budget() -> usize { + WEDGE_MEASUREMENTS +} + +/// Most wedges [`wedge_contrast`] measures: [`WEDGE_MEASUREMENTS`], or the lower limit a test set in [`WEDGE_BUDGET`]. +#[cfg(test)] +fn wedge_budget() -> usize { + WEDGE_BUDGET.with(std::cell::Cell::get) +} + /// [`legend_on_dark`] for legend labels `legend` of a pie of spec `g` with wedges `wedges`. fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap { use vectorcraft_geom::kurbo::ParamCurveNearest; @@ -1164,7 +1186,7 @@ fn wedge_contrast(legend: &[&Node], wedges: &[Wedge], g: &GraphSpec) -> HashMap< let ls = label_size(&g.label_styles, Role::Legend); // The search for the nearest wedge looks at this many wedges in all; past it, a label takes the contrast most of the // wedges of its series show. - let mut budget: usize = 1 << 20; + let mut budget = wedge_budget(); for t in legend { let NodeKind::Text(text) = &t.kind else { continue }; let id = t.id; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b41415ef02..856ac5919e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -10285,6 +10285,60 @@ fn a_color_mode_change_keeps_the_default_legend_fill_of_other_graphs() { } } +/// Past the limit on wedge measurements, a legend label of a pie with Legends in Wedges takes the contrast most of the +/// wedges of its series show: dark when 2 of its 3 wedges are dark, light when 1 of its 3 is. +#[test] +fn past_the_wedge_limit_a_legend_label_takes_the_contrast_most_of_its_wedges_show() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a,b\nP1,1,2\nP2,1,2\nP3,1,2"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + // The first two wedges of series a are dark and the third light; only the first wedge of series b is dark. + let wedge_ids = |s: &Session, index: u32| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let mut ids = vec![]; + series(&n, index).walk(&mut |m| { + if matches!(m.kind, NodeKind::Path { .. }) { + ids.push(m.id); + } + }); + ids + }; + let (a, b) = (wedge_ids(&s, 0), wedge_ids(&s, 1)); + assert_eq!((a.len(), b.len()), (3, 3), "one wedge of each series in each of the 3 pies"); + s.edit("shade", |d, _| { + for (ids, darks) in [(&a, 2), (&b, 1)] { + for (i, w) in ids.iter().enumerate() { + let color = if i < darks { vectorcraft_color::Color::BLACK } else { vectorcraft_color::Color::WHITE }; + d.node_mut(*w).unwrap().appearance.set_fill(Paint::solid(color)); + } + } + Ok(()) + }) + .unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = spec(&s, id); + let label = |text: &str| -> Vec { + group(&n, "Legend") + .children() + .unwrap() + .iter() + .filter(|c| matches!(&c.kind, NodeKind::Text(t) if t.plain_text() == text)) + .map(|c| c.id) + .collect() + }; + let (label_a, label_b) = (label("a"), label("b")); + assert!(!label_a.is_empty() && !label_b.is_empty(), "the legend labels a and b"); + let measured = super::legend_on_dark(&n, &g); + super::WEDGE_BUDGET.with(|b| b.set(0)); + let past = super::legend_on_dark(&n, &g); + super::WEDGE_BUDGET.with(|b| b.set(1 << 20)); + let on_dark = |map: &std::collections::HashMap, ids: &[NodeId]| -> Vec { ids.iter().map(|i| map[i]).collect() }; + assert!(on_dark(&measured, &label_a).contains(&false), "measured: a label of a sits on its light wedge: {measured:?}"); + assert!(on_dark(&past, &label_a).iter().all(|d| *d), "past the limit: 2 of 3 dark gives dark: {past:?}"); + assert!(on_dark(&past, &label_b).iter().all(|d| !*d), "past the limit: 1 of 3 dark gives light: {past:?}"); +} + #[test] fn labels_are_told_apart_by_where_they_come_not_by_their_text() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 278e7e0f3d..6cc6636fa5 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1831,6 +1831,76 @@ fn theme_picker_leaves_out_art_a_curved_clipping_path_hides() { assert_eq!(pick_theme(&mut s, all), ["rgb 255 0 0"], "the corner square is hidden"); } +/// A filled rectangle without a stroke. +fn filled(s: &mut Session, [x, y, w, h]: [f64; 4], fill: &str) -> NodeId { + let id = NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id +} + +/// An enabled opacity mask that clips shows the art only where its mask art is lighter than black: white mask art over +/// the red square of three lets red alone through, and black mask art hides all three. Inside a clip group, the masked +/// art shows only where the mask and the clipping path both let it. +#[test] +fn theme_picker_reads_only_what_a_clipping_opacity_mask_shows() { + let all = json!({"picks": [{"rect": [-10, -10, 120, 110]}]}); + // A red, a blue and a green square under one mask. + let masked = |[red, blue, green]: [[f64; 4]; 3], mask_art: [f64; 4], mask_fill: &str| { + let mut s = session(); + let red = filled(&mut s, red, "#ff0000"); + let blue = filled(&mut s, blue, "#0000ff"); + let green = filled(&mut s, green, "#00ff00"); + let mask = filled(&mut s, mask_art, mask_fill); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0, green.0, mask.0]})); + let g = NodeId(run(&mut s, "transparency.makeOpacityMask", json!({"clip": true}))["id"].as_u64().unwrap()); + (s, g) + }; + // Red runs from x 10 to 25, blue from 40 to 55 and green from 70 to 85; the mask art covers red alone. + let in_a_row = [[10.0, 10.0, 15.0, 15.0], [40.0, 10.0, 15.0, 15.0], [70.0, 10.0, 15.0, 15.0]]; + let over_red = [5.0, 5.0, 25.0, 25.0]; + let (mut s, _) = masked(in_a_row, over_red, "#ffffff"); + assert_eq!(pick_theme(&mut s, all.clone()), ["rgb 255 0 0"], "white mask art over the red square"); + let (mut s, _) = masked(in_a_row, over_red, "#000000"); + assert!(pick_theme(&mut s, all.clone()).is_empty(), "black mask art hides every square"); + // Red sits in the top left corner of a 100 × 100 ellipse's box, outside the ellipse; blue and green are inside it. + // The mask art covers red and blue, and the ellipse clips the masked group. + let around_an_ellipse = [[0.0, 0.0, 8.0, 8.0], [40.0, 40.0, 15.0, 15.0], [70.0, 40.0, 15.0, 15.0]]; + let (mut s, g) = masked(around_an_ellipse, [-5.0, -5.0, 65.0, 65.0], "#ffffff"); + let e = NodeId(run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 100, "height": 100}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0, e.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + assert_eq!(pick_theme(&mut s, all), ["rgb 0 0 255"], "only blue shows through both"); +} + +/// A blend a marquee touches is read whole: a marquee over a middle step alone takes the colors of both end objects, +/// also when a clip group around the blend hides the end objects. +#[test] +fn theme_picker_reads_a_blend_whole() { + let mut s = session(); + let circle = |s: &mut Session, x: f64, fill: &str| { + let id = NodeId(run(s, "shape.ellipse", json!({"x": x, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()); + run(s, "paint.setFill", json!({"ids": [id.0], "color": fill})); + run(s, "paint.setStroke", json!({"ids": [id.0], "none": true})); + id + }; + // The end objects are centered on x 20 and 260; the 3 steps between them on x 80, 140 and 200. + let (red, blue) = (circle(&mut s, 10.0, "#ff0000"), circle(&mut s, 250.0, "#0000ff")); + run(&mut s, "select.set", json!({"ids": [red.0, blue.0]})); + let blend = NodeId(run(&mut s, "object.blend.make", json!({"steps": 3}))["id"].as_u64().unwrap()); + let middle = json!({"picks": [{"rect": [135, 15, 145, 25]}]}); + let mut got = pick_theme(&mut s, middle.clone()); + got.sort(); + assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "the middle step gives both end colors"); + // A clipping path over the middle step alone. + let clip = filled(&mut s, [120.0, 5.0, 40.0, 30.0], "#00ff00"); + run(&mut s, "select.set", json!({"ids": [blend.0, clip.0]})); + run(&mut s, "object.clippingMask.make", json!({})); + let mut got = pick_theme(&mut s, middle); + got.sort(); + assert_eq!(got, ["rgb 0 0 255", "rgb 255 0 0"], "the clip group around the blend leaves the end objects in"); +} + /// In isolation mode a click and a marquee read only the isolated art. #[test] fn theme_picker_reads_only_the_isolated_art() { From 0d8b27ced001de4536d59c61a808193737094b5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:53:07 -0800 Subject: [PATCH 444/533] Tests: table_bytes test requires the reserved size; keep From<&[Anchor]> The anchor table test now asserts that table_bytes equals the reserved capacity of both tables, with spare capacity added to each, so a count by length fails. The From<&[Anchor]> impl is restored so the change stays test-only. --- crates/geom/src/anchors.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 78cfe5509a..186c4b53c0 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -554,6 +554,12 @@ impl From> for Anchors { } } +impl From<&[Anchor]> for Anchors { + fn from(s: &[Anchor]) -> Self { + Self::from(s.to_vec()) + } +} + impl From<[Anchor; N]> for Anchors { fn from(s: [Anchor; N]) -> Self { Self::from(Vec::from(s)) @@ -887,22 +893,26 @@ mod tests { assert_eq!(before.pairs_not_shared(&moved).count(), 10_000); } - /// The table bytes take in both tables: at least what the chunk table and the running totals - /// hold, and at most what they have reserved. A short list has no running totals; a list split - /// unevenly by an insert has both. + /// The table bytes are what the chunk table and the running totals have reserved, which is at + /// least what they hold. A short list has no running totals; a list split unevenly by an insert + /// has both, and spare capacity in either table counts. #[test] fn table_bytes_count_the_chunk_table_and_the_running_totals() { let (chunk, total) = (size_of::>>(), size_of::()); - let within = |a: &Anchors| { + let reserved = |a: &Anchors| { let held = a.chunks.len() * chunk + a.ends.len() * total; let reserved = a.chunks.capacity() * chunk + a.ends.capacity() * total; - (held..=reserved).contains(&a.table_bytes()) + assert!(held <= reserved); + a.table_bytes() == reserved }; let short = Anchors::from(line(5)); - assert!(short.ends.is_empty() && within(&short), "{}", short.table_bytes()); + assert!(short.ends.is_empty() && reserved(&short), "{}", short.table_bytes()); let mut uneven = Anchors::from(line(CHUNK)); uneven.insert(10, Anchor::corner(Point::ZERO)); assert!(uneven.chunks.len() == 2 && uneven.ends.len() == 2, "{:?}", uneven.ends); - assert!(within(&uneven), "{}", uneven.table_bytes()); + uneven.chunks.reserve(8); + uneven.ends.reserve(8); + assert!(uneven.chunks.capacity() > uneven.chunks.len() && uneven.ends.capacity() > uneven.ends.len()); + assert!(reserved(&uneven), "{}", uneven.table_bytes()); } } From 4bed43a4e895c18ca77ac7e9799efa638291c3c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:54:23 -0800 Subject: [PATCH 445/533] Scripts: undoing a point write selects the anchors it dropped again Writing a script's point changes drops the selected anchors and segments that the new points no longer have before it runs path.setAnchors, so the undo step of the edit kept the trimmed selection. Undoing the edit, with app.undo() in the run or Edit > Undo after it, put the points back but left them unselected. The step now keeps the selection from before the trim. The trim was added in #9304. --- crates/engine/src/script/dom/paths.rs | 32 ++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index cb23b429b0..4ce08f8116 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -342,7 +342,12 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); super::atomically(h, |h| { + // The anchors and segments the new points no longer have leave the selection before the + // points are written. The undo step of the edit keeps the selection from before that, so + // undoing it selects them again. + let mut kept = None; if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + kept = Some((st.doc.clone(), st.selection.clone())); let selection = &mut st.selection; if let Some(anchors) = selection.anchors.get_mut(&item.id) { anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); @@ -361,8 +366,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { { selection.remove(item.id); } + if kept.as_ref().is_some_and(|(_, before)| *before == st.selection) { + kept = None; + } } - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})) + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + if let Some((doc, selection)) = kept + && let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) + && let Some(step) = st.history.undo.last_mut().filter(|step| Arc::ptr_eq(&step.doc, &doc)) + { + step.selection = Arc::new(selection); + } + Ok(()) })?; Ok(()) } @@ -1992,6 +2007,21 @@ mod tests { LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); } + #[test] + fn undoing_a_point_write_selects_the_anchors_it_removed_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap(); + let source = "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [10, 10]]); \ + vc.log(p.selectedPathPoints.length); app.undo();"; + let out = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(out["log"], json!([1])); + let id = NodeId(id.as_u64().unwrap()); + let anchors: Vec<(usize, usize)> = s.active().unwrap().selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default(); + assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); + } + #[test] fn a_made_id_above_two_to_the_53_stays_exact() { let made = |v: Value| made_id(&(Data::Undefined, v)); From 06e5e28a0b74698ad2d723d4d3761b9c69c41cb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:55:45 -0800 Subject: [PATCH 446/533] Tests: cover SVG font keywords, CSS border styles and Save for Web text cells - SVG import: font-size keywords (x-large), larger and smaller against the parent's size, and every bolder and lighter step from the parent's weight. - CSS Properties: a round-capped dash starting with 0 gives a dotted border, other dashes a dashed one, and a gradient stroke a border with border-image. A pen-drawn upright rectangle is written as a rectangle with square corners, and the same path rotated gets the note for a shape CSS cannot draw. - Save for Web: a No Image cell over the matte color, aligned right and bottom, and an HTML Text cell whose lines are escaped and joined with
. --- crates/engine/src/tests/css.rs | 42 ++++++++++++++++++++++++++++ crates/engine/src/tests/webexport.rs | 15 ++++++++++ crates/svg/tests/it/import_text.rs | 19 +++++++++++++ 3 files changed, 76 insertions(+) diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 39fb6a5bc2..91b18686e5 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -79,6 +79,48 @@ fn gradients_mixed_around_the_hue_wheel_give_css_the_stops_on_their_way() { } } +/// A round-capped dash that starts with a 0 length is a dotted border, any other dash a dashed +/// one, and a gradient stroke a border with a `border-image`. +#[test] +fn dashed_dotted_and_gradient_strokes_give_border_styles() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + let border = |s: &mut Session| { + let text = css(&run(s, "css.selection", json!({}))).to_string(); + let line = text.lines().find(|l| l.trim_start().starts_with("border:")).unwrap_or_else(|| panic!("a border in {text}")).trim().to_string(); + (line, text) + }; + run(&mut s, "stroke.set", json!({"weight": 1, "cap": "round", "dash": [0, 4]})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px dotted #000000;", "{text}"); + run(&mut s, "stroke.set", json!({"cap": "butt", "dash": [6, 3]})); + assert_eq!(border(&mut s).0, "border: 1px dashed #000000;"); + run(&mut s, "stroke.set", json!({"dash": null})); + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + let (line, text) = border(&mut s); + assert_eq!(line, "border: 1px solid;", "{text}"); + let image = text.lines().find(|l| l.trim_start().starts_with("border-image:")).unwrap_or_else(|| panic!("a border-image in {text}")); + assert!(image.contains("linear-gradient(") && image.trim_end().ends_with(" 1;"), "{image}"); +} + +/// A pen-drawn upright rectangle is written as a rectangle: a background with square corners. The +/// same path turned is not, and gets the note for a shape CSS cannot draw. +#[test] +fn a_drawn_upright_rectangle_is_a_rectangle_and_a_turned_one_is_not() { + let mut s = session(); + let id = run(&mut s, "path.create", json!({"d": "M10 20 H130 V80 H10 Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#3366cc"})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + let text = css(&r); + assert!(text.contains("background-color: #3366cc;"), "{text}"); + assert!(!text.contains("border-radius"), "{text}"); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + run(&mut s, "object.rotate", json!({"angle": 30})); + let r = run(&mut s, "css.selection", json!({"ids": [id]})); + assert_eq!(r["rules"][0]["unsupported"], json!("a shape other than a rectangle or an ellipse"), "{r}"); +} + #[test] fn generate_covers_the_document_and_an_empty_selection_has_none() { let mut s = session(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 656a5689f8..746537db05 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -356,6 +356,13 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(f.len(), n); let html = String::from_utf8(f[0].1.clone()).unwrap(); assert!(html.contains("Hi") && html.contains("background: #ffffff;") && html.contains("justify-content: center")); + // Over the matte, at the bottom right. + run(&mut s, "object.slice.options", json!({"background": "matte", "hAlign": "right", "vAlign": "bottom"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html", "matte": "#ffff00"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + let cell = html.lines().find(|l| l.contains("Hi")).unwrap_or_else(|| panic!("the No Image cell in {html}")); + assert!(cell.contains("background: #ffff00;"), "{cell}"); + assert!(cell.contains("justify-content: flex-end;") && cell.contains("align-items: flex-end;"), "{cell}"); // Selected slices only. run(&mut s, "object.slice.select", json!({"slices": [a]})); let f = files(&run(&mut s, "document.exportForWeb", json!({"slices": "selected"}))); @@ -367,6 +374,14 @@ fn slices_give_one_image_each_and_a_page() { assert_eq!(run(&mut s, "document.exportForWeb.preview", json!({}))["slices"], n - 1); let one_slice = run(&mut s, "document.exportForWeb.preview", json!({"slice": layout[0]["number"]})); assert_eq!((one_slice["width"].as_f64(), one_slice["height"].as_f64()), (layout[0]["width"].as_f64(), layout[0]["height"].as_f64())); + // An HTML Text slice: the type's text, escaped, with its lines joined by
. + let t = run(&mut s, "text.create", json!({"x": 20, "y": 150, "text": "A&B\nC"}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.make", json!({"ids": [t]})); + run(&mut s, "select.set", json!({"ids": [t]})); + run(&mut s, "object.slice.options", json!({"kind": "htmlText"})); + let f = files(&run(&mut s, "document.exportForWeb", json!({"output": "html"}))); + let html = String::from_utf8(f[0].1.clone()).unwrap(); + assert!(html.contains(">A&B
C"), "{html}"); } /// Save for Web writes the image of a slice named after a Windows device (`aux`, `NUL`, `COM1`…) diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 9c1cac5890..4a9e0050e2 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -1126,6 +1126,25 @@ fn weights_spacing_and_decoration() { assert_eq!(style('a').kerning, None); } +/// Font-size keywords scale `medium` (12), `larger` and `smaller` scale the parent's size by 1.2, +/// and `bolder` and `lighter` step from the parent's weight as CSS's relative-weight table says. +#[test] +fn font_size_keywords_and_relative_weights_follow_the_parent() { + let d = open( + r#"abcdefghijklm"#, + ); + let t = only_text(&d); + let style = |c: char| t.runs.iter().find(|r| r.text.contains(c)).unwrap().style.clone(); + let size = |c: char| style(c).size; + assert!(close(size('b'), 18.0, 1e-9), "x-large is 3/2 of medium: {}", size('b')); + assert!(close(size('d'), 12.0, 1e-9), "larger than 10: {}", size('d')); + assert!(close(size('e'), 10.0 / 1.2, 1e-9), "smaller than 10: {}", size('e')); + assert_eq!(style('g').font_style, "Bold", "bolder than 500 is 700"); + assert_eq!(style('i').font_style, "Black", "bolder than 600 is 900"); + assert_eq!(style('k').font_style, "Regular", "lighter than 700 is 400"); + assert_eq!(style('m').font_style, "Bold", "lighter than 900 is 700"); +} + /// `font-variation-settings` becomes the characters' Variable Font settings, inherited as CSS /// inherits it; `normal` and `initial` set none, and `unset` and a value CSS ignores leave the /// inherited settings. From ebe9e41a331317725525797476f312de5c847ae1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:57:42 -0800 Subject: [PATCH 447/533] Tests: check where the spot gradient midpoint lands in the PDF The test passed "midpoint": 30, which the command clamps to 0.87, and its tint assertions hold at any midpoint. It now passes 0.3 and asserts the stitching function's /Bounds[0.3]. --- crates/engine/src/tests/linked_stops.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index 4aa7d4c2a1..e04296d26d 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -137,12 +137,14 @@ fn spot_gradients_export_as_separation_shadings() { run( &mut s, "paint.editGradient", - json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80, "midpoint": 30}, {"offset": 1, "color": "#ffffff"}]}), + json!({"stops": [{"offset": 0, "swatch": "Ink", "tint": 80, "midpoint": 0.3}, {"offset": 1, "color": "#ffffff"}]}), ); let (pdf, _) = pdf_of(&s); assert!(pdf.contains("/Separation/Ink/DeviceCMYK") && !pdf.contains("/DeviceN"), "still one spot ink"); let functions: Vec<_> = pdf.match_indices("/C0[").filter_map(|(i, _)| pdf.get(i..i + 24)).collect(); assert!(pdf.contains("/C0[0.8]/C1[0.4]") && pdf.contains("/C0[0.4]/C1[0]"), "the tints through the midpoint: {functions:?}"); + let bounds: Vec<_> = pdf.match_indices("/Bounds").filter_map(|(i, _)| pdf.get(i..i + 16)).collect(); + assert!(pdf.contains("/Bounds[0.3]"), "the midpoint stop sits at 30 %: {bounds:?}"); // Mixing the spot ink with an RGB color writes the gradient without the spot ink, with a warning. run(&mut s, "paint.editGradient", json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#00ff00"}]})); let (pdf, warnings) = pdf_of(&s); From bba32dd27cc12f707e5cf615509863c8ad7c1556 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:59:57 -0800 Subject: [PATCH 448/533] Recolor Artwork: a global swatch row's chip shows the swatch's own color A row picked from a global process swatch links its art to the swatch, which takes the swatch's color at full precision. The New chip showed the row's color key, which rounds that color to hundredths of a percent. The chip now shows the swatch's color while the row recolors art; a row with no current colors keeps the key's color, which the group takes. --- crates/ui-egui/src/dialogs/recolor.rs | 38 +++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 01860accb2..b20b261c90 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -2640,6 +2640,14 @@ fn new_shown(app: &VectorcraftApp, d: &Fields, links: &RowLinks, row: &Value) -> let to = to_color(row).unwrap_or_default(); // `recolor.apply` skips an excluded row, so without a library its chip takes no Global Adjust. let effective = if excluded(row) && links.library.is_none() { to } else { links.effective_color(&to) }; + // Art linked to a global swatch takes the swatch's own color, which the row's color key rounds. + // A row with no current colors links no art, and the group takes its color as the key gives it. + let maps_art = d.bool("__art") && row["from"].as_array().is_some_and(|f| !f.is_empty()); + let effective = if excluded(row) || !maps_art { + effective + } else { + own_global(app, d, links, row, &effective).and_then(|w| w.paint.color()).unwrap_or(effective) + }; if d.bool("__art") && !excluded(row) && let Some(c) = linked_spot(app, d, links, row, &to).and_then(|w| w.paint.color()) @@ -2807,6 +2815,20 @@ fn own_spot(app: &VectorcraftApp, d: &Fields, links: &RowLinks, row: &Value, c: row_swatch(app, row, c).filter(|w| w.spot && !link_rewritten(app, links, w)) } +/// The global process swatch the art of `row` links to through the row's own `swatch`, with `near` +/// the row's new color as [`RowLinks::effective_color`] gives it: only when Limit to Library has no +/// swatch of that color, as in `recolor.apply`. +fn own_global(app: &VectorcraftApp, d: &Fields, links: &RowLinks, row: &Value, near: &Color) -> Option { + swatch_ref(row)?; + if d.str("limitTo").is_empty() && !global_adjust(adjust_values(d)).is_identity() { + return None; + } + if links.library.as_ref().is_some_and(|(_, l)| l.iter().any(|w| w.paint.color() == Some(*near))) { + return None; + } + row_swatch(app, row, near).filter(|w| w.global && !w.spot && !link_rewritten(app, links, w)) +} + /// Whether the art `recolor.apply` links to swatch `w` (a library's or the document's) links nothing /// because OK's rewrite of the color group gives it another color: `w` joins the document under its /// own name only when the document's swatch of that name has its paint, Global and spot, and is @@ -4922,6 +4944,22 @@ mod tests { assert_eq!(new_shown(&app, &d, &links, &row), red); } + /// A row picked from a global process swatch shows the swatch's own color, which the art takes, + /// not the row's color key, which rounds it. + #[test] + fn a_global_swatch_row_shows_the_swatch_color_at_full_precision() { + let mut app = app(100); + app.run("swatch.new", json!({"name": "Fine", "color": {"c": 12.345, "m": 87.654, "y": 0, "k": 0}, "global": true})).unwrap(); + let ink = app.session.doc().unwrap().doc.swatch("Fine").and_then(|w| w.paint.color()).unwrap(); + let d = Fields::new(json!({"__art": true})); + let row = json!({"from": ["rgb 255 0 0"], "to": key(&ink), "swatch": {"name": "Fine"}}); + assert_ne!(to_color(&row).unwrap(), ink, "the key rounds the swatch's color"); + assert_eq!(new_shown(&app, &d, &RowLinks::new(&app, &d), &row), ink); + // A row with no current colors links no art, so the group takes the key's color. + let added = json!({"from": [], "to": key(&ink), "swatch": {"name": "Fine"}}); + assert_eq!(new_shown(&app, &d, &RowLinks::new(&app, &d), &added), to_color(&added).unwrap()); + } + /// A row picked from a spot swatch of the color group shows Tint and its tint on the chip while /// OK leaves the swatch its color, and no Tint and the full color once OK gives the swatch /// another color, as `recolor.apply` then gives the art. From 13488c3103a4d3fd7aa6d34ec09db4e3734071e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:10:09 -0800 Subject: [PATCH 449/533] Scripts: document pathItems.removeAll refuses to delete a clipping path Document.pathItems.removeAll() deleted every path of the document even when one was the clipping path of a group or layer that keeps other objects, so the next object became the clipping path. The scoped collections already refuse this. The document's collection now runs the same check before anything is deleted, and also refuses when it would empty a compound path or group that clips other objects. edit.clear removes an emptied compound path and keeps an emptied group, and the check follows it. The fault came with #9041, which added Document.pathItems. --- crates/engine/src/script/dom/paths.rs | 54 ++++++++- crates/engine/src/tests/script_dom.rs | 165 ++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 216 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a164dd93fc..00758409bc 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -495,18 +495,56 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before -/// anything is deleted, as `PageItems.removeAll()` does. +/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or +/// layer that keeps other objects, or a compound path or group that clips one and would be left +/// empty. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; - let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - let locks = st.doc.locked_artboards(); + let d = &st.doc; + let refused: Vec = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + let mut next: Vec<_> = d.layers.iter().collect(); + let mut nodes = Vec::new(); + while let Some(n) = next.pop() { + nodes.push(n); + next.extend(n.children().into_iter().flatten()); + } + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + let mut geometry = std::collections::HashSet::new(); + let mut masks = Vec::new(); + for n in nodes.into_iter().rev() { + let kids = n.children().map_or(&[][..], Vec::as_slice); + // Clear removes compound paths emptied of direct members, but keeps empty groups. + if matches!(n.kind, NodeKind::Compound { .. }) + && !kids.is_empty() + && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) + { + going.insert(n.id); + } + if kids.iter().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + if (matches!(n.kind, NodeKind::Path { .. }) && !going.contains(&n.id)) || kids.iter().any(|k| geometry.contains(&k.id)) { + geometry.insert(n.id); + } + if n.clips() + && let Some(mask) = kids.first() + && affected.contains(&mask.id) + && !geometry.contains(&mask.id) + && kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + && masks.len() < 20 + { + masks.push(mask.id.0); + } + } + Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -516,6 +554,12 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 73e44c2af7..2ebc3b3d44 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3312,6 +3312,171 @@ fn scoped_remove_all_refuses_a_clipping_compound_path() { assert_eq!(undo_steps(&s), steps); } +/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths. +const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + +/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the +/// group keeps other art, and deletes nothing, as the scoped collections do. +#[test] +fn document_path_items_remove_all_refuses_a_clipping_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + // The script catches the error and counts the paths before the run ends, so the run's own + // rollback cannot hide a deletion. + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&a.0.to_string()), "{out:?}"); + assert!(!e.contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping +/// other art, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&compound.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would +/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing. +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + assert!(d.node(empty).unwrap().children().unwrap().is_empty()); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!( + out[0], + json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0)) + ); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() { + for compound in [false, true] { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap(); + let sibling = s.active().unwrap().doc.parent_of(b).unwrap(); + let layer = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(layer).unwrap().clips()); + assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a)); + let before = d.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + if compound { + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(sibling).is_none()); + assert!(!d.node(layer).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } else { + assert_eq!( + out[0], + json!(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", + a.0 + )) + ); + assert_eq!(out[1], json!(3)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + } +} + /// A path that leaves a compound path for a layer is drawn as it was: it takes the compound /// path's paint and pixel alignment, as Release Compound Path gives them. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..242678381f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3233,7 +3233,7 @@ through `$`: `Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`, `groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`Stale page item`) and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document. - `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's + `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..f4bf5a74ff 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1116,7 +1116,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard, or when it would delete or empty the clipping path of a group or layer that keeps other objects. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. From ccbeae48322fdb6996bfeea9a888d6e201439c00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:11:04 -0800 Subject: [PATCH 450/533] EPS import: the 4096 x 4096 sampled function test fails on any rejection The test only checked that no warning mentioned limitcheck, so a rangecheck or typecheck at the size limit would still pass. It now checks that the import reports no error at all. --- crates/eps/src/import/tests_generators.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 17df25cd9c..260a6c0fe6 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -1010,7 +1010,7 @@ fn hostile_patterns_glyphs_and_shadings_end() { )) }; let r = sized("4096 4096"); - assert!(!r.warnings.iter().any(|w| w.contains("limitcheck")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("error")), "{:?}", r.warnings); let r = sized("4096 4097"); assert!(r.warnings[0].contains("limitcheck in `shfill`: Size"), "{:?}", r.warnings); // Procedures nesting through operators that run them end at the nesting limit. From b32285d451aac355bce7c352b44523dbe047b517 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:13:01 -0800 Subject: [PATCH 451/533] Tests: cover script DOM range checks, PrintOptions groups and evalFile refusals - The text attribute test has rows one step past the bounds of baselineShift, horizontalScale, verticalScale and rotation. - A new print test prints each PrintOptions group (overprints, page marks, orientation, separations, custom and transverse paper, emulsion, negative and position) through Document.print and compares the PostScript with what file.print writes for the matching settings, leaving out the CreationDate comment. Each case also checks that its settings change the file. The color intent is compared in PDF, by the art the printed file opens as. - A new include test reads a refused absolute path whose URI-decoded form is not read either, and checks that $.evalFile keeps the refusal. --- crates/engine/src/tests/script_include.rs | 15 ++++ crates/engine/src/tests/script_print.rs | 88 +++++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 4 ++ 3 files changed, 107 insertions(+) diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 1b41d992fd..8c4276cfce 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -461,6 +461,21 @@ fn script_eval_file_outside_scope_refused() { let _ = std::fs::remove_dir_all(base); } +/// A refused absolute path whose URI form is read by no candidate either keeps the refusal of +/// the path as written, not a missing file. +#[cfg(not(windows))] +#[test] +fn script_eval_file_keeps_the_refusal_when_no_uri_form_is_read() { + let base = folder("evaluri"); + write(&base.join("out%20side.jsx"), "1;"); + let absolute = base.join("out%20side.jsx").to_string_lossy().into_owned(); + let script = format!("try {{ $.evalFile('{absolute}'); }} catch (e) {{ vc.log(String(e)); }}"); + let r = run(&base, &script).unwrap(); + let e = r["log"][0].as_str().unwrap_or_default().to_string(); + assert!(e.starts_with(&format!("Error: script file read refused: {absolute}")), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_directives_in_strings_and_block_comments_are_inert() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index ad542049a1..624a108d1e 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -622,6 +622,94 @@ fn assigned_job_and_scale_options_apply_over_the_saved_settings() { let _ = std::fs::remove_dir_all(base); } +/// Each option group prints the PostScript `file.print` writes for the settings it maps to, and +/// each of those settings changes the file. +#[test] +fn option_groups_print_what_their_settings_print() { + let base = folder("groups"); + let mut s = session(&base); + // A red rectangle whose fill overprints, printed through a CMYK printer profile: the intent + // decides its inks and the overprint option whether it keeps overprinting. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("attributes.set", &json!({"overprintFill": true})).unwrap(); + let profile = vectorcraft_color::cms::GENERIC_CMYK; + let saved = + json!({"media": "letter", "autoRotate": false, "orientation": "portrait", "artboards": "range", "range": "1", "color": {"profile": profile}}); + s.execute("print.setup", &json!({"settings": saved})).unwrap(); + let dir = data_folder(&mut s, &base); + // The jobs print to PostScript, whose only line that depends on the clock is its + // `%%CreationDate` comment. + let undated = |path: &Path| { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.starts_with("%!PS"), "{}: {}", path.display(), &text[..text.len().min(40)]); + text.lines().filter(|l| !l.starts_with("%%CreationDate:")).collect::>().join("\n") + }; + s.execute("file.print", &json!({"format": "postscript", "path": dir.join("plain.ps").to_string_lossy()})).unwrap(); + let plain = undated(&dir.join("plain.ps")); + let mut wrong = Vec::new(); + let cases = [ + ("o.flattenerOptions.overprint = PDFOverprint.DISCARDPDFOVERPRINT;", json!({"advanced": {"overprints": "discard"}})), + ( + "o.pageMarksOptions.pageMarksType = PageMarksTypes.Japanese; o.pageMarksOptions.trimMarks = true;", + json!({"marks": {"kind": "japanese", "trim": true}}), + ), + ("o.coordinateOptions.orientation = PrintOrientation.LANDSCAPE;", json!({"autoRotate": false, "orientation": "landscape"})), + ("o.colorSeparationOptions.colorSeparationMode = PrintColorSeparationMode.HOSTBASEDSEPARATION;", json!({"output": {"mode": "separations"}})), + ( + "var m = o.pageMarksOptions; m.trimMarks = true; m.registrationMarks = true; m.trimMarksWeight = 1;", + json!({"marks": {"trim": true, "registration": true, "weight": 1.0}}), + ), + ("o.paperOptions.width = 400; o.paperOptions.height = 300;", json!({"media": "custom", "width": 400.0, "height": 300.0})), + ("o.paperOptions.transverse = true;", json!({"transverse": true})), + ("o.coordinateOptions.emulsion = true;", json!({"output": {"emulsion": "down"}})), + ("o.postScriptOptions.negativePrinting = true;", json!({"output": {"image": "negative"}})), + ("o.coordinateOptions.position = PrintPosition.TRANSLATETOPLEFT;", json!({"placement": {"origin": "topLeft"}})), + ]; + for (i, (body, settings)) in cases.iter().enumerate() { + let [want, got] = ["want", "got"].map(|name| dir.join(format!("{name}{i}.ps"))); + s.execute("file.print", &json!({"format": "postscript", "settings": settings, "path": want.to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); {body} app.activeDocument.print(o);", + quoted(&got) + ), + ); + let want = undated(&want); + if want == plain { + wrong.push(format!("{i}: {settings} does not change the printed file")); + } + if undated(&got) != want { + wrong.push(format!("{i}: {body} does not print as {settings}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + let page_count = |path: &Path| undated(path).lines().filter(|l| l.starts_with("%%Page:")).count(); + assert!(page_count(&dir.join("want3.ps")) > page_count(&dir.join("plain.ps")), "a page for each ink"); + // PostScript leaves the printer profile out, so the intent is compared in PDF, by the art the + // printed file opens as, which leaves out the file's date. + let art = |name: &str| { + let doc = vectorcraft_pdf::import(&std::fs::read(dir.join(name)).unwrap()).unwrap(); + serde_json::to_string(&doc.layers).unwrap() + }; + let perceptual = json!({"color": {"intent": "perceptual"}}); + s.execute("file.print", &json!({"path": dir.join("plain.pdf").to_string_lossy()})).unwrap(); + s.execute("file.print", &json!({"settings": perceptual, "path": dir.join("want.pdf").to_string_lossy()})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});\n\ + o.colorManagementOptions.intent = PrintColorIntent.PERCEPTUALINTENT; app.activeDocument.print(o);", + quoted(&dir.join("got.pdf")) + ), + ); + assert!(art("want.pdf") != art("plain.pdf"), "the intent changes the inks"); + assert_eq!(art("got.pdf"), art("want.pdf"), "PrintColorIntent.PERCEPTUALINTENT prints as {perceptual}"); + let _ = std::fs::remove_dir_all(base); +} + /// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the /// granted folder leads to. #[cfg(unix)] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 2794e929b2..1639358c7e 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -224,6 +224,10 @@ fn bad_attribute_values_are_refused_without_a_change() { ("r.size = NaN;", "not a finite number"), ("r.leading = 0;", "leading must be from 0.1"), ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.baselineShift = -1297;", "baselineShift must be from -1296 to 1296"), + ("r.horizontalScale = 0.9;", "horizontalScale must be from 1 to 10000"), + ("r.characterAttributes.verticalScale = 10001;", "verticalScale must be from 1 to 10000"), + ("r.rotation = 361;", "rotation must be from -360 to 360"), ("r.underline = 1;", "underline must be true or false"), ("r.textFont = 'Arial';", "textFont must be a TextFont"), ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), From ad7aebf3030cab602f98965d9394e55c81d4f643 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:16:30 -0800 Subject: [PATCH 452/533] Hyphenation: the focused-edit test clicks another option after typing The focused-edit test now clicks Hyphenate Capitalized Words after typing a Words Longer Than count and pressing Tab, and checks that the draft keeps the typed count while the checkbox changes, in every language and every answer it runs. OK and the confirmation commit both edits. The docs/mcp.md sentence on the disabled options is wrapped to the paragraph's width. --- crates/ui-egui/src/dialogs/hyphenation.rs | 14 +++++++++++++- docs/mcp.md | 8 ++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/hyphenation.rs b/crates/ui-egui/src/dialogs/hyphenation.rs index b1f3894c55..d6767ba3bc 100644 --- a/crates/ui-egui/src/dialogs/hyphenation.rs +++ b/crates/ui-egui/src/dialogs/hyphenation.rs @@ -227,15 +227,17 @@ mod tests { let modal = control(&tree, "Hyphenation", Role::Dialog, None); let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal)); let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal)); + let capitalized = control(&tree, "Hyphenate Capitalized Words", Role::CheckBox, Some(modal)); let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal)); assert!(screen.expand(0.5).contains_rect(modal)); - for bounds in [count, enabled, footer] { + for bounds in [count, enabled, capitalized, footer] { assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}"); } let before = driver::fields(&app); assert_eq!(before.number("wordsLongerThan"), Some(5.0)); assert_eq!(before.bool("hyphenate"), Some(false)); assert!(before.is_mixed("afterFirst")); + assert_eq!(before.bool("hyphenateCapitalized"), Some(true)); // The counts take input once Hyphenation is on. click(&mut app, &mut frame, enabled.center()); settle(&mut app, &mut frame); @@ -251,6 +253,15 @@ mod tests { if checked != Some(true) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") { failures.push(format!("{lang} {answer}: {checked:?}, {kept:?}")); } + // Clicking another option after typing keeps the typed count. + click(&mut app, &mut frame, capitalized.center()); + settle(&mut app, &mut frame); + let inspected = draft(&app, &ctx); + let other = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenateCapitalized"].as_bool()); + eprintln!("{lang}, {answer}: ui.inspect after the second checkbox {other:?}"); + if other != (Some(8.0), Some(false)) { + failures.push(format!("{lang} {answer}: after the second checkbox {other:?}")); + } assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open"); if answer == "ui.dialog.confirm" { let (request, _) = ControlRequest::new(answer, json!({})); @@ -279,6 +290,7 @@ mod tests { for p in [&mut expected.0, &mut expected.1] { p.hyphenation.words_longer_than = 8; p.hyphenate = true; + p.hyphenation.capitalized = false; } if actual != expected || undo_delta != 1 { failures.push(format!( diff --git a/docs/mcp.md b/docs/mcp.md index f77b041d47..4c7991433e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14179,10 +14179,10 @@ listed word. The options are saved with the paragraph (`hyphenation` in `para`) defaults, and paragraph styles carry them (`paraStyle.new {attrs: {hyphenation: {words_longer_than: 8}}}`). One undo step. `ui.hyphenation` opens the Hyphenation dialog on the values the Paragraph panel shows; OK sends the values that changed. The options below the Hyphenation checkbox take input only while it is checked, and Hyphenation Zone is -disabled while no paragraph in scope uses a single-line composer. The UI command `type.hyphenate` (Cmd+Alt+Shift+H, in remote mode `press_key {key: "H", mods: {cmd: true, -alt: true, shift: true}}` or `invoke_menu`) does what the Hyphenate checkbox does: it turns `hyphenate` off when -every paragraph of the selected type (or every paragraph the Type tool's selection touches) hyphenates, else on, and -returns the new value. +disabled while no paragraph in scope uses a single-line composer. The UI command `type.hyphenate` (Cmd+Alt+Shift+H, +in remote mode `press_key {key: "H", mods: {cmd: true, alt: true, shift: true}}` or `invoke_menu`) does what the +Hyphenate checkbox does: it turns `hyphenate` off when every paragraph of the selected type (or every paragraph the +Type tool's selection touches) hyphenates, else on, and returns the new value. ```json {"name":"run_command","arguments":{"command":"text.setFormat","params":{"hyphenate":true,"wordsLongerThan":8,"hyphenLimit":2}}} From 14e8959bc0e31df27bae7ee4ef0a16b9d870f2c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:19:16 -0800 Subject: [PATCH 453/533] Scripts: tighten rasterize clip bounds and imageCapture destination checks - object.rasterize and Document.rasterize refuse clipBounds that reach none of the selected objects' own bounds, including a rectangle in the gap between two of them, instead of replacing the art with a background-only image. - imageCapture checks its destination again on every write the export makes and as the file is committed, so a destination that becomes a link to an open document or a linked file while the art renders is refused. - imageCapture refuses a destination whose real path is not valid UTF-8 instead of writing under a name with its bytes replaced. - A missing linked file's name in the other Unicode normalization form counts as the linked file in folders that ignore the form (macOS, and casefolded folders on Linux). - The hard-link tests skip on volumes without hard links. - docs/mcp.md: imageCapture rounds clip dimensions to the nearest pixel; rasterize rounds fractional dimensions up. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 3 + crates/engine/src/cmd/menucmds.rs | 13 +- crates/engine/src/file_access.rs | 42 ++++++- crates/engine/src/script/dom.rs | 2 + .../engine/src/script/dom/raster_capture.rs | 83 +++++++++++-- .../engine/src/tests/script_raster_capture.rs | 115 +++++++++++++++++- docs/mcp.md | 4 +- 8 files changed, 239 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..50d594fab9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8741,6 +8741,7 @@ dependencies = [ "skrifa 0.47.0", "thiserror 2.0.21", "tiff", + "unicode-normalization", "vectorcraft-affinity", "vectorcraft-apischema", "vectorcraft-brush", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 945e6c92be..0fe4f7d10e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -71,6 +71,9 @@ serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } +# Whether two file names differ only in their Unicode normalization form, in a folder that ignores +# it (`script::dom::raster_capture`). Already in Cargo.lock, so this adds no new crate. +unicode-normalization = "0.1.26" # Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a # file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 7af1bae33d..661fe741e7 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -896,7 +896,8 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p }) .collect(); // What the art draws, its geometry effects applied. - let b = nodes.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, vectorcraft_render::drawn_bounds(doc, n))); + let each: Vec = nodes.iter().filter_map(|n| vectorcraft_render::drawn_bounds(doc, n)).collect(); + let b = each.iter().fold(None, |acc, r| vectorcraft_geom::union_opt(acc, Some(*r))); let drawn = b.ok_or_else(|| bad(cmd, "selection has no bounds"))?; let mut b = drawn.inflate(pad, pad); let mut clip_bounds = None; @@ -906,9 +907,13 @@ pub(crate) fn rasterize_art(doc: &vectorcraft_doc::Document, nodes: Vec, p return Err(bad(cmd, "clipBounds must have x1 greater than x0 and y1 greater than y0")); } let clip_rect = Rect::new(x0, y0, x1, y1); - // The rectangle must reach the art itself, not only the padding around it. - let on_art = drawn.intersect(clip_rect); - if on_art.width() <= 0.0 || on_art.height() <= 0.0 { + // The rectangle must reach the art itself, not only the padding around it or the gap + // between two of the selected objects. + let reaches = |r: &Rect| { + let on = r.intersect(clip_rect); + on.width() > 0.0 && on.height() > 0.0 + }; + if !each.iter().any(reaches) { return Err(bad(cmd, "clipBounds does not overlap the art")); } clip_bounds = Some(clip_rect); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 55c06cc130..afc8c52e73 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -510,11 +510,43 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// A check every write on this thread must pass as well, given the path as written or, at the +/// moment a checked write commits on Unix, the opened folder's real path with the file's name +/// ([`with_write_guard`]). +pub(crate) type WriteGuard = std::rc::Rc Result<(), String>>; + +thread_local! { + static WRITE_GUARD: RefCell> = const { RefCell::new(None) }; +} + +/// Puts the write guard it replaced back when dropped (also when `f` panics). +struct RestoreWriteGuard(Option); + +impl Drop for RestoreWriteGuard { + fn drop(&mut self) { + let previous = self.0.take(); + WRITE_GUARD.with(|g| *g.borrow_mut() = previous); + } +} + +/// Runs `f` with `guard` checked on every write it makes on this thread, again at the moment each +/// checked write commits, so a destination that is changed after an earlier check is checked as it +/// is then. +pub(crate) fn with_write_guard(guard: WriteGuard, f: impl FnOnce() -> T) -> T { + let _restore = RestoreWriteGuard(WRITE_GUARD.with(|g| g.replace(Some(guard)))); + f() +} + +fn check_write_guard(path: &Path) -> Result<(), String> { + WRITE_GUARD.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g(path)) +} + /// [`check_write`] without adding `path` to the files a script run reports as written, for a /// check made before anything is written. pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write) + check_gate(path, Access::Write)?; + check_write_guard(Path::new(path)) } /// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been @@ -523,12 +555,14 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { #[cfg(unix)] pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; - GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))?; + check_write_guard(real) } -/// Whether a write here is checked: roots are in force, or a script's command runs. +/// Whether a write here is checked: roots are in force, a script's command runs, or a write guard +/// is in force ([`with_write_guard`]). pub(crate) fn writes_checked() -> bool { - current().is_some() || in_script_command() + current().is_some() || in_script_command() || WRITE_GUARD.with(|g| g.borrow().is_some()) } /// A file's modification time and length; `None` when there is no file at `path`. diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 607a20362e..b08a961396 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -108,6 +108,8 @@ mod paths; pub mod preferences; mod print; mod raster_capture; +#[cfg(test)] +pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT; mod save_open; mod tags; mod text; diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 3a2100a148..36fec48381 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -321,9 +321,65 @@ fn placed(p: &std::path::Path) -> Option { } /// Whether two [`placed`] files are one file: the same folder, and the same name, or names that -/// differ only in letter case in a folder whose volume ignores case. +/// differ only in letter case in a folder whose volume ignores case, or only in their Unicode +/// normalization form in a folder whose volume ignores that. fn same_file(a: &Placed, b: &Placed) -> bool { - same_folder(&a.0, &b.0) && (a.1 == b.1 || (a.1.to_string_lossy().to_lowercase() == b.1.to_string_lossy().to_lowercase() && ignores_case(&a.0))) + if !same_folder(&a.0, &b.0) { + return false; + } + if a.1 == b.1 { + return true; + } + let (x, y) = (a.1.to_string_lossy(), b.1.to_string_lossy()); + let form = |s: &str| unicode_normalization::UnicodeNormalization::nfc(s).collect::(); + if form(&x) == form(&y) { + return ignores_normalization(&a.0); + } + let (lx, ly) = (x.to_lowercase(), y.to_lowercase()); + if form(&lx) != form(&ly) || !ignores_case(&a.0) { + return false; + } + lx == ly || ignores_normalization(&a.0) +} + +/// Whether file names in the real folder `folder` ignore their Unicode normalization form: the +/// first of the folder's first 256 entries whose name changes between the composed (NFC) and +/// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and +/// names ignore the form when that finds the same entry. With no such entry, names ignore the form +/// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that +/// ignores letter case (ext4 and f2fs casefolding also ignore the form), and keep it elsewhere. +fn ignores_normalization(folder: &std::path::Path) -> bool { + use unicode_normalization::UnicodeNormalization; + for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue }; + let (c, d): (String, String) = (name.nfc().collect(), name.nfd().collect()); + let other = if name == c { d } else { c }; + if other != name && entry.file_type().is_ok_and(|t| !t.is_symlink()) { + return finds_same(&entry.path(), &folder.join(other)); + } + } + cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ignores_case(folder)) +} + +/// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path +/// of its folder with its name: it is none of the `sources` ([`sources_on_disk`]), not one of them +/// under another name, and has no other hard links. +fn capture_target_check(p: &std::path::Path, sources: &[Placed], shown: &str) -> Result<(), String> { + let real = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if placed(&real).is_some_and(|t| sources.iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { + return Err(format!("imageCapture cannot write over an open document or a file it links: {shown}")); + } + if has_other_links(&real) { + return Err(format!("imageCapture cannot write over a file that has other hard links: {shown}")); + } + Ok(()) +} + +#[cfg(test)] +thread_local! { + /// Run once in `imageCapture` after its checks and before its export, for tests that change the + /// destination in between. + pub(crate) static BEFORE_CAPTURE_EXPORT: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Whether two real paths are one file or folder: the same path, or, on Unix, the same device and @@ -453,15 +509,18 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { }; check_size(region, ppi)?; let real = h.disk.borrow().save_target(path).map_err(|m| HostError::Error(format!("{m}: {path}")))?; - let target = placed(&real); - if target.is_some_and(|t| sources_on_disk(h).iter().any(|s| same_file(&t, s) || same_identity(&real, &s.0.join(&s.1)))) { - return Err(HostError::Error(format!("imageCapture cannot write over an open document or a file it links: {path}"))); - } - if has_other_links(&real) { - return Err(HostError::Error(format!("imageCapture cannot write over a file that has other hard links: {path}"))); - } + let sources = sources_on_disk(h); + let shown = path.to_string(); + // Checked here, and again as the export commits its file, so a destination changed into a link + // to a protected file while the art renders is refused too. + let guard = move |p: &std::path::Path| capture_target_check(p, &sources, &shown); + guard(&real).map_err(HostError::Error)?; + let plain = crate::cmd::findfiles::plain(real); + let Some(plain) = plain.to_str() else { + return Err(HostError::Error(format!("imageCapture cannot write to a path that is not valid UTF-8: {path}"))); + }; let p = json!({ - "path": crate::cmd::findfiles::plain(real).to_string_lossy(), + "path": plain, "format": "png", "rect": [region.x0, region.y0, region.width(), region.height()], "ppi": ppi, @@ -469,8 +528,10 @@ fn doc_image_capture(h: &Host, a: &[Data]) -> Answer { "antiAlias": anti_alias, "includeArtboardFill": false, }); + #[cfg(test)] + BEFORE_CAPTURE_EXPORT.with(|f| f.borrow_mut().take().map(|f| f())); h.disk.borrow_mut().exact = true; - let r = on_doc(h, doc.uid, false, |h| command(h, "document.export", &p)); + let r = crate::file_access::with_write_guard(std::rc::Rc::new(guard), || on_doc(h, doc.uid, false, |h| command(h, "document.export", &p))); h.disk.borrow_mut().exact = false; super::save_open::command_warnings(h, "imageCapture", &r?); Ok(Data::Undefined) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index 6f1c6357f5..ac12a3e22f 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -444,6 +444,20 @@ fn script_rasterize_rejects_bad_clip_bounds() { ); } +#[test] +fn object_rasterize_refuses_clip_bounds_between_the_sources() { + let (mut s, a, b) = doc(); + let undo = undo_steps(&s); + // The rectangle lies inside the box around `a` and `b` but reaches neither of them. + let e = s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [55, 45, 65, 55]})).unwrap_err().to_string(); + assert!(e.contains("does not overlap the art"), "{e}"); + assert_eq!(undo_steps(&s), undo, "no edit"); + assert_eq!(images(&s), Vec::<(u32, u32)>::new()); + // A rectangle that reaches only `a` is still accepted. + s.execute("object.rasterize", &json!({"ids": [a.0, b.0], "clipBounds": [30, 30, 65, 55]})).unwrap(); + assert_eq!(images(&s).len(), 1); +} + #[test] fn script_rasterize_rejects_an_image_past_the_size_limit() { let (mut s, ..) = doc(); @@ -567,6 +581,22 @@ fn image_capture_exact_clip_bounds_and_matte() { let _ = std::fs::remove_dir_all(base); } +/// `imageCapture` rounds fractional clip dimensions to the nearest whole pixel, as +/// `document.export` does, where `rasterize` rounds them up. +#[test] +fn image_capture_rounds_fractional_clip_dimensions_to_the_nearest_pixel() { + let base = folder("nearest"); + let (mut s, dir) = capture_doc(&base); + let source = format!( + "var o = new ImageCaptureOptions(); o.resolution = 72; app.activeDocument.imageCapture(new File({}), [0, 300, 10.25, 289.75], o);", + quoted(&dir.join("n.png")) + ); + script(&mut s, &base, &source); + let img = png(&dir.join("n.png")); + assert_eq!((img.width(), img.height()), (10, 10), "10.25 pt at 72 ppi"); + let _ = std::fs::remove_dir_all(base); +} + /// Bounds that miss every object still give an image of that area, blank or transparent. #[test] fn image_capture_of_bounds_without_art_is_blank() { @@ -698,13 +728,88 @@ fn capture_refuses_a_file_with_other_hard_links() { let other = dir.join("other.bin"); std::fs::write(&other, b"kept").unwrap(); let alias = dir.join("alias.png"); - std::fs::hard_link(&other, &alias).unwrap(); + if std::fs::hard_link(&other, &alias).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); assert!(e.contains("other hard links"), "{e}"); assert_eq!(std::fs::read(&other).unwrap(), b"kept"); let _ = std::fs::remove_dir_all(base); } +/// A destination that becomes a second name of an open document's file after the capture's checks, +/// while the art renders, is refused as the export commits its file. +#[test] +fn capture_refuses_a_destination_linked_to_an_open_document_during_the_export() { + let base = folder("rebind"); + let (mut s, dir) = capture_doc(&base); + let source = dir.join("source.vectorcraft"); + std::fs::write(&source, b"kept").unwrap(); + s.active_mut().unwrap().path = Some(source.to_string_lossy().into_owned()); + let target = dir.join("late.png"); + let probe = dir.join("probe-link"); + if std::fs::hard_link(&source, &probe).is_err() { + // The volume has no hard links. + let _ = std::fs::remove_dir_all(base); + return; + } + std::fs::remove_file(&probe).unwrap(); + let (from, to) = (source.clone(), target.clone()); + crate::script::dom::BEFORE_CAPTURE_EXPORT.with(|f| *f.borrow_mut() = Some(Box::new(move || std::fs::hard_link(&from, &to).unwrap()))); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&target))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert_eq!(std::fs::read(&source).unwrap(), b"kept"); + assert_eq!(std::fs::read(&target).unwrap(), b"kept", "the late link is left as it was"); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix a destination whose real path is not valid UTF-8 is refused before anything is written, +/// rather than written under a name with its bytes replaced. +#[cfg(unix)] +#[test] +fn capture_refuses_a_destination_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt; + let base = folder("non-utf8"); + let (mut s, dir) = capture_doc(&base); + let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd\xff")); + if std::fs::create_dir(&odd).is_err() { + // The volume refuses names that are not UTF-8. + let _ = std::fs::remove_dir_all(base); + return; + } + // A link with a UTF-8 name that leads into the folder whose name is not. + let link = dir.join("plain"); + std::os::unix::fs::symlink(&odd, &link).unwrap(); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&link.join("x.png")))); + assert!(e.contains("not valid UTF-8"), "{e}"); + assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing written"); + assert!(!dir.join("odd\u{fffd}").exists(), "nothing written under the replaced name"); + let _ = std::fs::remove_dir_all(base); +} + +/// On macOS, whose volumes look names up in either Unicode normalization form, a missing linked +/// file's name in the other form is the linked file. +#[cfg(target_os = "macos")] +#[test] +fn capture_to_a_missing_links_name_in_the_other_normalization_form_writes_nothing() { + let base = folder("missing-nfd"); + let (mut s, dir) = capture_doc(&base); + s.active_mut().unwrap().path = Some(dir.join("doc.vectorcraft").to_string_lossy().into_owned()); + // The link's name is composed (NFC); the capture names it decomposed (NFD). + place_linked( + &mut s, + "cafe", + vectorcraft_doc::LinkInfo { path: "caf\u{e9}.png".into(), relative: Some("caf\u{e9}.png".into()), ..Default::default() }, + ); + let nfd = dir.join("cafe\u{301}.png"); + let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}), [0, 300, 50, 250]);", quoted(&nfd))); + assert!(e.contains("cannot write over an open document"), "{e}"); + assert!(!nfd.exists() && !dir.join("caf\u{e9}.png").exists(), "nothing written"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn capture_denied_or_source_path_writes_nothing() { let base = folder("denied"); @@ -812,11 +917,15 @@ fn capture_to_a_missing_links_path_writes_nothing() { } else { script(&mut s, &base, &text); assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); - // Two names for one file that differ only in case show that the folder keeps case. + // Two names for one file that differ only in case show that the folder keeps case. A + // volume without hard links skips this part. let sub = dir.join("sub"); std::fs::create_dir(&sub).unwrap(); std::fs::write(sub.join("probe.txt"), b"x").unwrap(); - std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); + if std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).is_err() { + let _ = std::fs::remove_dir_all(base); + return; + } s.edit("Place", |d, _| { let id = d.alloc_id(); let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); diff --git a/docs/mcp.md b/docs/mcp.md index e57e827b60..04d3ee75f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3946,8 +3946,8 @@ through `$`: a locked layer or group or on a locked artboard, and one that is hidden or in a hidden layer or group throw an error, and nothing changes. An object containing locked descendants also throws an error, as do objects whose nearest clip group or clipped layer is not the same one (or none for all). - Clip dimensions within floating-point error of a whole pixel use that whole pixel count; other fractional - dimensions round up. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. + In `rasterize`, clip dimensions within floating-point error of a whole pixel use that whole pixel count, and other + fractional dimensions round up. `imageCapture` rounds each dimension to the nearest whole pixel. `rasterize` and `imageCapture` send command warnings to the Script Console with the method name. `rasterize` keeps the selection, less the art it replaces. With `clippingMask` the `RasterItem` is the image inside its clip group. `transparency` wins over `backgroundBlack`, and `padding` takes 0 to 1,000 points. `convertSpotColors`, `convertTextToOutlines` and `includeLayers` true throw an From ced550ebef33475e1c6d00255300d0289ffb8e2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:34:57 -0800 Subject: [PATCH 454/533] Scripts: path points of other Global Edit members go stale when Global Edit changes them While Global Edit is on, an object model edit of one member (or a move of a group that holds it) is given to the other members, but the check that marks read PathPoint handles stale only looked at the edited object's own subtree. A script that read a point of another member kept a valid handle after the edit, even when an undo then put the member back. The check now also looks at each Global Edit member, or the outermost Objects on Path group that holds it, and skips subtrees the command left as they were. The stale-point check came in with #9288. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/paths.rs | 26 ++++++--- crates/engine/src/tests/script_dom_paths.rs | 65 +++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 88 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index cb23b429b0..752b8ea5b1 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1375,7 +1375,8 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// [`see_points`] for each path whose points the run has read, after each command, so that a /// change that a later command reverses still makes the points stale. Paths under the object that /// the object model is changing ([`super::State`]), or that object itself, take the change as the -/// object model's own, and their points stay valid. A document that is the one the run last looked +/// object model's own, and their points stay valid; the other Global Edit members, which take the +/// object model's edit too, are looked at as well. A document that is the one the run last looked /// at is skipped, as are its paths. pub(super) fn see_all_points(h: &super::Host) { let keys: Vec<(u64, u64)> = { @@ -1384,18 +1385,27 @@ pub(super) fn see_all_points(h: &super::Host) { let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); docs.retain(|uid, before| { - let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + let state = s.documents().iter().find(|d| d.uid == *uid); + let after = state.map(|st| &st.doc); if after.is_some_and(|after| Arc::ptr_eq(before, after)) { return true; } // Editing a path in an Objects on Path group can move the other paths in the group, so - // the outermost such group is looked at in place of the path. + // the outermost such group is looked at in place of the path. While Global Edit is on, + // an edit of the selected member (also one made by moving a group that holds it) is + // given to the other members, so each of them, or the outermost Objects on Path group + // holding it, is looked at too. Subtrees the command left as they were are skipped. let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { Some(item) => { - let group = before - .ancestry(item.id) - .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))); - node_arc(before, group.unwrap_or(item.id)).into_iter().collect() + let root = |id: NodeId| { + before + .ancestry(id) + .and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))) + .unwrap_or(id) + }; + let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten(); + let mut roots = std::collections::HashSet::new(); + std::iter::once(item.id).chain(members).map(root).filter(|id| roots.insert(*id)).filter_map(|id| node_arc(before, id)).collect() } None => before.layers.iter().collect(), }; @@ -1417,6 +1427,8 @@ pub(super) fn see_all_points(h: &super::Host) { false } }); + keys.sort_unstable(); + keys.dedup(); keys }; let editing = h.dom.editing.get(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 1e4a123d09..3b44785b3a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1588,6 +1588,71 @@ fn a_point_outside_an_inner_objects_on_path_group_is_stale_after_its_path_change assert_eq!(art(&s), before); } +/// Global Edit gives an edit of one member to the others, so a point read of another member before +/// the edit is stale afterwards, even when an undo puts the member back. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_an_edit_and_undo() { + let (mut s, a, _) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "edit"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]];\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the edit"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, p = P.getByName('edit'), m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + var q = p.pathPoints[0]; q.anchor = [q.anchor[0] - 10, q.anchor[1]]; app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + +/// Moving a group that holds the selected Global Edit member moves the other members too, so a +/// point read of another member before the move is stale afterwards. +#[test] +fn a_point_of_another_global_edit_member_is_stale_after_its_group_moves_and_undoes() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 30.0, 40.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "m"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert_eq!(r["count"], json!(2), "{r}"); + let before = art(&s); + let out = log( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + vc.log(m.pathPoints[0].anchor);\ + app.activeDocument.groupItems[0].translate(10, 0);\ + vc.log(P.getByName('m').pathPoints[0].anchor); app.undo();", + ); + assert_ne!(out[0], out[1], "the other member took the move"); + assert_eq!(art(&s), before); + let e = failure( + &mut s, + "var P = app.activeDocument.pathItems, m = P.getByName('m');\ + var mp = m.pathPoints[0]; mp.anchor;\ + app.activeDocument.groupItems[0].translate(10, 0); app.undo();\ + mp.anchor;", + ); + assert!(e.contains("Stale path point"), "{e}"); + assert_eq!(art(&s), before); +} + /// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. fn doc_with_paints() -> (Session, NodeId) { let (mut s, a, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..c812305400 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3685,7 +3685,9 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. An exception applies when editing another path in an Objects on - Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`. + Path group moves a path inside that group, and when Global Edit changes another member's path points. + Their existing `PathPoint` handles throw `Stale path point`. An appearance-only change, such as a fill change, + leaves the handles valid. Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point, and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 145e117d67..6358be692f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1116,7 +1116,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. From f29cce450d72166477c898fb1857bcbc8eca0a7a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:49:30 -0800 Subject: [PATCH 455/533] Find and Replace: every set lists action, and a click or reopening resets it - A `ui.dialog.set` on the dialog that gives no `action` answers with the dialog as `ui.inspect` lists it, `action` included, instead of the framework's listing without it. - A `fields` list of more than 256 items is refused before `action` is taken out of it, so `action` counts toward the framework's limit. - A click on Find Next, Replace, Replace & Find or Replace All puts `action` back to find, as `ui.dialog.confirm` does. - A test covers these and the reset when the dialog opens again. --- crates/ui-egui/src/dialogs/find_replace.rs | 23 +++++++++----- .../ui-egui/src/dialogs/find_replace/tests.rs | 31 +++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index cb987773ff..52dae1b1a5 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -341,6 +341,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { FindRequest::ReplaceAll { .. } => replace_all(app, &form), _ => return None, }; + // A click presses a button as `ui.dialog.confirm` does: `action` goes back to find. + app.ui.find_action = None; Some(ran.unwrap_or_else(|e| said(&e))) }); report(app, &form, message); @@ -378,6 +380,11 @@ fn take_action(params: &mut Value) -> Result, String> { } let mut only_action = false; if let Some(list) = o.get_mut("fields").and_then(Value::as_array_mut) { + // The framework's limit counts `action` with the other items. + let most = craft::automation::dialogs::MAX_DIALOG_FIELDS; + if list.len() > most { + return Err(format!("`fields` holds {} items; at most {most}", list.len())); + } let is_action = |item: &Value| item.get("field").and_then(Value::as_str) == Some("action"); if let Some(last) = list.iter().rev().find(|item| is_action(item)) { given = Some(last.get("value").cloned().unwrap_or(Value::Null)); @@ -417,10 +424,11 @@ pub(crate) fn show_action(app: &VectorcraftApp, dialogs: &mut Value) { } /// `ui.dialog.set` and `ui.dialog.confirm` (`method`) on the open Find and Replace dialog, when -/// `params.dialog` names it: a set takes the `action` field, and `ui.dialog.confirm`, or a set with +/// `params.dialog` names it: a set takes the `action` field and answers with the dialog as +/// `ui.inspect` lists it, `action` included, and `ui.dialog.confirm`, or a set with /// `action: "confirm"`, presses the button it names (`find` when none is set) and leaves `action` at -/// `find` again. Every other request is the host's, as is a set that gives no `action` field and -/// does not confirm: `None`. +/// `find` again. Every other request is the host's, as is a set with `action: "cancel"` that gives +/// no `action` field: `None`. pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Option> { if !matches!(method, "ui.dialog.set" | "ui.dialog.confirm") { return None; @@ -452,14 +460,13 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, metho Some(Some("cancel")) => false, Some(_) => return Some(Err("`action` must be confirm or cancel".into())), }; - if given.is_none() && !confirm { - return None; - } if let Err(e) = craft::automation::protocol::Params(¶ms).only(None, keys) { return Some(Err(e)); } - // The other fields are set first, all or none, as the host sets and checks them. - let sets = ["field", "value", "fields"].iter().any(|k| params.get(k).is_some()); + // The other fields are set first, all or none, as the host sets and checks them. A set that + // gives no `action` and does not confirm goes to the host's setter whole, which refuses one + // with nothing to set. + let sets = ["field", "value", "fields"].iter().any(|k| params.get(k).is_some()) || (given.is_none() && !confirm); if sets && let Some(Err(e)) = dialogs.with(|host| craft::automation::dialogs::dialog_method(host, ctx, "ui.dialog.set", ¶ms)) { return Some(Err(e)); } diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 81e550c77a..9c7e5f122d 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -198,6 +198,37 @@ fn an_action_that_names_no_button_is_refused() { assert!(is_open(&p)); } +/// A set of other fields answers with `action` listed. A click on a button, like a confirm, puts +/// `action` back to find, and so does opening the dialog again. A `fields` list of more than 256 +/// items is refused, `action` counted with the rest. +#[test] +fn action_is_listed_and_goes_back_to_find() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + set_action(&p, "replace"); + let shown = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat"})).unwrap(); + assert_eq!((shown["fields"]["find"].clone(), shown["fields"]["action"].clone()), (json!("cat"), json!("replace"))); + assert!(control(&p, "ui.dialog.set", json!({"dialog": "top"})).is_err(), "a set with nothing to set"); + + let mut fields = vec![json!({"field": "find", "value": "cat"}); 256]; + fields.push(json!({"field": "action", "value": "replaceAll"})); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})); + assert_eq!(r, Err("`fields` holds 257 items; at most 256".to_string())); + assert_eq!(listed_action(&p), json!("replace")); + + p.click("Find Next"); + assert_eq!(listed_action(&p), json!("find"), "a click"); + + set_action(&p, "replace"); + control(&p, "ui.dialog.cancel", json!({"dialog": "top"})).unwrap(); + assert!(!is_open(&p)); + choose(&p); + p.frame(); + assert_eq!(listed_action(&p), json!("find"), "opening again"); +} + #[test] fn a_cached_match_cannot_replace_text_restored_by_revert() { let (mut app, ids) = app_with(&["Needle Needle"]); From 3d69c8d49ac66a54652ff08053a12049d465d348 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:54:26 -0800 Subject: [PATCH 456/533] Scripts: removeAll cannot leave an image first in a group named Image Trace textFrames.removeAll() and the removeAll() of a group's pageItems, groupItems and compoundPathItems checked only clip groups whose mask they release. Deleting the type or art below an image in an ordinary group named Image Trace left the image first, so the group was read as a tracing and the image dropped out of pageItems. Both now throw "Only Image Trace can make a tracing" and delete nothing, checking the whole set being deleted at once. --- crates/engine/src/script/dom.rs | 13 +++++ crates/engine/src/script/dom/layers.rs | 4 ++ crates/engine/src/script/dom/text.rs | 3 +- crates/engine/src/tests/script_dom_tracing.rs | 51 +++++++++++++++++++ docs/mcp.md | 4 +- 5 files changed, 73 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4d87c3b8a8..2ad7469dbb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3049,6 +3049,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> } } +/// Whether deleting every object in `removed` together would leave one of their parents, an +/// ordinary group named as a tracing, with an image first in it, which would make it a tracing. +pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool { + let going: std::collections::HashSet = removed.iter().copied().collect(); + let mut parents: Vec = removed.iter().filter_map(|i| d.parent_of(*i)).collect(); + parents.sort_unstable_by_key(|p| p.0); + parents.dedup(); + parents + .into_iter() + .filter(|p| named_as_tracing(d, *p)) + .any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 0b1b1f0e57..3f40ad4c11 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -855,6 +855,10 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" ))); } + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 6237af9179..b14b065c84 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1542,7 +1542,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { // Type that clips a group or layer releases its mask, so the object above it is not made // the clipping path. let released = super::masks_cleared_by(&st.doc, &ids); - let tracing = super::release_makes_tracing(&st.doc, &released, &ids); + // So would deleting the type above an image in an ordinary group named as a tracing. + let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids); Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 0f6851d342..403510d73c 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1242,6 +1242,57 @@ fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tr let _ = std::fs::remove_dir_all(base); } +/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing +/// refuse to leave an image first in it, before the document changes, and delete when another +/// object stays first. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("remove-all-trace-name"); + let refused = json!("Only Image Trace can make a tracing"); + for (under, call) in [ + ("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"), + ("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"), + ] { + let (mut s, _) = session(&base, false); + // The group holds the type or group at the bottom and the image above it. + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\ + d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);" + ), + ); + assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}"); + assert_eq!(undo_steps(&s), steps, "{call}"); + assert!(traces(&s).is_empty()); + } + // With a rectangle left first, the type goes and the group stays an ordinary group. + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\ + t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\ + g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);", + ); + assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1abf72fbba..30ac0bfb82 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3246,7 +3246,9 @@ through `$`: delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step, so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they - throw `Only Image Trace can make a tracing` and delete nothing. The `removeAll()` of a layer's or group's + throw `Only Image Trace can make a tracing` and delete nothing. `textFrames.removeAll()` and the `removeAll()` of a + group's `pageItems`, `groupItems` or `compoundPathItems` throw the same error and delete nothing when they would + leave an image at the bottom of an ordinary group named `Image Trace`. The `removeAll()` of a layer's or group's `pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described above. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw From 96ba49f5bd79d0999d1d90dbccf341f4e85ebcb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:09:11 -0800 Subject: [PATCH 457/533] Files: check a write again before it is put in place off Unix Off Unix, write_atomic_checked asked `allowed` once, before the file was written, so a destination that stopped being allowed while the file was filled still received it. The check now runs again after the fill, right before the rename, and again before the content is copied over a file whose folder refuses the rename. A refusal removes the staging file and leaves the target as it was. The hard-link fixtures in the capture tests unwrap the link again, as the other hard-link tests in the engine do (script_io.rs, plugins.rs). --- .../engine/src/tests/script_raster_capture.rs | 14 +-- crates/format/src/atomic.rs | 90 +++++++++++++++++-- 2 files changed, 85 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/tests/script_raster_capture.rs b/crates/engine/src/tests/script_raster_capture.rs index ac12a3e22f..9e0d53c696 100644 --- a/crates/engine/src/tests/script_raster_capture.rs +++ b/crates/engine/src/tests/script_raster_capture.rs @@ -728,11 +728,7 @@ fn capture_refuses_a_file_with_other_hard_links() { let other = dir.join("other.bin"); std::fs::write(&other, b"kept").unwrap(); let alias = dir.join("alias.png"); - if std::fs::hard_link(&other, &alias).is_err() { - // The volume has no hard links. - let _ = std::fs::remove_dir_all(base); - return; - } + std::fs::hard_link(&other, &alias).unwrap(); let e = file_failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.imageCapture(new File({}));", quoted(&alias))); assert!(e.contains("other hard links"), "{e}"); assert_eq!(std::fs::read(&other).unwrap(), b"kept"); @@ -917,15 +913,11 @@ fn capture_to_a_missing_links_path_writes_nothing() { } else { script(&mut s, &base, &text); assert!(upper.exists() && !gone.exists(), "a different file on a volume that keeps case"); - // Two names for one file that differ only in case show that the folder keeps case. A - // volume without hard links skips this part. + // Two names for one file that differ only in case show that the folder keeps case. let sub = dir.join("sub"); std::fs::create_dir(&sub).unwrap(); std::fs::write(sub.join("probe.txt"), b"x").unwrap(); - if std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).is_err() { - let _ = std::fs::remove_dir_all(base); - return; - } + std::fs::hard_link(sub.join("probe.txt"), sub.join("PROBE.TXT")).unwrap(); s.edit("Place", |d, _| { let id = d.alloc_id(); let link = Some(vectorcraft_doc::LinkInfo { path: "sub/gone.png".into(), relative: Some("sub/gone.png".into()), ..Default::default() }); diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..30c55f3cc0 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -265,15 +265,19 @@ pub fn write_atomic_checked( } } -/// See the Unix version. +/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is +/// filled, right before it is put in place; a refusal then removes the temporary file and leaves +/// `path` unchanged. #[cfg(not(unix))] pub fn write_atomic_checked( path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>, - allowed: impl FnOnce(&Path) -> io::Result<()>, + allowed: impl Fn(&Path) -> io::Result<()>, ) -> io::Result<()> { allowed(path)?; - write_atomic_with(path, fill) + let replacing = path.exists(); + let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) }; + write_atomic_staged(path, fill, create, || allowed(path), |tmp, target| std::fs::rename(tmp, target)) } /// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links @@ -404,6 +408,18 @@ fn write_atomic_stepping( fill: impl FnOnce(&mut File) -> io::Result<()>, create: impl FnOnce(&Path) -> io::Result, rename: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result<()> { + write_atomic_staged(path, fill, create, || Ok(()), rename) +} + +/// [`write_atomic_stepping`], with `check` run after the temporary file is filled and right before +/// it is put in place. An error from `check` removes the temporary file and leaves `path` unchanged. +fn write_atomic_staged( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + create: impl FnOnce(&Path) -> io::Result, + check: impl Fn() -> io::Result<()>, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result<()> { let target = resolve_link(path)?; let beside = temp_path(&target)?; @@ -420,7 +436,7 @@ fn write_atomic_stepping( }; let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); - if let Err(e) = filled { + if let Err(e) = filled.and_then(|()| check()) { // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); return Err(e); @@ -435,7 +451,7 @@ fn write_atomic_stepping( e } }; - write_over(&tmp, &target, refused) + write_over(&tmp, &target, refused, &check) } /// The content of `tmp`, which is whole and flushed, copied into `target` itself, and `tmp` @@ -443,8 +459,8 @@ fn write_atomic_stepping( /// writing it is untouched: `tmp` is removed and `refused` returned. When what it holds can't be /// copied aside first ([`keep_old`]) it is untouched too: `tmp` stays and the error names it. When /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the -/// error says where they are. -fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { +/// error says where they are. `check` runs again right before `target` is overwritten. +fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> io::Result<()>) -> io::Result<()> { let old = tmp.with_extension("old"); let over = Over { tmp: &|| tmp.to_path_buf(), @@ -461,7 +477,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { #[cfg(unix)] create_target: &|| create_new(target), synced: &|| sync_written_parent(target), - still_allowed: &|| Ok(()), + still_allowed: check, }; write_over_in(&over, refused) } @@ -1753,6 +1769,64 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A check that refuses after the file is filled keeps the old file, removes the temporary file + /// and tries no rename, whether the folder takes the temporary file or not. + #[test] + fn a_check_refused_after_the_fill_keeps_the_file() { + let d = dir("staged-check"); + let path = d.join("staged-check.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let renamed = std::cell::Cell::new(false); + let rename = |_: &Path, _: &Path| { + renamed.set(true); + Ok(()) + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), |_| denied(), || Err(io::Error::other("moved away")), rename); + assert_eq!(r.unwrap_err().to_string(), "moved away"); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(!renamed.get() && leftovers(&d, "staged-check.vectorcraft").is_empty()); + // A folder that refuses the rename: the check runs again before the file is written over. + let calls = std::cell::Cell::new(0); + let check = || { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("moved away")) } else { Ok(()) } + }; + let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, check, |_, _| denied()); + assert!(r.is_err_and(|e| e.to_string().contains("moved away"))); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "staged-check.vectorcraft").is_empty()); + let staged = format!(".staged-check.vectorcraft.{}-", std::process::id()); + let in_system = std::fs::read_dir(std::env::temp_dir()).unwrap().filter_map(Result::ok); + assert!(!in_system.into_iter().any(|e| e.file_name().to_string_lossy().starts_with(&staged)), "the system's folder keeps no staging file"); + let _ = std::fs::remove_dir_all(&d); + } + + /// Off Unix the check runs again after the file is filled: a refusal at that point keeps the + /// old file and leaves no temporary file. + #[cfg(not(unix))] + #[test] + fn a_checked_write_checks_again_before_the_file_is_put_in_place() { + let d = dir("checked-twice"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + let calls = std::cell::Cell::new(0); + let r = write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |_| { + calls.set(calls.get() + 1); + if calls.get() > 1 { Err(io::Error::other("no longer allowed")) } else { Ok(()) } + }, + ); + assert_eq!(r.unwrap_err().to_string(), "no longer allowed"); + assert_eq!(calls.get(), 2); + assert_eq!(std::fs::read(&path).unwrap(), b"old"); + assert!(leftovers(&d, "doc.vectorcraft").is_empty()); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn write_new_never_replaces_what_is_there() { let d = dir("new"); From f238d59b31decfce1ecd593ddacf6f853a27071d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:20:51 -0800 Subject: [PATCH 458/533] Tests: quote temp paths as script strings in the evalFile refusal tests script_eval_file_outside_scope_refused and script_eval_file_keeps_the_refusal_when_no_uri_form_is_read put the temp folder path into a single-quoted script string without escaping it. A path with an apostrophe, backslash or line break ended the string, and the run failed with a syntax error instead of the refusal under test. The tests now write the path as a JSON-escaped string literal, and their folder names contain an apostrophe so the quoting is exercised. --- crates/engine/src/tests/script_include.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 8c4276cfce..3ab8f8be82 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -24,6 +24,11 @@ fn write(path: &Path, text: &str) { std::fs::write(path, text).unwrap(); } +/// `text` as a quoted script string literal, with its quotes, backslashes and line breaks escaped. +fn js_string(text: &str) -> String { + serde_json::to_string(text).unwrap() +} + /// Runs `main/main.jsx` in `base`, with the text `text`. fn run(base: &Path, text: &str) -> Result { let main = base.join("main/main.jsx"); @@ -443,11 +448,12 @@ fn script_file_name_names_the_file_of_the_code_that_reads_it() { #[test] fn script_eval_file_outside_scope_refused() { - let base = folder("evaloutside"); + // The apostrophe in the folder name would end a quoted script string. + let base = folder("eval'outside"); write(&base.join("outside.jsx"), "1;"); - let absolute = base.join("outside.jsx").to_string_lossy().replace('\\', "/"); + let absolute = js_string(&base.join("outside.jsx").to_string_lossy().replace('\\', "/")); let script = format!( - "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile('{absolute}'); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" + "var out = [];\ntry {{ $.evalFile('../outside.jsx'); }} catch (e) {{ out.push(String(e)); }}\ntry {{ $.evalFile({absolute}); }} catch (e) {{ out.push(String(e)); }}\nvc.log(out);" ); let r = run(&base, &script).unwrap(); let out = r["log"][0].as_array().unwrap(); @@ -466,10 +472,10 @@ fn script_eval_file_outside_scope_refused() { #[cfg(not(windows))] #[test] fn script_eval_file_keeps_the_refusal_when_no_uri_form_is_read() { - let base = folder("evaluri"); + let base = folder("eval'uri"); write(&base.join("out%20side.jsx"), "1;"); let absolute = base.join("out%20side.jsx").to_string_lossy().into_owned(); - let script = format!("try {{ $.evalFile('{absolute}'); }} catch (e) {{ vc.log(String(e)); }}"); + let script = format!("try {{ $.evalFile({}); }} catch (e) {{ vc.log(String(e)); }}", js_string(&absolute)); let r = run(&base, &script).unwrap(); let e = r["log"][0].as_str().unwrap_or_default().to_string(); assert!(e.starts_with(&format!("Error: script file read refused: {absolute}")), "{e}"); From 626994effd3a808d39512b745746f32294cfef68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:25:17 -0800 Subject: [PATCH 459/533] Scripts: a text color assigned in a CMYK document is compared as the document stores it Assigning fillColor or strokeColor on a text range compared the color as given with the paint the characters have. In a CMYK document an RGB color is stored as CMYK, so assigning the RGB color the text already stores ran text.setRangeStyle again and recorded an undo step that changed nothing. The comparison now converts the color through the text's own document (its color mode and color settings), so the same assignment records no step, and text in a background RGB document keeps an RGB color assigned to it. The text paint setters came with #9304. --- crates/engine/src/cmd/newart.rs | 7 +++++ crates/engine/src/script/dom/text.rs | 17 ++++++++--- crates/engine/src/script/dom/text/styles.rs | 2 +- crates/engine/src/tests/script_text.rs | 33 +++++++++++++++++++++ 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index f420054d11..6296b4e302 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -109,6 +109,13 @@ pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcr super::paint::new_color(s, &json!({}), c) } +/// `c` as a paint command without `keepModel` stores it in `d`: an RGB color in a CMYK document +/// becomes CMYK through the document's own color settings ([`super::colormgmt::doc_cms`]). +pub(crate) fn stored_color_in(d: &vectorcraft_doc::Document, c: vectorcraft_color::Color) -> vectorcraft_color::Color { + let model = (d.color_mode != vectorcraft_doc::ColorMode::Rgb).then(|| d.color_mode.model()); + vectorcraft_color::cms::with_active(super::colormgmt::doc_cms(d), || super::paint::stored_color(model, c)) +} + /// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before /// anything changes. fn set_new_art(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index ebfe900ee4..4f4e477979 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -970,8 +970,16 @@ fn stroke_scale(t: &TextObject) -> f64 { vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) } -/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. -fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after in +/// the document `doc` (a color as given when there is none). +fn attr_param( + h: &Host, + attr: Attr, + name: &str, + v: &Data, + first: (&TextObject, &CharStyle, usize), + doc: Option<&vectorcraft_doc::Document>, +) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); Ok(match attr { Attr::Size => { @@ -1040,8 +1048,9 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & } Attr::FillColor | Attr::StrokeColor => { let color = colors::assigned(v, name)?; - let paint = color.map_or(Paint::None, Paint::solid); let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + // The paint reads back as the text's document stores it: an RGB color in a CMYK document as CMYK. + let paint = color.map_or(Paint::None, |c| Paint::solid(doc.map_or(c, |d| crate::cmd::newart::stored_color_in(d, c)))); let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; (json!({ key: given }), colors::of_paint(&paint)) } @@ -1082,7 +1091,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let styles = styles_in(t, ba, bb, false)?; let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); - let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1), Some(&st.doc))?; // A leading set on characters with auto leading fixes it even where auto gives that value. let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 45d1a428f3..af3e9118ea 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -471,7 +471,7 @@ fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let leading = old.get("leading").and_then(Value::as_f64); let sample = CharStyle { size, leading, ..base }; let t = TextObject::point(Point::default(), "", sample.clone()); - let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0), None)?; let mut attrs = old.clone(); for (k, v) in param.as_object().into_iter().flatten() { let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 480779c60c..829bc5770e 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -302,6 +302,39 @@ fn character_attributes_paint_only_their_own_characters() { assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); } +#[test] +fn an_rgb_paint_a_cmyk_document_already_stores_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap(); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red; vc.log(r.fillColor.typename);", + ); + assert_eq!(out[0], json!("CMYKColor"), "the document stores the color as CMYK"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange, red = new RGBColor(); red.red = 255; r.fillColor = red;"); + assert_eq!(undo_steps(&s), steps, "assigning the color the text already stores records no undo step"); +} + +#[test] +fn an_rgb_paint_on_text_in_a_background_rgb_document_is_kept_as_rgb() { + let (mut s, id) = doc_with("abc"); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("text.create", &json!({"x": 20, "y": 100, "text": "abc", "size": 12})).unwrap(); + let out = log( + &mut s, + "var front = app.activeDocument, back = app.documents[0] === front ? app.documents[1] : app.documents[0];\ + var red = new RGBColor(); red.red = 255;\ + var f = front.textFrames[0].textRange, b = back.textFrames[0].textRange;\ + f.fillColor = red; b.fillColor = f.fillColor; b.fillColor = red; vc.log(b.fillColor.typename);", + ); + assert_eq!(out[0], json!("RGBColor"), "the RGB document keeps the RGB color it is given: {out:?}"); + let rgb = s.documents().iter().find(|d| d.doc.color_mode == vectorcraft_doc::ColorMode::Rgb).expect("the RGB document"); + let NodeKind::Text(t) = &rgb.doc.node(id).expect("the RGB document's text").kind else { panic!("not text") }; + assert!(t.runs.iter().all(|r| r.style.fill == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "{:?}", t.runs); +} + #[test] fn stroke_weight_reads_back_in_document_points_on_scaled_type() { let (mut s, id) = doc_with("abc"); From f4ee5e7be3b0103de986d7eefc46a508a30b66be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:26:40 -0800 Subject: [PATCH 460/533] Scripts: match the point write's undo step after the switch to its document Making a background document active can measure its type again and replace the document, so the undo step is now found by the document read after the switch. A test covers a background document whose text is measured again. --- crates/engine/src/script/dom/paths.rs | 39 ++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 4ce08f8116..6ea8fabfc3 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -347,7 +347,7 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { // undoing it selects them again. let mut kept = None; if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { - kept = Some((st.doc.clone(), st.selection.clone())); + kept = Some(st.selection.clone()); let selection = &mut st.selection; if let Some(anchors) = selection.anchors.get_mut(&item.id) { anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); @@ -366,12 +366,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { { selection.remove(item.id); } - if kept.as_ref().is_some_and(|(_, before)| *before == st.selection) { + if kept.as_ref().is_some_and(|before| *before == st.selection) { kept = None; } } - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; - if let Some((doc, selection)) = kept + // The document as the edit's step keeps it, read after the switch to it, which can measure + // its type again. + let doc = super::edit_item_with(h, item, |h| { + let doc = h.session.borrow().active().map(|st| st.doc.clone()); + super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + Ok(doc) + })?; + if let Some((doc, selection)) = doc.zip(kept) && let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) && let Some(step) = st.history.undo.last_mut().filter(|step| Arc::ptr_eq(&step.doc, &doc)) { @@ -2022,6 +2028,31 @@ mod tests { assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); } + #[test] + fn undoing_a_point_write_in_a_background_document_selects_its_anchors_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let text = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap(); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let st = s.document_mut(uid).unwrap(); + let NodeKind::Text(t) = &mut Arc::make_mut(&mut st.doc).node_mut(NodeId(text)).unwrap().kind else { panic!("not a text object") }; + t.cached_bounds = None; + let before_activation = st.doc.clone(); + let source = "var d; for (var i = 0; i < app.documents.length; i++) { if (app.documents[i].pathItems.length) d = app.documents[i]; } \ + d.pathItems[0].setEntirePath([[0, 0], [10, 0], [10, 10]]); app.activeDocument = d; app.undo();"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + let id = NodeId(id.as_u64().unwrap()); + let st = s.documents().iter().find(|d| d.uid == uid).unwrap(); + assert!(!Arc::ptr_eq(&st.doc, &before_activation)); + assert!(matches!(&st.doc.node(NodeId(text)).unwrap().kind, NodeKind::Text(t) if t.cached_bounds.is_some())); + assert_eq!(st.doc.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].anchors.len()), Some(4)); + let anchors: Vec<(usize, usize)> = st.selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default(); + assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed"); + } + #[test] fn a_made_id_above_two_to_the_53_stays_exact() { let made = |v: Value| made_id(&(Data::Undefined, v)); From 5e68ecd7c8c9d438a82f4f22f9b59b1f34cc25f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:39:52 -0800 Subject: [PATCH 461/533] macOS: closing Preferences no longer crashes on Macs with a Touch Bar Clicking OK or Cancel in Preferences ended the app with an uncaught NSRangeException from -[_NSTouchBarFinderObservation invalidate] whenever the Touch Bar server runs (any Mac with a Touch Bar). When a window closes, accesskit_macos 0.27.1 put the content view's original class back, which removed the key-value observing subclass AppKit's Touch Bar support had installed on the view. AppKit then failed to remove its observer. accesskit_macos 0.27.2 leaves the class alone when key-value observing has subclassed the view (AccessKit/accesskit#835). Cargo.lock moves to it, with accesskit 0.25.2 and accesskit_consumer 0.39.2, which it requires. Fixes #10473 --- Cargo.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..ff70d04bdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] @@ -27,9 +27,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", From 4e90d6c21114cdf1b422b1ca5e5d6fc23044a3fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:09:32 -0800 Subject: [PATCH 462/533] Scripts: same_folder builds without a needless bool on Windows On Windows the Unix block in same_folder is compiled out, which left `if a == b { return true; } false` and failed clippy's needless_bool lint with -D warnings in the Windows CI run. The early return now sits inside the Unix block and the other platforms compare the paths. Behavior is unchanged on every platform. --- crates/engine/src/script/dom/raster_capture.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 36fec48381..38c8eb5437 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -386,17 +386,21 @@ thread_local! { /// file number, so a path spelled in another letter case on a volume that ignores case still /// matches. On Windows a real path carries the letter case stored on disk. fn same_folder(a: &std::path::Path, b: &std::path::Path) -> bool { - if a == b { - return true; - } #[cfg(unix)] { use std::os::unix::fs::MetadataExt; + if a == b { + return true; + } if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { return x.dev() == y.dev() && x.ino() == y.ino(); } + false + } + #[cfg(not(unix))] + { + a == b } - false } /// Whether two existing paths name one file on disk, such as two hard links to it: the same device From c738e2e6aa2e682633740801259bca5ac36bb7e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:10:08 -0800 Subject: [PATCH 463/533] Recolor: Save Changes leaves excluded rows' color, swatch and tint as they are bake_adjust gave every row the Global Adjust and, with no library limit, removed every row's picked swatch and tint, excluded rows included. An excluded row recolors no art, so it now keeps its new color, swatch and tint, and the other rows still take the adjustment. --- crates/ui-egui/src/dialogs/recolor.rs | 21 +++++++++++++++++++-- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index b20b261c90..fc36ef76af 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -64,7 +64,8 @@ //! Swatches panel shows. When the art has colors of the group, Save Changes keeps the group's //! swatches in order: a swatch whose color a row lists takes that row's new color (its own color //! when the row is excluded), and every other swatch keeps its color. After a save with art the -//! rows' new colors take the Global Adjust, which goes back to 0%. When the save recolors art +//! rows' new colors take the Global Adjust, which goes back to 0%; an excluded row keeps its new +//! color, swatch and tint. When the save recolors art //! linked to the group's global swatches, the rows are read from the art again (a color the save //! gave the art is excluded, and a color the art had before keeps its row's new color). Until the //! rows or the Global Adjust change, OK changes the saved group only by its name. After a Delete @@ -931,7 +932,8 @@ fn bake_adjust(app: &VectorcraftApp, d: &mut Fields) { } let mut rs = rows(d); let suppresses_links = d.str("limitTo").is_empty(); - for r in &mut rs { + // An excluded row recolors no art, so it keeps its new color, swatch and tint. + for r in rs.iter_mut().filter(|r| !excluded(r)) { if to_color(r).is_some() && let Some(c) = group_colors(app, d, std::iter::once(&*r)).into_iter().next() { @@ -4944,6 +4946,21 @@ mod tests { assert_eq!(new_shown(&app, &d, &links, &row), red); } + /// Save Changes bakes the Global Adjust into the rows that recolor art only: an excluded row + /// keeps its new color, its picked swatch and its tint. + #[test] + fn baking_the_global_adjust_leaves_excluded_rows_as_they_are() { + let app = app(100); + let row = json!({"from": ["rgb 128 128 128"], "to": "cmyk 0 100 0 0", "swatch": {"name": "Ink", "library": "document"}, "tint": 40.0, "exclude": true}); + let mut d = Fields::new( + json!({"globalAdjust": {"brightness": -50}, "limitTo": "", "rows": [row.clone(), {"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}]}), + ); + bake_adjust(&app, &mut d); + let rs = super::rows(&d); + assert_eq!(rs[0], row, "the excluded row is unchanged: {}", rs[0]); + assert_ne!(rs[1]["to"], json!("rgb 255 0 0"), "the other row takes the adjustment: {}", rs[1]); + } + /// A row picked from a global process swatch shows the swatch's own color, which the art takes, /// not the row's color key, which rounds it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ce203a3080..f4efaf929d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6930,7 +6930,7 @@ before an excluded row or one that removes the color, as `recolor.apply` maps th a row's new color, takes that row's new color (its own color when the row is excluded), so art linked to the swatch takes the color its row shows, and every other swatch keeps its color. A row whose color was removed (`to: null`) and is not excluded removes its swatch, and the colors added on the Edit tab follow the group's other colors, as at OK. After a `save` with art, the rows' new colors take the Global -Adjust and it goes back to 0%; when the save recolored linked art, the rows are read from the art again and a row with a +Adjust and it goes back to 0% (an excluded row keeps its new color, swatch and tint); when the save recolored linked art, the rows are read from the art again and a row with a color the save gave the art is excluded, also when other art has that color, since a row recolors every use of its colors alike. Until the rows or the Global Adjust change, OK changes the saved group only by the name in `groupName`. `save` and `delete` with no group selected answer `` missing `group` ``. `save` on a group with a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50e50869b9..225e1c3f0c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2191,7 +2191,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. + - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%, and an excluded row keeps its new color, swatch and tint. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list for a row of the selected art stays that swatch, unless an earlier solid swatch (other than a linked tint) in the same library has the same name and color, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. From 7b51b005eb759473b97a73d58192e490df89f2e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:15:40 -0800 Subject: [PATCH 464/533] CSS Properties: evenly spaced round dots are a dotted border without a note A stroke of evenly spaced round dots (round cap, a zero-length dash, one gap length, not fitted to corners) is written as `border: ... dotted`, but the rule also carried the "arrowheads, width profiles, brushes or dashes fitted to corners" note, and with rasterize on it got a picture as well. Such a stroke no longer raises that note. Projecting caps, dots fitted to corners, dots mixed with dashes and unevenly spaced dots keep it. A gradient border is written with `border-image`, which replaces the border's style, so its dots or dashes are lost. A dotted or dashed gradient border now carries the note "dashes or dots on a gradient border". --- crates/engine/src/tests/css.rs | 28 ++++++++++++++++++++++++++++ crates/svg/src/css.rs | 19 +++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/css.rs b/crates/engine/src/tests/css.rs index 39fb6a5bc2..a6bb174d28 100644 --- a/crates/engine/src/tests/css.rs +++ b/crates/engine/src/tests/css.rs @@ -43,6 +43,34 @@ fn a_rounded_rectangle_gives_background_border_and_radius() { assert!(s.execute("css.selection", &json!({"units": "furlong"})).is_err(), "unknown units are refused"); } +#[test] +fn round_dots_are_a_dotted_border_without_a_note() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 120, "height": 60})); + run(&mut s, "paint.setStroke", json!({"color": "#000000"})); + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4]})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border: 1px dotted #000000;"), "{}", css(&r)); + assert!(r["rules"][0].get("unsupported").is_none(), "{r}"); + // Squares, dots fitted to corners, dots mixed with dashes and unevenly spaced dots are not what + // `dotted` draws. + let others = [json!({"cap": "projecting"}), json!({"alignDashes": true}), json!({"dash": [0, 4, 6, 4]}), json!({"dash": [0, 4, 0, 40]})]; + for p in others { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": [0, 4], "alignDashes": false})); + run(&mut s, "stroke.set", p.clone()); + let r = run(&mut s, "css.selection", json!({})); + assert!(r["rules"][0].get("unsupported").is_some(), "{p}: {r}"); + } + // A gradient border image draws the border whole, without its dots or dashes. + run(&mut s, "paint.setStroke", json!({"gradient": {"kind": "linear"}})); + for dash in [json!([0, 4]), json!([4, 2])] { + run(&mut s, "stroke.set", json!({"cap": "round", "dash": dash, "alignDashes": false})); + let r = run(&mut s, "css.selection", json!({})); + assert!(css(&r).contains("border-image: linear-gradient("), "{}", css(&r)); + assert_eq!(r["rules"][0]["unsupported"], json!("dashes or dots on a gradient border"), "{dash}"); + } +} + #[test] fn type_gives_font_properties_and_gradients_css_gradients() { let mut s = session(); diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 76069d802a..d37715f9b9 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -539,8 +539,11 @@ impl Rules<'_> { /// A stroke as a border: weight, style (dashed; dotted for round dots) and colour. fn border(&mut self, s: &StrokeLayer, bounds: Rect, art: &mut Art) { - // Aligned strokes still draw as borders; arrowheads, profiles, brushes and fitted dashes don't. - if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, ..s.clone() }) { + // Aligned strokes still draw as borders, and evenly spaced round dots as `dotted`; + // arrowheads, profiles, brushes and fitted dashes don't. + let dots = s.dash.as_ref().is_some_and(|d| d.is_dashed() && s.cap == LineCap::Round && !d.align_corners && even_dots(&d.pattern)); + let dash = if dots { None } else { s.dash.clone() }; + if !vectorcraft_effects::stroke::is_plain(&StrokeLayer { align: StrokeAlign::Center, dash, ..s.clone() }) { art.unsupported("arrowheads, width profiles, brushes or dashes fitted to corners"); } let style = match &s.dash { @@ -553,6 +556,11 @@ impl Rules<'_> { Paint::Solid { color, .. } => art.props.push(("border", format!("{width} {style} {}", color_css(color, s.opacity)))), Paint::Gradient(g) => match self.gradient(g, s.paint_bounds(bounds), s.opacity) { Some(css) => { + // A border image takes the place of the border's style + // (https://www.w3.org/TR/css-backgrounds-3/#border-images). + if style != "solid" { + art.unsupported("dashes or dots on a gradient border"); + } art.props.push(("border", format!("{width} {style}"))); art.props.push(("border-image", format!("{css} 1"))); } @@ -803,6 +811,13 @@ fn corners(path: &PathData, live: Option<&LiveShape>) -> Option { } } +/// Whether `pattern` (dash, gap, dash, gap…) draws evenly spaced dots: every dash has zero length +/// and every gap is the same. An odd-length pattern repeats with dashes and gaps swapped, so its +/// dashes can't all be zero unless the whole pattern is. +fn even_dots(pattern: &[f64]) -> bool { + pattern.len().is_multiple_of(2) && pattern.chunks(2).all(|c| c.first() == Some(&0.0) && c.get(1) == pattern.get(1)) +} + /// One closed subpath of four straight sides along the axes. fn is_upright_rectangle(path: &PathData) -> bool { let ([sp], Some(b)) = (path.subpaths.as_slice(), path.bounds()) else { return false }; From 4ada69770b9bc19a49775c9414058454070c4b1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 00:34:07 -0800 Subject: [PATCH 465/533] Scripts: pathItems.removeAll deletes a clipping path when visible text still clips A group that clips by a mask holding a path and a text object keeps clipping by the text's outlines after the path is deleted, so Document.pathItems.removeAll() no longer refuses that case. Hidden text and hidden subgroups do not clip, so a mask left with only those still refuses. docs/mcp.md describes the rule. --- crates/engine/src/script/dom/paths.rs | 6 ++- crates/engine/src/tests/script_dom.rs | 63 +++++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 7a1929aa43..40db503d05 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -540,7 +540,7 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or /// layer that keeps other objects, or a compound path or group that clips one and would be left -/// empty. +/// with no visible path or text. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); @@ -579,7 +579,9 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if kids.iter().any(|k| affected.contains(&k.id)) { affected.insert(n.id); } - if (matches!(n.kind, NodeKind::Path { .. }) && !going.contains(&n.id)) || kids.iter().any(|k| geometry.contains(&k.id)) { + if (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Text(_)) && n.visible && !going.contains(&n.id)) + || kids.iter().any(|k| k.visible && geometry.contains(&k.id)) + { geometry.insert(n.id); } if n.clips() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 042adfd88f..ab0772e2ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3421,6 +3421,69 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { assert_eq!(undo_steps(&s), steps); } +/// A clipping group of a path and text keeps the text's glyph outlines when the document's +/// `pathItems.removeAll()` deletes the path, so the paths are deleted. +#[test] +fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keeps_text() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(outer).unwrap().clips()); + assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out, [json!(""), json!(0)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none()); + assert!(d.node(t).is_some()); + assert!(d.node(kept).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + +/// Hidden text in a clipping group does not clip, so the document's `pathItems.removeAll()` +/// refuses to delete the group's only visible clipping path. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c71bb57245..8eb344964e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3235,7 +3235,8 @@ through `$`: and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document. `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group - or layer that keeps other objects. `remove()` on an object that + or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that + clips when a text object in that group stays, because the text then clips. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` From 164a9ec05f916140c06d0d1a0c768738f954f1e5 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:22:02 +0530 Subject: [PATCH 466/533] Artboards: avoid duplicate lock submenu rows --- crates/ui-egui/src/menus/context.rs | 5 +++- crates/ui-egui/src/panels/artboards/tests.rs | 4 +-- crates/ui-egui/src/tests/contextmenu.rs | 27 ++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index d94e4feef4..3ecff4863f 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -252,7 +252,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec { .collect(); let unlock: Vec = [entry("Unlock Selected", sel.clone(), false), entry("Unlock All", (0..n).collect(), false)].into_iter().flatten().collect(); - for (label, items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + for (label, mut items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] { + // The selected and unselected targets are disjoint. If All matches a narrower row, it + // is adjacent to it after empty rows are removed. Keep the narrower row for that command key. + items.dedup_by(|a, b| matches!((a, b), (Node::Item(a), Node::Item(b)) if a.command == b.command)); if !items.is_empty() { v.push(sub(label, items)); } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 2359a17bae..32fb3d451f 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -1176,8 +1176,8 @@ fn the_artboard_tools_lock_entries_have_something_to_change() { Some(sub) => menu_labels(children_of(sub)), None => vec![], }; - assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected", "Lock All"], "the selected artboard is locked already"); - assert_eq!(subs("Unlock Artboards"), ["Unlock Selected", "Unlock All"]); + assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected"], "only the unselected artboard can be locked"); + assert_eq!(subs("Unlock Artboards"), ["Unlock Selected"], "only the selected artboard can be unlocked"); } /// A right-click on an artboard that isn't selected selects it alone; on a selected one the selection diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index ad11b25441..24d06187c5 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -614,12 +614,17 @@ fn every_context_label_is_a_menu_string() { app.ui.context_spelling = None; // The Lock Artboards and Unlock Artboards submenus of the Artboard tool. app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 80})).unwrap(); + app.run("artboard.new", json!({"x": 520, "y": 0, "width": 100, "height": 80})).unwrap(); app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap(); app.select_tool("artboard"); shown.extend(labels(&app)); // Lock Selected with the artboard that isn't locked active. crate::panels::artboards::select(&mut app, 1); shown.extend(labels(&app)); + // Unlock All has its own target when another locked artboard is outside the selection. + app.run("artboard.setProps", json!({"index": 2, "locked": true})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + shown.extend(labels(&app)); let missing: Vec<_> = shown.iter().filter(|l| !strings.contains(l.as_str())).collect(); assert!(missing.is_empty(), "context menu labels missing from menu_strings: {missing:?}"); for label in menus::CONTEXT_LABELS { @@ -681,6 +686,28 @@ impl CanvasMenu { } } +#[test] +fn single_artboard_lock_submenus_open_and_apply_the_available_action() { + let mut app = app(); + app.select_tool("artboard"); + let mut canvas = CanvasMenu::new(app); + for (submenu, action, equivalent, locked) in + [("Lock Artboards", "Lock Selected", "Lock All", true), ("Unlock Artboards", "Unlock Selected", "Unlock All", false)] + { + canvas.right_click(100.0, 100.0); + let row = canvas.fixture.by_label(submenu).expect("the canvas offers the artboard submenu"); + canvas.frame(vec![Event::PointerMoved(row.center())]); + canvas.fixture.advance(1.0); + canvas.frame(vec![]); + + let row = canvas.fixture.by_label(action).expect("the submenu shows the action for the selected artboard"); + assert!(canvas.fixture.by_label(equivalent).is_none(), "the same action has only one row"); + canvas.fixture.click(&row); + canvas.frame(vec![]); + assert_eq!(canvas.app.borrow().session.active().unwrap().doc.artboards[0].locked, locked); + } +} + #[test] fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..7bca51829f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11700,7 +11700,8 @@ every artboard, and Lock All Except Selected acts on the artboards that are not that is not selected first selects it alone. An entry that cannot run is left out: Cut with a locked artboard or every artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Fit to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected artboard to change, -and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and +and a lock entry with no artboard to change. When two lock or unlock entries would change the same artboards, the +menu shows the more specific action. The menu measures the art for Delete Empty Artboards and Fit to Artwork Bounds once, at the right-click. Paste centers copied artboards on the right-click's point (`edit.paste {artboardsAt: [x, y]}`) and centers copied objects there too (`center`). Chosen from a menu or the command palette with the tool in use, `artboard.new` makes the new artboard active, `artboard.duplicate` selects the copies, From ec943eebf7dfa14576e4589991e8b2f84ca2e4b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:02:12 -0800 Subject: [PATCH 467/533] Tabs: an unentered X, Leader or Align On value stays with its stop A value typed in the Tabs panel's X, Leader or Align On field and not yet entered was kept when the selection changed to other text, or the ruler picked another stop, whose stop held the same value. Enter then set the stop of the new target. Each field now has an edit target made of the document, the selection, the Type tool's range, the text and paragraph shown and the picked stop, so the typed value is dropped when any of them changes. --- crates/ui-egui/src/panels/tabs.rs | 24 +++++- crates/ui-egui/src/panels/tabs/tests.rs | 101 ++++++++++++++++++++++++ 2 files changed, 122 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index fbea360c43..56c1362911 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -344,6 +344,19 @@ fn shown_paragraph(app: &VectorcraftApp, t: &TextObject) -> usize { super::character::text_editing(app).map_or(0, |(_, a, _)| t.paragraphs_in(a, a).start) } +/// The edit target of the panel's fields for text `n`: the active document and its reverts, the +/// selected objects, the Type tool's range, and the text and paragraph whose stops the panel shows. +/// A value typed in a field is dropped when this changes before it is entered, so it does not set +/// the stops of other text, even text whose stop holds the same values. +fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { + let para = match &n.kind { + NodeKind::Text(t) => shown_paragraph(app, t), + _ => 0, + }; + let document = app.session.active().map(|st| (st.uid, st.reverts, &st.selection.objects)); + egui::IdSalt::new((document, super::character::text_editing(app), n.id, para)) +} + /// [`above_text`], then note the active document and text `n`. A floating panel is /// at least [`crate::panel_docking::PANEL_MIN_WIDTH`] wide, so for narrow text at a low zoom the /// panel comes out wider than asked; the ruler then draws text `n` at [`screen_scale`] and runs @@ -722,6 +735,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let vertical = matches!(&node.kind, NodeKind::Text(text) if text.vertical); + let edited = edited_paragraph(app, &node); let targets = indent_targets(app, &node); let mixed_left = targets.iter().any(|p| p.left != para.left_indent); let panel = &mut app.ui.tabs_panel; @@ -763,7 +777,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let label = if vertical { tl!("Y:") } else { tl!("X:") }; let x = marker.map_or_else(|| stops.get(stop).map(|s| s.position), |item| picked_position(item, ¶, span)); let typed = Field::new(label) - .show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).show(ui)) + .show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).edit_target((edited, stop, marker)).show(ui)) .inner .and_then(|out| out.edit.events.committed().copied().flatten()); if let Some(value) = typed { @@ -773,7 +787,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let on_stop = marker.is_none() && stop < stops.len(); let leader = stops.get(stop).filter(|_| marker.is_none()).map(|s| s.leader.clone()).unwrap_or_default(); let typed = Field::new(tl!("Leader:")) - .show(ui, |ui, _| TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).show(ui)) + .show(ui, |ui, _| { + TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).edit_target((edited, stop)).show(ui) + }) .inner .and_then(|out| out.events.committed().cloned()); if let (Some(leader), Some(s)) = (typed, stops.get_mut(stop)) { @@ -784,7 +800,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let decimal = marker.is_none() && stops.get(stop).is_some_and(|s| s.align == TabAlign::Decimal); let on = stops.get(stop).map_or_else(|| ".".to_string(), |s| s.align_on.to_string()); let typed = Field::new(tl!("Align On:")) - .show(ui, |ui, _| TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).show(ui)) + .show(ui, |ui, _| { + TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).edit_target((edited, stop)).show(ui) + }) .inner .and_then(|out| out.events.committed().and_then(|text| text.chars().next())); if let (Some(c), Some(s)) = (typed, stops.get_mut(stop)) { diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index a30cf7b559..e0afadbd66 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1094,3 +1094,104 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() { assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); } } + +/// An app with area texts that each have decimal stops, aligned on a period with no leader, at +/// `positions`, and the first text selected. → the app and the texts' ids. +fn decimal_stops_app(texts: usize, positions: &[f64]) -> (VectorcraftApp, Vec) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let stops: Vec<_> = positions.iter().map(|p| json!({"position": p, "align": "decimal"})).collect(); + let ids: Vec = (0..texts) + .map(|i| { + let y = 20.0 + 80.0 * i as f64; + let id = app.run("text.create", json!({"x": 10, "y": y, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": stops})).unwrap(); + id + }) + .collect(); + app.run("select.set", json!({"ids": [ids[0]]})).unwrap(); + (app, ids) +} + +/// The stops of the first paragraph of text `id` as (position, leader, align on). +fn stops_of(app: &VectorcraftApp, id: u64) -> Vec<(f64, String, char)> { + text_of(app, id).para_at(0).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect() +} + +/// Selects all of the focused field's text, types `text` and leaves it unentered. +fn draft(panel: &mut crate::tests::panel_harness::Panel, label: &str, role: craft::ui::contract::Role, text: &str) { + panel.click_role(label, role); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); +} + +/// A value typed in the X, Leader or Align On field and not yet entered is dropped when the +/// selection moves to another text whose stop holds the same values: Enter then leaves both texts' +/// stops as they were. A value typed for the newly selected text still sets its stop. +#[test] +fn a_field_value_typed_before_the_selection_changes_does_not_reach_the_new_text() { + use craft::ui::contract::Role; + for (label, role, typed) in [("X:", Role::SPIN_BUTTON, "70"), ("Leader:", Role::TEXT_INPUT, "-"), ("Align On:", Role::TEXT_INPUT, ",")] { + let (app, ids) = decimal_stops_app(2, &[40.0]); + let (a, b) = (ids[0], ids[1]); + let before = stops_of(&app, a); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, label, role, typed); + panel.app().run("select.set", json!({"ids": [b]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for id in [a, b] { + assert_eq!(stops_of(&panel.app(), id), before, "{label} {typed:?} typed for text {a}, entered after selecting text {b}: text {id}"); + } + draft(&mut panel, label, role, typed); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), a), before, "{label} {typed:?} typed for text {b}: text {a}"); + assert_ne!(stops_of(&panel.app(), b), before, "{label} {typed:?} typed for text {b} sets its stop"); + } +} + +/// A Leader value typed with two texts selected and not yet entered is dropped when the selection +/// changes to the first text and a third one: the panel still shows the first text, but Enter +/// would set every selected text's stops. +#[test] +fn a_field_value_typed_before_other_texts_join_the_selection_does_not_reach_them() { + let (app, ids) = decimal_stops_app(3, &[40.0]); + let before = stops_of(&app, ids[0]); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.app().run("select.set", json!({"ids": [ids[0], ids[1]]})).unwrap(); + draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-"); + panel.app().run("select.set", json!({"ids": [ids[0], ids[2]]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for &id in &ids { + assert_eq!( + stops_of(&panel.app(), id), + before, + "Leader typed for texts {} and {}, entered after selecting {} and {}: text {id}", + ids[0], + ids[1], + ids[0], + ids[2] + ); + } +} + +/// A Leader or Align On value typed for one stop and not yet entered is dropped when the ruler +/// picks another stop of the paragraph with the same leader and alignment character. +#[test] +fn a_field_value_typed_before_another_stop_is_picked_does_not_reach_that_stop() { + use craft::ui::contract::Role; + for (label, typed) in [("Leader:", "-"), ("Align On:", ",")] { + let (app, ids) = decimal_stops_app(1, &[30.0, 60.0]); + let before = stops_of(&app, ids[0]); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + panel.app().ui.tabs_panel.stop = 0; + draft(&mut panel, label, Role::TEXT_INPUT, typed); + panel.app().ui.tabs_panel.stop = 1; + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), ids[0]), before, "{label} {typed:?} typed for the first stop, entered after picking the second"); + } +} From b50bed79ed9888757127c5bc9194bb8ad3772b05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:30:02 -0800 Subject: [PATCH 468/533] Gradient: test Aspect Ratio, Repeats and wider selections for unfinished values Add tests showing that an unfinished Aspect Ratio or Repeats value does not reach another object with the same value, and that an unfinished Angle value does not reach a wider selection or another part of the same symbol instance. The field key no longer holds the selected symbol part's path: `Session::gradient_owner` already names the part through `StopOwner`, so the key is the gradient owner and the selected objects. --- crates/ui-egui/src/panels/gradient.rs | 8 +-- crates/ui-egui/src/panels/gradient/tests.rs | 66 +++++++++++++++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 5feb4b231a..4c8122fa77 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -292,12 +292,12 @@ fn selected_mid(app: &VectorcraftApp, stops: usize) -> Option { } /// What the panel's number fields edit: the gradient behind the active proxy -/// ([`vectorcraft_engine::Session::gradient_owner`]) on the selected objects and the selected part of a symbol -/// instance. Each field passes it to [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value +/// ([`vectorcraft_engine::Session::gradient_owner`], which names the selected part of a symbol instance) on the selected +/// objects. Each field passes it to [`NumberField::edit_target`], with the stop, midpoint or point it shows, so a value /// left unfinished in the field is dropped when another one is selected. fn field_target(app: &VectorcraftApp) -> egui::IdSalt { - let selection = app.session.active().map(|st| (&st.selection.objects, st.selection.symbol_part.as_ref().map(|p| (p.instance, &p.path)))); - egui::IdSalt::new((app.session.gradient_owner(), selection)) + let objects = app.session.active().map(|st| &st.selection.objects); + egui::IdSalt::new((app.session.gradient_owner(), objects)) } /// A stored fraction as the percent a field shows, without the `f32` noise (`0.3` is `30`, not `30.000001`). diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 3ad8f26f0b..0085caada8 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -396,6 +396,72 @@ fn an_unfinished_point_or_angle_value_does_not_reach_a_new_target() { } } +/// An unfinished Aspect Ratio or Repeats value belongs to the gradient it was typed for: after another object with the +/// same value is selected, the field shows that object's value, and further typing starts a new value. +#[test] +fn an_unfinished_aspect_or_repeats_value_does_not_reach_another_object() { + let gradient = json!({"gradient": {"kind": "radial", "aspect": 50, "spread": "repeat", "repeats": 3}}); + let mut app = app(gradient.clone()); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + app.run("paint.setFill", gradient).unwrap(); + let of = |rig: &Rig, id: NodeId| match rig.app().session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + Paint::Gradient(g) => (g.geom.map(|x| (x.aspect * 100.0).round()), g.gradient.repeats), + p => panic!("expected a gradient fill, got {p:?}"), + }; + let mut rig = Rig::new(app); + + for (label, shown) in [("Aspect Ratio", "50 %"), ("Repeats", "3")] { + rig.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + rig.fixture.settle(); + rig.type_unfinished(label, "20+"); + rig.app().run("select.set", json!({"ids": [b.0]})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text(label).as_deref(), Some(shown), "{label} shows the other object's value"); + rig.finish("2"); + } + assert_eq!(of(&rig, a), (Some(50.0), 3), "the first object keeps its gradient"); + assert_eq!(of(&rig, b), (Some(2.0), 2), "the other object takes 2%, not 20+2, and 2 repeats, not 20+2"); +} + +/// An unfinished value is dropped when another object joins the selection, which keeps the same first object, and when +/// another part of the same symbol instance is selected. +#[test] +fn an_unfinished_value_does_not_reach_a_wider_selection_or_another_symbol_part() { + let gradient = json!({"gradient": {"angle": 30}}); + let angle_of = |rig: &Rig, id: NodeId| match rig.app().session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint() { + Paint::Gradient(g) => g.angle, + p => panic!("expected a gradient fill, got {p:?}"), + }; + let mut objects = app(gradient.clone()); + let a = objects.session.active().unwrap().selection.objects[0]; + let b = NodeId(objects.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + objects.run("paint.setFill", gradient.clone()).unwrap(); + objects.run("select.set", json!({"ids": [a.0]})).unwrap(); + let mut rig = Rig::new(objects); + let angle = rig.text("Angle"); + rig.type_unfinished("Angle", "20+"); + rig.app().run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Angle"), angle, "Angle shows the wider selection's angle"); + rig.finish("1"); + assert_eq!((angle_of(&rig, a), angle_of(&rig, b)), (1.0, 1.0), "both objects take 1°, not 20+1"); + + // Two parts of one symbol instance with the same angle. + let mut parts = app(gradient.clone()); + let left = parts.session.active().unwrap().selection.objects[0]; + let right = parts.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].clone(); + parts.run("paint.setFill", gradient).unwrap(); + let symbol = parts.run("symbol.new", json!({"name": "Pair", "type": "dynamic", "ids": [left.0, right]})).unwrap()["id"].clone(); + parts.run("symbol.instance.selectPart", json!({"id": symbol, "path": [0]})).unwrap(); + let mut rig = Rig::new(parts); + let angle = rig.text("Angle"); + rig.type_unfinished("Angle", "20+"); + rig.app().run("symbol.instance.selectPart", json!({"id": symbol, "path": [1]})).unwrap(); + rig.fixture.settle(); + assert_eq!(rig.text("Angle"), angle, "Angle shows the other part's angle"); +} + /// A mirrored conic's Aspect Ratio field shows the extent's size, and a typed value keeps the /// sweep mirrored (the field's value times the mirror's sign). #[test] From b18d3c163efd2c3745919eed6158c34c435ebe92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:34:55 -0800 Subject: [PATCH 469/533] Docs: a Global Adjust keeps a row's art off its picked swatch The Recolor Artwork entry now says that without Limit to Library, a Global Adjust other than 0% gives the row's art the adjusted color and does not link it to the swatch picked for the row. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 225e1c3f0c..0f0315cc9c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2194,7 +2194,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%, and an excluded row keeps its new color, swatch and tint. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list for a row of the selected art stays that swatch, unless an earlier solid swatch (other than a linked tint) in the same library has the same name and color, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list for a row of the selected art stays that swatch, unless an earlier solid swatch (other than a linked tint) in the same library has the same name and color, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. Without Limit to Library, with a Global Adjust other than 0%, the row's art takes the adjusted color and is not linked to the picked swatch. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From b6bca116e41f7c87a31fa1498798779f9c989dfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:38:36 -0800 Subject: [PATCH 470/533] Find and Replace: a confirm with no Find text presses nothing With an empty Find text the dialog's buttons other than Done run nothing when clicked. ui.dialog.confirm now refuses such a press with "the Find text is empty" and leaves the text, the undo steps, the dialog's message and the action field as they were, instead of running edit.findNext or edit.findReplace and writing their parameter error into the message. ui.dialog.set now refuses `fields` given together with `field` or `value`, as the dialog host does, also when the list holds only `action`. --- crates/ui-egui/src/dialogs/find_replace.rs | 18 +++++--- .../ui-egui/src/dialogs/find_replace/tests.rs | 41 +++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 52dae1b1a5..0cc695feaa 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -370,11 +370,12 @@ const ACTIONS: [&str; 5] = ["find", "replace", "replaceFind", "replaceAll", "don /// out of `params`: `Ok(None)` when it gives none, an error when it is not one of [`ACTIONS`]. fn take_action(params: &mut Value) -> Result, String> { let Some(o) = params.as_object_mut() else { return Ok(None) }; + // The host's setter refuses the same mix. + if o.contains_key("fields") && (o.contains_key("field") || o.contains_key("value")) { + return Err("`fields` takes the place of `field` and `value`".into()); + } let mut given = None; if o.get("field").and_then(Value::as_str) == Some("action") { - if o.contains_key("fields") { - return Err("`fields` takes the place of `field` and `value`".into()); - } o.remove("field"); given = Some(o.remove("value").unwrap_or(Value::Null)); } @@ -483,15 +484,22 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, metho /// Presses the button the `action` field names, as a click on it does, and leaves `action` at /// `find`. Replace and Replace & Find find a match when Find Next has reached none with the Find /// text and the switches as they are now. Done closes the dialog → the dialog as listed, or null -/// once closed; a refusal is the dialog's message and the error. +/// once closed; a refusal is the dialog's message and the error. With an empty Find text every +/// button but Done runs nothing, as a click does: the press is an error that leaves the message and +/// `action` as they were. fn press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result { - let action = app.ui.find_action.take().unwrap_or_else(|| "find".into()); + let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); let dialogs = app.dialogs().ok_or("no window")?; let form = dialogs.with(|host| host.get::().map(form)).ok_or("no hosted dialog is open")?; if action == "done" { + app.ui.find_action = None; dialogs.with(|host| host.cancel::(ctx)); return Ok(Value::Null); } + if form.query["find"].as_str().is_none_or(str::is_empty) { + return Err("the Find text is empty".into()); + } + app.ui.find_action = None; let found = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some()); let ran = match action.as_str() { "replace" | "replaceFind" if found => replace(app, &form, action == "replaceFind"), diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 9c7e5f122d..8fc19c094e 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -198,6 +198,47 @@ fn an_action_that_names_no_button_is_refused() { assert!(is_open(&p)); } +/// With an empty Find text a confirm presses nothing, as the dialog's buttons run nothing: it is +/// refused, and the text, the undo steps, the message and `action` stay as they were. Done still +/// closes the dialog. +#[test] +fn a_confirm_with_no_find_text_presses_nothing() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "replace", "value": "dog"})).unwrap(); + assert_eq!(field(&p, "find"), json!("")); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["find", "replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the Find text is empty".to_string()), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + +/// `fields` given with `field` or `value` is refused, as the host refuses it, even when the list +/// holds only `action`; nothing is set. +#[test] +fn fields_with_field_or_value_is_refused() { + let (app, _) = app_with(&["cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let refusal = Err("`fields` takes the place of `field` and `value`".to_string()); + let only_action = json!([{"field": "action", "value": "replace"}]); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "find", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + let r = control(&p, "ui.dialog.set", json!({"dialog": "top", "value": "cat", "fields": only_action})); + assert_eq!(r, refusal); + assert_eq!((field(&p, "find"), listed_action(&p)), (json!(""), json!("find"))); +} + /// A set of other fields answers with `action` listed. A click on a button, like a confirm, puts /// `action` back to find, and so does opening the dialog again. A `fields` list of more than 256 /// items is refused, `action` counted with the rest. From 4bbfb2d4aff9a1614856560221982cbeb138684f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:01:46 -0800 Subject: [PATCH 471/533] Scripts: pathItems.removeAll counts only type that draws glyphs as a clip outline The document's pathItems.removeAll() counted any visible text object as geometry that keeps a clipping mask clipping. Blank type and area type too short for its first line lay out no glyphs, so the clip renderer clips by nothing for them; deleting the mask's last path then hid the clipped art. - Text counts only when it is visible and its layout gives glyph outlines. - A clipping group nested in the mask counts only its first member. - Hidden objects and members of hidden groups do not count. - Tests cover blank, overset, hidden and nested-clipped type, and type with glyphs that still allows the delete. - docs/mcp.md states the rule. --- crates/engine/src/script/dom/paths.rs | 20 +++- crates/engine/src/tests/script_dom.rs | 140 ++++++++++++++++++++++---- docs/mcp.md | 4 +- 3 files changed, 141 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 40db503d05..4ae9d65dc0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -540,7 +540,7 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or /// layer that keeps other objects, or a compound path or group that clips one and would be left -/// with no visible path or text. +/// with no visible path or visible type that lays out glyphs to clip by. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if super::layers::is_scoped(a, "PathItems") { return super::layers::scoped_remove_all(h, a); @@ -579,9 +579,21 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { if kids.iter().any(|k| affected.contains(&k.id)) { affected.insert(n.id); } - if (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Text(_)) && n.visible && !going.contains(&n.id)) - || kids.iter().any(|k| k.visible && geometry.contains(&k.id)) - { + // A clip outline takes in visible paths and the glyphs of visible type, as + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no outline. + let shape = n.visible + && match &n.kind { + NodeKind::Path { .. } => true, + NodeKind::Text(t) => { + t.runs.iter().any(|r| !r.text.trim().is_empty()) + && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + } + _ => false, + }; + // A clipping group's outline is its first member's alone. + let inner = + if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) }; + if n.visible && ((shape && !going.contains(&n.id)) || inner) { geometry.insert(n.id); } if n.clips() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ab0772e2ea..222c40cf21 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3421,16 +3421,16 @@ fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() { assert_eq!(undo_steps(&s), steps); } -/// A clipping group of a path and text keeps the text's glyph outlines when the document's -/// `pathItems.removeAll()` deletes the path, so the paths are deleted. +/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still +/// clips, and the document's `pathItems.removeAll()` deletes every path. #[test] -fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keeps_text() { - let (mut s, a, _) = doc(); +fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() { + let (mut s, a, b) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); - let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { @@ -3445,33 +3445,33 @@ fn document_path_items_remove_all_deletes_a_path_from_a_clipping_group_that_keep assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask)); let steps = undo_steps(&s); let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); - assert_eq!(out, [json!(""), json!(0)]); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); let d = &s.active().unwrap().doc; - assert!(d.node(a).is_none()); - assert!(d.node(t).is_some()); - assert!(d.node(kept).is_some()); + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); assert_eq!(undo_steps(&s), steps + 1); } -/// Hidden text in a clipping group does not clip, so the document's `pathItems.removeAll()` -/// refuses to delete the group's only visible clipping path. +/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would +/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing. #[test] -fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { +fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() { let (mut s, a, _) = doc(); let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); - let kept = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "art"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - s.execute("select.set", &json!({"ids": [mask.0, kept.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + } if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { children.sort_by_key(|c| c.id != mask); *clip = true; } - if let Some(n) = d.node_mut(t) { - n.visible = false; - } Ok(()) }) .unwrap(); @@ -3480,6 +3480,110 @@ fn document_path_items_remove_all_refuses_when_only_hidden_text_would_clip() { let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); let e = out[0].as_str().unwrap_or_default(); assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does +/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer +/// mask too. +#[test] +fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap(); + let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + for (g, first) in [(nested, b), (outer, mask)] { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != first); + *clip = true; + } + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a +/// clipping group whose paths would leave only such type makes the document's +/// `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId( + s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes +/// the document's `pathItems.removeAll()` throw and delete nothing. +#[test] +fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() { + let (mut s, a, _) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(n) = d.node_mut(t) { + n.visible = false; + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + let e = out[0].as_str().unwrap_or_default(); + assert!(e.contains("cannot delete a clipping path"), "{out:?}"); + assert!(e.contains(&mask.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); assert_eq!(s.active().unwrap().doc, before); assert_eq!(undo_steps(&s), steps); } diff --git a/docs/mcp.md b/docs/mcp.md index 8eb344964e..d6fd6b06fa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3236,7 +3236,9 @@ through `$`: `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's `pathItems`, `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that - clips when a text object in that group stays, because the text then clips. `remove()` on an object that + clips when a visible text object that lays out glyphs stays in it, because the text then clips. Hidden text, text + in a hidden group, blank text, area text too short for its first line, and text that a clipping group nested in + the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` From 787eafd7de0d5dd13ddcb07d6645ca951962f44f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:33:14 -0800 Subject: [PATCH 472/533] Find and Replace: a confirm presses only a button the open tab shows ui.dialog.confirm pressed the button `action` names whatever tab the dialog showed. With `tab` set to find, a confirm of replaceAll replaced every match although that tab shows only Find Next and Replace more, and on the Go To tab a confirm of find ran a search although that tab shows no Find Next. A confirm now presses only a button the open tab shows: Find Next on the Find and Replace tabs, Replace, Replace & Find and Replace All on the Replace tab, and Done on every tab. Any other press is refused with "the tab has no button for `action` " and leaves the document, the dialog's message and `action` as they were. --- crates/ui-egui/src/dialogs/find_replace.rs | 27 ++++++++++++--- .../ui-egui/src/dialogs/find_replace/tests.rs | 34 +++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs index 0cc695feaa..fc62033bf9 100644 --- a/crates/ui-egui/src/dialogs/find_replace.rs +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -481,16 +481,35 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, ctx: &egui::Context, metho Some(if confirm { press(app, ctx) } else { Ok(listed(app)) }) } +/// Whether the dialog's `tab` (its `tab` field: `find`, `replace` or `goTo`) shows the button +/// `action` presses, enabled. Every tab shows Done. The Find tab shows Find Next, and the Replace tab +/// shows Find Next, Replace, Replace & Find and Replace All. The Go To tab shows no Find Next: its +/// first button is Go To, which stays disabled while the dialog has no go-to kinds. +fn shown_on(tab: &str, action: &str) -> bool { + match action { + "done" => true, + "find" => matches!(tab, "find" | "replace"), + _ => tab == "replace", + } +} + /// Presses the button the `action` field names, as a click on it does, and leaves `action` at /// `find`. Replace and Replace & Find find a match when Find Next has reached none with the Find /// text and the switches as they are now. Done closes the dialog → the dialog as listed, or null -/// once closed; a refusal is the dialog's message and the error. With an empty Find text every -/// button but Done runs nothing, as a click does: the press is an error that leaves the message and -/// `action` as they were. +/// once closed; a refusal is the dialog's message and the error. A button the open tab does not +/// show ([`shown_on`]) and, with an empty Find text, every button but Done run nothing, as a click +/// cannot press them: the press is an error that leaves the document, the message and `action` as +/// they were. fn press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Result { let action = app.ui.find_action.clone().unwrap_or_else(|| "find".into()); let dialogs = app.dialogs().ok_or("no window")?; - let form = dialogs.with(|host| host.get::().map(form)).ok_or("no hosted dialog is open")?; + let (form, tab) = dialogs + .with(|host| host.get::().map(|d| (form(d), d.json_fields().and_then(|f| f["tab"].as_str().map(str::to_string))))) + .ok_or("no hosted dialog is open")?; + let tab = tab.unwrap_or_default(); + if !shown_on(&tab, &action) { + return Err(format!("the {tab} tab has no button for `action` {action}")); + } if action == "done" { app.ui.find_action = None; dialogs.with(|host| host.cancel::(ctx)); diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 8fc19c094e..dd1dc255e7 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -222,6 +222,40 @@ fn a_confirm_with_no_find_text_presses_nothing() { assert!(!is_open(&p)); } +/// A confirm presses only a button the open tab shows enabled: on the Find tab the Replace buttons +/// and on the Go To tab Find Next are refused, naming the tab, and the text, the undo steps, the +/// message and `action` stay as they were. Find Next runs on the Find tab, and Done closes the +/// dialog from the Go To tab. +#[test] +fn a_confirm_presses_only_a_button_the_tab_shows() { + let (app, ids) = app_with(&["cat cat"]); + let mut p = Panel::new(app, draw); + choose(&p); + p.frame(); + let fields = json!([{"field": "find", "value": "cat"}, {"field": "replace", "value": "dog"}, {"field": "tab", "value": "find"}]); + control(&p, "ui.dialog.set", json!({"dialog": "top", "fields": fields})).unwrap(); + let (before, said) = (undo_steps(&p), message(&p)); + for action in ["replace", "replaceFind", "replaceAll"] { + set_action(&p, action); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err(format!("the find tab has no button for `action` {action}")), "{action}"); + assert_eq!((plain(&p, ids[0]), undo_steps(&p), message(&p)), ("cat cat".to_string(), before, said.clone()), "{action}"); + assert_eq!(listed_action(&p), json!(action)); + } + set_action(&p, "find"); + control(&p, "ui.dialog.confirm", json!({})).unwrap(); + assert_eq!(matched(&p), Some((ids[0], 0, 3)), "Find Next is on the Find tab"); + + control(&p, "ui.dialog.set", json!({"dialog": "top", "field": "tab", "value": "goTo"})).unwrap(); + let (at, said) = (from(&p), message(&p)); + let r = control(&p, "ui.dialog.confirm", json!({})); + assert_eq!(r, Err("the goTo tab has no button for `action` find".to_string())); + assert_eq!((from(&p), message(&p), listed_action(&p)), (at, said, json!("find"))); + set_action(&p, "done"); + assert_eq!(control(&p, "ui.dialog.confirm", json!({})), Ok(Value::Null)); + assert!(!is_open(&p)); +} + /// `fields` given with `field` or `value` is refused, as the host refuses it, even when the list /// holds only `action`; nothing is set. #[test] From ade0e47f4808303d70bb5ca4b08cb928bf7ab191 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:35:18 -0800 Subject: [PATCH 473/533] Scripts: refused writes create no file; Linux reads the casefold flag A refused rename that falls back to copying into the target no longer creates a missing target before the final authorization check. The target is created only after that check, on every platform, so a refusal at the final check leaves the path absent. An existing target is still opened with O_CREAT, so Linux's fs.protected_regular applies. imageCapture no longer treats an empty Linux folder as ignoring the Unicode normalization form. It reads the folder's casefold inode flag (FS_IOC_GETFLAGS) instead, so a missing linked cafe\u{301}.png no longer matches cafe\u{e9}.png in an ordinary folder, and a casefolded folder still matches both spellings. --- .../engine/src/script/dom/raster_capture.rs | 55 ++++++++++++++++++- crates/format/src/atomic.rs | 46 +++++++++++----- 2 files changed, 86 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index 38c8eb5437..b7385a6b94 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -347,7 +347,8 @@ fn same_file(a: &Placed, b: &Placed) -> bool { /// decomposed (NFD) forms, and that is not a symbolic link, is looked up in the other form, and /// names ignore the form when that finds the same entry. With no such entry, names ignore the form /// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that -/// ignores letter case (ext4 and f2fs casefolding also ignore the form), and keep it elsewhere. +/// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the +/// form. Elsewhere, and on Linux when the flag can't be read, names keep the form. fn ignores_normalization(folder: &std::path::Path) -> bool { use unicode_normalization::UnicodeNormalization; for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { @@ -358,7 +359,31 @@ fn ignores_normalization(folder: &std::path::Path) -> bool { return finds_same(&entry.path(), &folder.join(other)); } } - cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ignores_case(folder)) + #[cfg(target_os = "linux")] + { + casefolded(folder) + } + #[cfg(not(target_os = "linux"))] + { + cfg!(target_os = "macos") + } +} + +/// `FS_CASEFOLD_FL` from Linux's `include/uapi/linux/fs.h`: the folder looks names up casefolded. +#[cfg(target_os = "linux")] +const FS_CASEFOLD_FL: u32 = 0x4000_0000; + +/// Whether the Linux folder `folder` carries the casefold inode flag, read with +/// `FS_IOC_GETFLAGS`. `false` when the folder can't be opened or its flags can't be read. +#[cfg(target_os = "linux")] +fn casefolded(folder: &std::path::Path) -> bool { + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_some_and(|f| has_casefold(f.bits())) +} + +/// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. +#[cfg(target_os = "linux")] +fn has_casefold(bits: u32) -> bool { + bits & FS_CASEFOLD_FL != 0 } /// The check `imageCapture` makes on the file it writes, `p`, given as written or as the real path @@ -640,4 +665,30 @@ mod source_tests { assert!(same_file(&target, &source)); }); } + + /// In an empty Linux folder, names that differ only in their normalization form are one file + /// only when the folder is casefolded. On a folder without the flag they are distinct, and + /// nothing is written into the folder to find out. + #[cfg(target_os = "linux")] + #[test] + fn names_in_another_normalization_form_match_only_in_a_casefolded_empty_folder() { + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-distinct"); + let folder = std::fs::canonicalize(&*dir).unwrap(); + let (linked, capture): (Placed, Placed) = ((folder.clone(), "cafe\u{301}.png".into()), (folder.clone(), "caf\u{e9}.png".into())); + assert_eq!(same_file(&capture, &linked), casefolded(&folder)); + assert_eq!(std::fs::read_dir(&folder).unwrap().count(), 0); + } + + /// A casefolded folder, which looks a name up in either normalization form, is recognized by + /// its inode flag, and a folder that can't be read is not taken for one. + #[cfg(target_os = "linux")] + #[test] + fn a_casefolded_folder_is_recognized_by_its_inode_flag() { + assert!(has_casefold(FS_CASEFOLD_FL)); + assert!(has_casefold(FS_CASEFOLD_FL | 0x10)); + assert!(!has_casefold(0x10)); + assert!(!has_casefold(0)); + let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); + assert!(!casefolded(&dir.join("missing"))); + } } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 30c55f3cc0..83901874fd 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -473,8 +473,17 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> remove_tmp: &|| { let _ = std::fs::remove_file(tmp); }, - open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, - #[cfg(unix)] + // A missing target is created by `create_target`, after the last check. An existing one is + // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. + open_target: &|write| { + if !write { + return File::open(target); + } + if matches!(std::fs::symlink_metadata(target), Err(e) if e.kind() == io::ErrorKind::NotFound) { + return Err(io::ErrorKind::NotFound.into()); + } + OpenOptions::new().write(true).create(true).truncate(false).open(target) + }, create_target: &|| create_new(target), synced: &|| sync_written_parent(target), still_allowed: check, @@ -497,10 +506,9 @@ struct Over<'a> { /// Best effort. remove_tmp: &'a dyn Fn(), /// Opens the target without truncating it for writing when `true`, or for reading when `false`. - /// Checked Unix writes defer creation of a missing target to `create_target`. + /// It never creates a missing target: `create_target` does that, after the final check. open_target: &'a dyn Fn(bool) -> io::Result, /// Creates a missing target after the final check and fails if its name is taken. - #[cfg(unix)] create_target: &'a dyn Fn() -> io::Result, /// The target's folder flushed, after the target is written. synced: &'a dyn Fn() -> io::Result<()>, @@ -510,7 +518,7 @@ struct Over<'a> { /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - // Checked Unix writes create a missing target only after the final check. + // A missing target is created only after the final check. if let Err(e) = (over.still_allowed)() { (over.remove_tmp)(); return Err(e); @@ -518,7 +526,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { let opened = (over.open_tmp)().and_then(|from| { let to = match (over.open_target)(true) { Ok(to) => Some(to), - #[cfg(unix)] Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; @@ -563,7 +570,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { } let mut to = match to { Some(to) => to, - #[cfg(unix)] None => match (over.create_target)() { Ok(to) => to, // A file put at the name meanwhile is left alone, and reported as there. @@ -576,11 +582,6 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { return Err(refused); } }, - #[cfg(not(unix))] - None => { - (over.remove_tmp)(); - return Err(refused); - } }; let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); @@ -1116,6 +1117,26 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A refused rename onto a missing file that is no longer allowed at the final check does not + /// create the file. + #[test] + fn a_refused_rename_does_not_create_a_missing_file_once_no_longer_allowed() { + let d = dir("no-rename-missing-disallowed"); + let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp")); + std::fs::write(&tmp, b"new").unwrap(); + let checks = std::cell::Cell::new(0); + let check = || { + checks.set(checks.get() + 1); + if checks.get() == 1 { Ok(()) } else { Err(io::Error::other("moved outside")) } + }; + let e = write_over(&tmp, &path, denied::<()>().unwrap_err(), &check).unwrap_err(); + assert_eq!(checks.get(), 2); + assert!(e.to_string().contains("moved outside"), "{e}"); + assert!(!path.exists(), "the refused write created {}", path.display()); + assert!(!tmp.exists()); + let _ = std::fs::remove_dir_all(d); + } + /// A refused rename whose folder is no longer allowed by the time the file would be overwritten /// leaves the file as it was, and neither copy stays behind. #[test] @@ -1137,7 +1158,6 @@ mod tests { let _ = std::fs::remove_file(&tmp); }, open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }, - #[cfg(unix)] create_target: &|| create_new(&path), synced: &|| Ok(()), still_allowed: &|| { From fe06a16261d9bf20287a292acd378c5a990f1a80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:40:06 -0800 Subject: [PATCH 474/533] Docs: a Global Adjust stops the pick from linking, not existing links The Recolor Artwork entry now says that with a Global Adjust other than 0%, the row's swatch pick does not create a link, and art already linked to that swatch stays linked. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0f0315cc9c..d43bf3758d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2194,7 +2194,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Recolor Artwork color groups list:** a list on the right of the dialog shows the document's color groups, and the Show Color Groups button beside the tabs shows or hides it. A click on a group makes it the group being edited, and the rows take its colors. Save Changes rewrites the selected group with the new colors, New Color Group saves them as a new group, and Delete removes the selected group; the Swatches panel shows each change ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). VectorCraft's own rules: when the art has colors of the group, Save Changes and OK keep the group's swatches in order, and a swatch no row lists keeps its color; an excluded row leaves its swatch its own color; after a save with art, the rows' new colors take the Global Adjust, which goes back to 0%, and an excluded row keeps its new color, swatch and tint. `group`, `groupStorage` and `groupAction` are the dialog fields. Tests: `the_color_groups_list_selects_saves_and_deletes_groups`, `a_group_picked_in_the_list_recolors_the_art` and the `saving_a_group_` tests in `crates/ui-egui/src/dialogs/recolor.rs`, and `edit_color_group_with_its_own_colors_records_no_undo_step` and `edit_color_group_with_its_own_color_keys_keeps_the_colors` in `crates/engine/src/tests/swatchcmds.rs`. - **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`. - **Recolor Artwork Undo Changes and Redo Changes:** two buttons beside the Color Theme Picker go back and forward one color edit made in the open dialog, and Undo Changes has nothing to undo after the dialog is opened again ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html)); `ui.recolorUndo` and `ui.recolorRedo` run them. VectorCraft's own rules: the dialog's history is separate from the document's, which changes when OK records one undo step and when Save All Colors or Save Prominent Colors adds a color group at once as its own undo step, which Cancel and Undo Changes leave in place; a drag is one step, fields set with `ui.dialog.set` before the next frame with the pointer up or the next step are one step, Reset is a step of its own, a new edit leaves nothing to redo, selecting another color group or Save Changes leaves nothing to undo or redo and an edit after either is a step back to the fields as they were then, a button with no step to go to is disabled, and the dialog keeps at most 64 steps and 4 MiB of them, always keeping the newest step. Tests: `undo_and_redo_changes_step_through_the_dialogs_own_edits`, `a_drag_is_one_step_of_undo_changes`, `undo_changes_reverses_reset`, `the_recolor_undo_and_redo_commands_step_the_open_dialog`, `the_recolor_undo_and_redo_commands_preview_the_step`, `an_edit_with_the_pointer_down_from_the_first_frame_is_a_step` and `rows_and_weights_set_before_the_art_is_read_are_no_step` in `crates/ui-egui/src/tests/recolor.rs`, and `undo_changes_keeps_a_bounded_history` and `another_group_or_save_changes_leaves_nothing_to_undo` and `an_edit_right_after_another_group_is_a_step` and `an_unchanged_save_changes_leaves_nothing_to_redo` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list for a row of the selected art stays that swatch, unless an earlier solid swatch (other than a linked tint) in the same library has the same name and color, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. Without Limit to Library, with a Global Adjust other than 0%, the row's art takes the adjusted color and is not linked to the picked swatch. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. + - **Recolor Artwork: a swatch picked for a row stays that swatch:** a row's new color is changed in the Color Picker ([Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)), Scale Tints gives a row's lighter current colors lighter tints of its new color, and Preserve Tints gives a spot or global current color's tint to the new color ([CS5 help, Colorize Method](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=151), [2021 reference, Colorize Method](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=252)). VectorCraft's own rule: a spot or global swatch picked in the Color Picker's swatch list for a row of the selected art stays that swatch, unless an earlier solid swatch (other than a linked tint) in the same library has the same name and color, so the row's art takes tints of it linked to it, also with no Limit to Library, and editing the swatch recolors the art; a process swatch gives its color as before, the row drops the swatch when its new color changes, and a swatch deleted after the pick links nothing, nor does a global swatch of the color group being rewritten that takes another color, and with Limit to Library the library's swatch of that color is used instead. Without Limit to Library, with a Global Adjust other than 0%, the row's art takes the adjusted color and the pick does not link it to the picked swatch; art already linked to that swatch stays linked. `recolor.apply` rows take `swatch: {name, library?}`. Tests: `a_swatch_picked_for_a_row_links_the_art_to_it_without_a_library`, `a_process_library_swatch_hides_the_tint_of_a_rows_own_spot_swatch`, `a_rows_spot_swatch_rewritten_with_another_color_shows_no_tint`, `a_library_spot_swatch_rewritten_with_another_color_shows_no_tint` and `a_library_swatch_named_like_a_rewritten_group_swatch_keeps_its_tint` in `crates/ui-egui/src/tests/recolor.rs`, `a_picked_spot_swatch_gives_its_row_the_tint_slider`, `a_picked_swatch_that_is_gone_links_nothing` and `a_picked_swatch_the_group_rewrites_shows_the_full_color` in `crates/ui-egui/src/dialogs/recolor.rs`, and `a_rows_swatch_links_its_art_without_limit_to_library`, `a_rows_swatch_with_a_finer_color_than_its_key_still_links`, `a_rows_swatch_in_the_rewritten_group_keeps_the_rows_new_color` and `a_rows_library_swatch_joins_the_document_and_a_process_swatch_changes_nothing` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. - **Convert to Indexed Color:** Edit › Edit Colors › Convert to Indexed Color… (`edit.colors.toIndexed`) stores the embedded images in the selection as indexed-color PNGs of at most 256 colors. The palette is chosen as for a PNG-8 export, as evenly spaced levels of red, green and blue, or from the document's swatches, with diffusion, pattern or noise dithering; pixels under half opacity become transparent. The dialog previews live, and OK is one undo step. This is VectorCraft's own command and counts toward no score. `tests::editcolors` and `encode::tests_palette` cover it. Scores and estimates unchanged. - **Working RGB numeric controls:** the Color panel and Color Picker read RGB, HSB, hex and Web Safe RGB values in the active working RGB space. Editing one RGB channel preserves the other native channels, including colors outside display sRGB. Regressions cover sRGB, Display P3, Wide Gamut RGB and ProPhoto RGB, picker initialization, native numeric round trips, and a slider click with one Undo step. Scores and estimates unchanged. From 1c23ee86380e4f8f0c433d6ff8ceb7d6b0d7bfab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:49:01 -0800 Subject: [PATCH 475/533] Tabs: test each part of the fields' edit target Four panel tests cover the parts of the edit target that no test covered: another document whose text has the same id and stops, the Type tool's insertion point moved to the next paragraph or its selection grown over both, the left indent's box picked after the first-line marker at the same position, and File > Revert followed by selecting the restored text again. Each one fails when its part is left out of the edit target. --- crates/ui-egui/src/panels/tabs/tests.rs | 108 ++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index e0afadbd66..f10afe5c98 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1195,3 +1195,111 @@ fn a_field_value_typed_before_another_stop_is_picked_does_not_reach_that_stop() assert_eq!(stops_of(&panel.app(), ids[0]), before, "{label} {typed:?} typed for the first stop, entered after picking the second"); } } + +/// An X value typed in one document and not yet entered is dropped when another document becomes +/// active, also when the text selected there has the same id and the same stops. +#[test] +fn an_x_value_typed_before_another_document_is_activated_does_not_reach_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ids: Vec = (0..2) + .map(|_| { + app.run("file.new", json!({})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + id + }) + .collect(); + assert_eq!(ids[0], ids[1], "the two documents' texts have the same id"); + let id = ids[0]; + let before = stops_of(&app, id); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().run("document.activate", json!({"index": 0})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + for index in [0, 1] { + panel.app().run("document.activate", json!({"index": index})).unwrap(); + assert_eq!(stops_of(&panel.app(), id), before, "X typed in the second document, entered after activating the first: document {index}"); + } +} + +/// The stops of every paragraph of text `id` as (position, leader, align on). +fn paragraph_stops(app: &VectorcraftApp, id: u64) -> Vec> { + let t = text_of(app, id); + (0..t.paragraph_count()).map(|i| t.para_at(i).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect()).collect() +} + +/// An X value typed with the Type tool's insertion point in the first paragraph and not yet +/// entered is dropped when the insertion point moves to the second paragraph, or the selection +/// grows over both, though both paragraphs hold the same stops. +#[test] +fn an_x_value_typed_before_the_type_tool_selection_changes_does_not_reach_other_paragraphs() { + for (anchor, caret) in [(6, 6), (0, 9)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5\nb\t2.5", "area": {"width": 300, "height": 80}})).unwrap(); + let id = id["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + let before = paragraph_stops(&app, id); + assert_eq!(before.len(), 2); + assert_eq!(before[0], before[1], "both paragraphs hold the same stops"); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 0})); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": anchor, "caret": caret})); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!( + paragraph_stops(&panel.app(), id), + before, + "X typed at the start of the text, entered with the Type tool's selection at {anchor}..{caret}" + ); + } +} + +/// An X value typed for the first-line marker and not yet entered is dropped when the ruler picks +/// the left indent's box at the same position. +#[test] +fn an_x_value_typed_before_another_indent_marker_is_picked_does_not_move_it() { + let mut app = indent_app(0.0, 0.0); + app.ui.tabs_panel.marker = Some(RulerItem::FirstLine); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "20"); + panel.app().ui.tabs_panel.marker = Some(RulerItem::LeftBox); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(indent_values(&panel.app(), 0), (0.0, 0.0), "X typed for the first-line marker, entered after picking the left indent's box"); +} + +/// An X value typed and not yet entered is dropped when File › Revert restores the document, also +/// when the restored text is selected again and holds the same stops. +#[test] +fn an_x_value_typed_before_file_revert_does_not_reach_the_restored_text() { + struct SavedFile(std::path::PathBuf); + impl Drop for SavedFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + let (mut app, ids) = decimal_stops_app(1, &[40.0]); + let id = ids[0]; + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-tabs-draft-revert-{}.vectorcraft", std::process::id()))); + app.run("file.saveAs", json!({"path": path.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let before = stops_of(&app, id); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70"); + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + panel.app().run("select.set", json!({"ids": [id]})).unwrap(); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(stops_of(&panel.app(), id), before, "X typed before File › Revert, entered after selecting the restored text"); +} From 4a1ac38ac3bf05160bf2deb41695fc90e8d80405 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 02:59:58 -0800 Subject: [PATCH 476/533] Scripts: a Linux folder whose casefold flag can't be read is taken as casefolded When the folder can't be opened or `FS_IOC_GETFLAGS` fails, `casefolded` returned false, so `imageCapture` treated names that differ only in their normalization form as two files and could write over a source document. It now returns false only when the flags are read and the flag is clear. --- crates/engine/src/script/dom/raster_capture.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/raster_capture.rs b/crates/engine/src/script/dom/raster_capture.rs index b7385a6b94..f067b430d4 100644 --- a/crates/engine/src/script/dom/raster_capture.rs +++ b/crates/engine/src/script/dom/raster_capture.rs @@ -348,7 +348,7 @@ fn same_file(a: &Placed, b: &Placed) -> bool { /// names ignore the form when that finds the same entry. With no such entry, names ignore the form /// on macOS, whose volumes (APFS and HFS+) look names up that way, and on Linux in a folder that /// carries the casefold inode flag ([`casefolded`]): ext4 and f2fs casefolding also ignores the -/// form. Elsewhere, and on Linux when the flag can't be read, names keep the form. +/// form, as they are taken to when the flag can't be read. Elsewhere names keep the form. fn ignores_normalization(folder: &std::path::Path) -> bool { use unicode_normalization::UnicodeNormalization; for entry in std::fs::read_dir(folder).into_iter().flatten().flatten().take(256) { @@ -374,10 +374,11 @@ fn ignores_normalization(folder: &std::path::Path) -> bool { const FS_CASEFOLD_FL: u32 = 0x4000_0000; /// Whether the Linux folder `folder` carries the casefold inode flag, read with -/// `FS_IOC_GETFLAGS`. `false` when the folder can't be opened or its flags can't be read. +/// `FS_IOC_GETFLAGS`. `true` when the folder can't be opened or its flags can't be read: `false` +/// only when the flags are read and the flag is clear. #[cfg(target_os = "linux")] fn casefolded(folder: &std::path::Path) -> bool { - std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_some_and(|f| has_casefold(f.bits())) + std::fs::File::open(folder).ok().and_then(|d| rustix::fs::ioctl_getflags(&d).ok()).is_none_or(|f| has_casefold(f.bits())) } /// Whether the inode flags `bits` include `FS_CASEFOLD_FL`. @@ -680,7 +681,8 @@ mod source_tests { } /// A casefolded folder, which looks a name up in either normalization form, is recognized by - /// its inode flag, and a folder that can't be read is not taken for one. + /// its inode flag. A folder whose flags can't be read is taken for one, so a capture is never + /// written over a source under a name in another normalization form. #[cfg(target_os = "linux")] #[test] fn a_casefolded_folder_is_recognized_by_its_inode_flag() { @@ -689,6 +691,6 @@ mod source_tests { assert!(!has_casefold(0x10)); assert!(!has_casefold(0)); let dir = vectorcraft_testkit::TempDir::new("capture-nfd-missing"); - assert!(!casefolded(&dir.join("missing"))); + assert!(casefolded(&dir.join("missing"))); } } From 5474dd708c893120b5cc68989c2199188c9f62a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:13:29 -0800 Subject: [PATCH 477/533] Artboards: an unentered name stays with its artboard A name typed in the Control bar's or the Properties panel's artboard Name field and not yet entered was kept when another artboard became active, moved to the active artboard's number, File Revert replaced the document, or another document became active, as long as the artboard then shown had the same name. Enter then renamed that artboard. Both fields now have an edit target made of the active document, its reverts, and the artboard's number and id, so the typed name is dropped when any of them changes. --- crates/ui-egui/src/panels/artboards.rs | 18 +++-- crates/ui-egui/src/panels/artboards/tests.rs | 68 +++++++++++++++++++ .../panels/properties/artboard_sections.rs | 2 +- 3 files changed, 82 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 270fc9edcf..f2c67f6307 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -65,12 +65,20 @@ fn icon_button(ui: &mut Ui, icon: &'static str, label: &'static str, enabled: bo IconButton::new(IconId::new(icon)).label(label).enabled(enabled).show(ui).response().clicked() } -/// The Control bar's Name field showing `name` → the name typed, trimmed, when it is new. An empty field -/// keeps the old name, as in the Properties panel; names are never translated. -fn name_field(ui: &mut Ui, name: &str) -> Option { +/// The edit target of the Name field of artboard `i` with id `id`, in the Control bar and Properties: the active +/// document and its reverts, and the artboard. A name typed and not yet entered is dropped when this changes, so +/// it does not rename another artboard, even one with the same name. +pub(crate) fn name_target(app: &VectorcraftApp, i: usize, id: u32) -> egui::IdSalt { + egui::IdSalt::new((app.session.active().map(|st| (st.uid, st.reverts)), i, id)) +} + +/// The Control bar's Name field showing `name`, for edit target `target` ([`name_target`]) → the name typed, +/// trimmed, when it is new. An empty field keeps the old name, as in the Properties panel; names are never +/// translated. +fn name_field(ui: &mut Ui, name: &str, target: egui::IdSalt) -> Option { let mut typed = None; Field::new(tl!("Name:")).id_salt("ab-name").show(ui, |ui, _| { - typed = TextField::new(tl!("Name:"), Bind::given(name.to_owned())).show(ui).events.committed().cloned(); + typed = TextField::new(tl!("Name:"), Bind::given(name.to_owned())).edit_target(target).show(ui).events.committed().cloned(); }); typed.map(|n| n.trim().to_owned()).filter(|n| !n.is_empty() && n != name) } @@ -100,7 +108,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, if icon_button(ui, "trash-2", tl!("Delete Artboard"), n > 1) { delete_selected(app); } - if let Some(name) = name_field(ui, &ab.name) { + if let Some(name) = name_field(ui, &ab.name, name_target(app, i, ab.id)) { app.run("artboard.setProps", json!({"index": i, "name": name})).ok(); } }); diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index 2359a17bae..ade85780f9 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -581,6 +581,74 @@ fn control_bar_name_cancels_typing_and_commits_one_rename() { } } +/// The artboards' names in each open document. +fn names_in_every_document(app: &VectorcraftApp) -> Vec> { + app.session.documents().iter().map(|st| st.doc.artboards.iter().map(|a| a.name.clone()).collect()).collect() +} + +/// A name typed in the Control bar's or Properties' Name field and not yet entered is dropped when another +/// artboard becomes active or moves to the active artboard's number, File Revert replaces the document, or +/// another document becomes active, each time showing an artboard with the same name: Enter then renames nothing. A name typed after the change renames +/// the artboard now shown. +#[test] +fn a_name_typed_before_the_active_artboard_changes_does_not_rename_another_artboard() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + fn bar(app: &mut VectorcraftApp, ui: &mut Ui) { + assert!(control_bar(app, ui, true, false)); + } + type Change = fn(&mut VectorcraftApp); + let changes: [(&str, Change); 4] = [ + ("another artboard became active", |app| select(app, 1)), + ("another artboard took its number", |app| { + app.run("artboard.reorder", json!({"index": 1, "to": 0})).unwrap(); + }), + ("File Revert", |app| { + let uid = app.session.active().unwrap().uid; + app.session.document_mut(uid).unwrap().reverts += 1; + }), + ("another document became active", |app| { + app.run("document.activate", json!({"index": 1})).unwrap(); + }), + ]; + for (field, draw) in [("Name:", bar as fn(&mut VectorcraftApp, &mut Ui)), ("Name", crate::panels::properties::show)] { + for (change, apply) in changes { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for _ in 0..2 { + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + for index in 0..2 { + app.run("artboard.setProps", json!({"index": index, "name": "Same"})).unwrap(); + } + } + app.run("document.activate", json!({"index": 0})).unwrap(); + app.select_tool("artboard"); + select(&mut app, 0); + let mut panel = Panel::new(app, draw); + panel.room(egui::vec2(1000.0, 500.0)); + let before = names_in_every_document(&panel.app()); + panel.click_role(field, Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("Typed"); + apply(&mut panel.app()); + panel.frame(); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(names_in_every_document(&panel.app()), before, "{field:?}: a name typed, then {change}, then Enter"); + + panel.click_role(field, Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("Typed"); + panel.key(Key::Enter, Modifiers::NONE); + let app = panel.app(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.artboards[selected(&app, doc.artboards.len())].name, "Typed", "{field:?}: a name typed after {change}"); + let typed = names_in_every_document(&app).concat().iter().filter(|n| *n == "Typed").count(); + assert_eq!(typed, 1, "{field:?}: a name typed after {change} renames one artboard"); + } + } +} + /// The Control bar's size fields resize the active artboard about the reference point in one undo /// step: about its center, and from its top-left corner once the top-left point is chosen. #[test] diff --git a/crates/ui-egui/src/panels/properties/artboard_sections.rs b/crates/ui-egui/src/panels/properties/artboard_sections.rs index 0d171b208d..c9e8a58fd4 100644 --- a/crates/ui-egui/src/panels/properties/artboard_sections.rs +++ b/crates/ui-egui/src/panels/properties/artboard_sections.rs @@ -47,7 +47,7 @@ pub(super) fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { Row::new().show(ui, |ui, _| { // The field shows the name as it is (names are never translated). A blank name is refused: // the field shows the old one again. - let out = TextField::new(tl!("Name"), Bind::given(ab.name.clone())).show(ui); + let out = TextField::new(tl!("Name"), Bind::given(ab.name.clone())).edit_target(artboards::name_target(app, i, ab.id)).show(ui); if let Some(text) = out.events.committed() { let name = text.trim(); if !name.is_empty() && name != ab.name { From fc9d77032f4af9cb25b836b1216676fe0ae03789 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:19:03 -0800 Subject: [PATCH 478/533] Scripts: pathItems.removeAll counts a list marker as a clip outline The document's pathItems.removeAll() skipped text whose characters are all whitespace before laying it out, so a numbered paragraph holding a single space did not count, although its number clips. The deletion was then refused while the mask would still clip. - Whitespace-only text is laid out like other text. - Text is laid out only inside a mask that loses a path, so documents with text outside such masks do no layout for the check. - A test covers a mask left with only a list number. - docs/mcp.md says blank text without a list marker does not count. --- crates/engine/src/script/dom/paths.rs | 29 +++++++++++++++----- crates/engine/src/tests/script_dom.rs | 39 +++++++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 4ae9d65dc0..1a8fb3087b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -565,6 +565,26 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { } let mut going: std::collections::HashSet = ids.iter().copied().collect(); let mut affected: std::collections::HashSet = ids.iter().copied().collect(); + for n in nodes.iter().rev() { + if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) { + affected.insert(n.id); + } + } + // Type is laid out only inside a mask that loses a path; no other outline decides a refusal. + let mut in_mask = std::collections::HashSet::new(); + for n in &nodes { + if n.clips() + && let Some(mask) = n.children().and_then(|k| k.first()) + && affected.contains(&mask.id) + { + let mut stack = vec![mask]; + while let Some(m) = stack.pop() { + if in_mask.insert(m.id) { + stack.extend(m.children().into_iter().flatten()); + } + } + } + } let mut geometry = std::collections::HashSet::new(); let mut masks = Vec::new(); for n in nodes.into_iter().rev() { @@ -576,17 +596,14 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { { going.insert(n.id); } - if kids.iter().any(|k| affected.contains(&k.id)) { - affected.insert(n.id); - } // A clip outline takes in visible paths and the glyphs of visible type, as - // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no outline. + // `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no + // outline. A list marker is a glyph too, so whitespace-only type is laid out as well. let shape = n.visible && match &n.kind { NodeKind::Path { .. } => true, NodeKind::Text(t) => { - t.runs.iter().any(|r| !r.text.trim().is_empty()) - && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() + in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty() } _ => false, }; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 222c40cf21..62c47de128 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3519,6 +3519,45 @@ fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() { assert_eq!(s.active().unwrap().doc, before); } +/// A numbered paragraph whose text is a single space still draws its number, which clips, so the +/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it. +#[test] +fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() { + use vectorcraft_doc::text::{NumberStyle, ParaList}; + let (mut s, a, b) = doc(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap(); + let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Clip", |d, _| { + if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) { + tx.runs.iter_mut().for_each(|r| r.text = " ".into()); + let mut styles = tx.paragraph_styles(); + styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic))); + tx.set_paragraph_styles(styles); + } + if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) { + children.sort_by_key(|c| c.id != mask); + *clip = true; + } + Ok(()) + }) + .unwrap(); + if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) { + assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty()); + } + let steps = undo_steps(&s); + let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL); + assert_eq!(out[0], json!(""), "{out:?}"); + assert_eq!(out[1], json!(0)); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none()); + assert!(d.node(t).is_some() && d.node(u).is_some()); + assert_eq!(undo_steps(&s), steps + 1); +} + /// Area type too short for its first line lays out no glyphs and gives no clip outline, so a /// clipping group whose paths would leave only such type makes the document's /// `pathItems.removeAll()` throw and delete nothing. diff --git a/docs/mcp.md b/docs/mcp.md index d6fd6b06fa..3c2ac4f459 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3237,7 +3237,7 @@ through `$`: `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects. The document's `pathItems.removeAll()` still deletes the paths of a group that clips when a visible text object that lays out glyphs stays in it, because the text then clips. Hidden text, text - in a hidden group, blank text, area text too short for its first line, and text that a clipping group nested in + in a hidden group, blank text without a list marker, area text too short for its first line, and text that a clipping group nested in the mask clips do not keep it clipping, so `removeAll()` then throws and deletes nothing. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on From 89509c31e413555a4ae7ca98f9bed6897f6287fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 05:58:08 -0800 Subject: [PATCH 479/533] CLI: convert and run --export take --width, --height and --background The raster export already reads width, height and background, but the CLI only passed scale and ppi, so those options were reachable through the MCP export tool alone. convert and run now take --width N, --height N and --background V and send them for raster outputs only. A width or height that is not a positive finite number, and a missing or unreadable background, are refused when the flags are read, for every output format. Fixes #10577 --- apps/vectorcraft-cli/src/main.rs | 139 ++++++++++++++++++------ apps/vectorcraft-cli/tests/it/fileio.rs | 89 +++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 194 insertions(+), 37 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index c01f84edd9..51d2aec7b6 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -3,9 +3,9 @@ //! ```text //! vectorcraft-cli --safe-mode SUBCOMMAND ... //! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... -//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] +//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] //! vectorcraft-cli commands -//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] +//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] //! vectorcraft-cli info FILE //! vectorcraft-cli thumbnail [--size 256] IN OUT //! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5] @@ -98,12 +98,16 @@ USAGE: heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either, and a grant accepted under this flag lasts for that session only. - vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--allow-plugin-grants] + vectorcraft-cli run [--in FILE] [--cmd ID [--params JSON] | --commands FILE|-]... [--export FILE]... [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--allow-plugin-grants] Headless batch: open FILE (any readable format) or start a new document, run commands in order, export each FILE in the format its extension picks (see Writable formats; a .ait FILE is a template, written as file.saveAsTemplate writes it). Raster exports use the document's raster effects resolution unless --scale (pixels per point) or --ppi (pixels per inch, wins - over --scale) is given; other formats leave them out. Prints one JSON result per step. + over --scale) is given. --width or --height sets the size of each raster file in pixels, the + other side in proportion (--width wins over --height, and both win over --ppi and --scale), + within 0.01 to 64 pixels per point. + --background is transparent, none, white, black or a color such as #ff8800. Other formats + leave these options out. Prints one JSON result per step. --commands reads steps from FILE, or from standard input for -, where it stands among the --cmd and --export steps: a JSON array of {\"command\": ID, \"params\": {...}} (or \"id\" for \"command\"), or one such object per line (JSON Lines), at most 64 MiB and 100000 steps. @@ -114,10 +118,13 @@ USAGE: vectorcraft-cli commands Print the command catalogue as JSON. - vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] + vectorcraft-cli convert IN OUT [--scale N] [--ppi N] [--width N] [--height N] [--background V] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit] Open IN (any readable format) and export OUT in the format its extension picks (see Writable - formats). Raster resolution: --ppi, else 72 times --scale, else the document's raster effects - resolution; other formats leave them out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard + formats). Raster size: --width, else --height (pixels, the other side in proportion, within + 0.01 to 64 pixels per point), else --ppi, else 72 times --scale, else the document's raster + effects resolution. --background + is transparent, none, white, black or a color such as #ff8800. Other formats leave these + options out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard unless one of them is given, EPS the bounds of the art, the other formats the first artboard. A .ait OUT is a template of every artboard, written as file.saveAsTemplate writes it (not with --artboard or --range). @@ -367,6 +374,9 @@ fn convert(args: &[String]) -> Result<(), String> { "--scale", "-s", "--ppi", + "--width", + "--height", + "--background", "--artboard", "-a", "--range", @@ -381,9 +391,9 @@ fn convert(args: &[String]) -> Result<(), String> { return help(); } let mut files = vec![]; - let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = - (None::, None::, None::, false, false, false, false); - let mut ppi = None::; + let (mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) = + (None::, None::, false, false, false, false); + let mut size = RasterSize::default(); let mut decimals = None::; // The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s // `legacyNameEncoding`; the engine checks it. @@ -394,15 +404,11 @@ fn convert(args: &[String]) -> Result<(), String> { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { - "--scale" | "-s" => scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), - "--ppi" => { - ppi = Some( - it.next() - .and_then(|v| v.parse().ok()) - .filter(|n: &f64| n.is_finite() && *n > 0.0) - .ok_or("--ppi needs a positive finite number")?, - ); - } + "--scale" | "-s" => size.scale = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--scale needs a number")?), + "--ppi" => size.ppi = Some(positive("--ppi", it.next())?), + "--width" => size.width = Some(positive("--width", it.next())?), + "--height" => size.height = Some(positive("--height", it.next())?), + "--background" => size.background = Some(background_flag(it.next())?), "--artboard" | "-a" => artboard = Some(it.next().and_then(|v| v.parse().ok()).ok_or("--artboard needs an index")?), "--range" | "-r" => range = Some(it.next().cloned().ok_or("--range needs artboards such as 1-3,5")?), "--outline-text" => outline_text = true, @@ -442,7 +448,7 @@ fn convert(args: &[String]) -> Result<(), String> { ("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy})) } else { let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy}); - let mut params = with_pixel_scale(params, &output, scale, ppi); + let mut params = with_pixel_scale(params, &output, &size); // An option the format doesn't read comes back in the warnings, so each goes out only // when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the // formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects, @@ -498,17 +504,58 @@ fn is_template(path: &str) -> bool { vectorcraft_engine::cmd::fileio::format_for_name(path).is_some_and(|f| f.id == "ait") } -/// The export `params` for `path`, with explicit raster resolution options only for raster formats. +/// The raster size and background options of `convert` and `run`: `--scale`, `--ppi`, `--width`, +/// `--height` and `--background`. The engine checks the background and applies the precedence +/// (width, then height, then ppi, then scale). +#[derive(Default)] +struct RasterSize { + scale: Option, + ppi: Option, + width: Option, + height: Option, + background: Option, +} + +/// A pixel size or resolution flag's value: a positive finite number. +fn positive(flag: &str, raw: Option<&String>) -> Result { + raw.and_then(|v| v.parse::().ok()) + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{flag} needs a positive finite number{}", raw.map(|r| format!(", not {r}")).unwrap_or_default())) +} + +/// A `--background` value, checked when the flag is read so that a bad or missing value is refused +/// for every output format: transparent, none, white, black or a color the engine reads. +fn background_flag(raw: Option<&String>) -> Result { + let ok = raw.filter(|v| { + ["transparent", "none", "white", "black"].iter().any(|k| v.eq_ignore_ascii_case(k)) + || vectorcraft_engine::cmd::color_value(&json!(v)).is_some() + }); + ok.cloned().ok_or_else(|| { + let got = raw.map(|r| format!(", not {r}")).unwrap_or_default(); + format!("--background needs transparent, none, white, black or a color such as #ff8800{got}") + }) +} + +/// The export `params` for `path`, with explicit raster size options only for raster formats. /// DXF has a `scale` of its own (drawing units per unit), which would resize the drawing and leave /// its units unset. -fn with_pixel_scale(mut params: Value, path: &str, scale: Option, ppi: Option) -> Value { +fn with_pixel_scale(mut params: Value, path: &str, size: &RasterSize) -> Value { if vectorcraft_engine::cmd::fileio::writable_format(None, Some(path)).is_ok_and(|f| f.raster) { - if let Some(scale) = scale { + if let Some(scale) = size.scale { params["scale"] = json!(scale); } - if let Some(ppi) = ppi { + if let Some(ppi) = size.ppi { params["ppi"] = json!(ppi); } + if let Some(width) = size.width { + params["width"] = json!(width); + } + if let Some(height) = size.height { + params["height"] = json!(height); + } + if let Some(background) = &size.background { + params["background"] = json!(background); + } } params } @@ -698,7 +745,23 @@ fn command_step(v: Value) -> Result { } fn run(args: &[String]) -> Result<(), String> { - let valued = ["--in", "-i", "--cmd", "-c", "--params", "-p", "--commands", "--export", "-o", "--scale", "-s", "--ppi"]; + let valued = [ + "--in", + "-i", + "--cmd", + "-c", + "--params", + "-p", + "--commands", + "--export", + "-o", + "--scale", + "-s", + "--ppi", + "--width", + "--height", + "--background", + ]; if help_requested(args, &valued) { return help(); } @@ -707,8 +770,7 @@ fn run(args: &[String]) -> Result<(), String> { // The step of the `--cmd` just given, which a `--params` sets. let mut params_for: Option = None; let mut stdin_read = false; - let mut scale = None::; - let mut ppi = None::; + let mut size = RasterSize::default(); let mut allow_grants = false; let mut it = args.iter(); while let Some(a) = it.next() { @@ -747,17 +809,22 @@ fn run(args: &[String]) -> Result<(), String> { "--allow-plugin-grants" => allow_grants = true, "--scale" | "-s" => { let raw = val("a number")?; - scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); + size.scale = Some(raw.parse::().map_err(|_| format!("--scale {raw}: not a number"))?); } - "--ppi" => { + "--ppi" | "--width" | "--height" => { let raw = val("a number")?; - ppi = Some( - raw.parse::() - .ok() - .filter(|n| n.is_finite() && *n > 0.0) - .ok_or_else(|| format!("--ppi {raw}: needs a positive finite number"))?, - ); + let n = raw + .parse::() + .ok() + .filter(|n| n.is_finite() && *n > 0.0) + .ok_or_else(|| format!("{a} {raw}: needs a positive finite number"))?; + match a.as_str() { + "--ppi" => size.ppi = Some(n), + "--width" => size.width = Some(n), + _ => size.height = Some(n), + } } + "--background" => size.background = Some(background_flag(Some(&val("a background")?))?), other => return Err(format!("unknown run option `{other}`")), } } @@ -801,7 +868,7 @@ fn run(args: &[String]) -> Result<(), String> { let r = if is_template(&path) { h.call("engine.execute", json!({"command": "file.saveAsTemplate", "params": {"path": path, "format": "ait"}})) } else { - h.call("app.export", with_pixel_scale(json!({"path": path}), &path, scale, ppi)) + h.call("app.export", with_pixel_scale(json!({"path": path}), &path, &size)) }; let r = r.map_err(|e| format!("step {n}: export {path}: {e}"))?; emit(json!({"step": "export", "result": r}))?; diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index cdb16d28d3..60486d27e7 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -135,6 +135,95 @@ fn raster_export_rejects_invalid_ppi() { } } +/// The pixel size in a PNG's IHDR. +fn png_size(path: &str) -> (u32, u32) { + let bytes = std::fs::read(path).unwrap(); + let be = |i: usize| u32::from_be_bytes([bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]]); + (be(16), be(20)) +} + +/// #10577: `convert` and `run --export` take `--width`, `--height` and `--background` for raster +/// outputs and leave them out of other formats. +#[test] +fn raster_export_takes_width_height_and_background() { + let source = tmp("size.vectorcraft"); + ok(&[ + "run", + "--cmd", + "file.new", + "--params", + r#"{"width":100,"height":50}"#, + "--cmd", + "document.setup", + "--params", + r#"{"backgroundContents":"white"}"#, + "--cmd", + "shape.rectangle", + "--params", + r#"{"x":40,"y":20,"width":20,"height":10}"#, + "--export", + &source, + ]); + let wide = tmp("wide.png"); + ok(&["convert", &source, &wide, "--width", "400"]); + assert_eq!(png_size(&wide), (400, 200)); + let high = tmp("high.png"); + ok(&["convert", &source, &high, "--height", "100", "--ppi", "300"]); + assert_eq!(png_size(&high), (200, 100)); + let both = tmp("both.png"); + ok(&["convert", &source, &both, "--width", "300", "--height", "10"]); + assert_eq!(png_size(&both), (300, 150), "--width wins over --height"); + let run = tmp("run.png"); + ok(&["run", "--in", &source, "--export", &run, "--width", "64"]); + assert_eq!(png_size(&run), (64, 32)); + + let clear = tmp("clear.png"); + ok(&["convert", &source, &clear, "--background", "transparent"]); + let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&clear).unwrap()).unwrap(); + assert_eq!(img.pixel(0, 0)[3], 0, "--background transparent wins over the document's white background"); + let orange = tmp("orange.png"); + ok(&["run", "--in", &source, "--export", &orange, "--background", "#ff8800"]); + let img = vectorcraft_testkit::raster::Image::from_png(&std::fs::read(&orange).unwrap()).unwrap(); + vectorcraft_testkit::raster::assert_pixel(&img, 0, 0, [255, 136, 0, 255], 1); + + // Other formats leave the options out. + let svg = tmp("size.svg"); + let plain = tmp("plain.svg"); + let r: Value = serde_json::from_str(&ok(&["convert", &source, &svg, "--width", "400", "--height", "9", "--background", "#ff8800"])).unwrap(); + let warnings = r["warnings"].as_array().cloned().unwrap_or_default(); + assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| ["width", "height", "background"].iter().any(|k| s.contains(k)))), "{r}"); + ok(&["convert", &source, &plain]); + assert_eq!(std::fs::read(&svg).unwrap(), std::fs::read(&plain).unwrap()); +} + +#[test] +fn raster_export_rejects_invalid_width_height_and_background() { + for (flag, value, message) in [ + ("--width", "0", "positive finite number"), + ("--width", "abc", "positive finite number"), + ("--height", "-5", "positive finite number"), + ("--background", "chartreuse-ish", "background"), + ] { + let source = tmp("reject.vectorcraft"); + ok(&["run", "--export", &source]); + let png = tmp("reject.png"); + for args in [vec!["run", "--in", &source, "--export", &png, flag, value], vec!["convert", &source, &png, flag, value]] { + let out = Command::new(crate::bin()).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains(message), "{args:?}: {out:?}"); + } + } + // A bad or missing background is refused for formats that leave it out too, so it can't take + // the next flag as its value. + let source = tmp("reject.vectorcraft"); + let svg = tmp("reject.svg"); + for args in [vec!["convert", &source, &svg, "--background", "--outline-text"], vec!["convert", &source, &svg, "--background"]] { + let out = Command::new(crate::bin()).args(&args).output().unwrap(); + assert!(!out.status.success(), "{args:?}"); + assert!(String::from_utf8_lossy(&out.stderr).contains("--background needs"), "{args:?}: {out:?}"); + } +} + #[test] fn help_lists_readable_formats() { let out = ok(&["--help"]); diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..c92cd17a92 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1578,7 +1578,8 @@ Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard (with `useArtboards`, each file), `rect` or art bounds gets the scale that makes it that wide or high, within 0.01–64 pixels per point, and the file stores the resolution that results, as with `ppi`. `width` wins over `height`, and -either one wins over `ppi` and `scale`. A value that is not a positive number is refused. Export for Screens rows keep +either one wins over `ppi` and `scale`. A value that is not a positive number is refused. CLI `run --export` and +`convert` pass `--width N`, `--height N` and `--background V` on as these options for raster outputs. Export for Screens rows keep their own size (`scale: "512w"`). WebP is lossless by default (`lossless: true`). `{"format": "webp", "lossless": false, "quality": 60}` writes a lossy From 74d8757ef50e2dac09e1276f86af07f6441c62cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:01:21 -0800 Subject: [PATCH 480/533] Find and Replace: the params text and docs/mcp.md say which tab runs each action ui.dialog.confirm refuses an action whose button the open tab does not show. The ui.paramDialog params text (crates/mcp/src/ui_catalog.rs and crates/ui-egui/src/menus/ui_commands.rs) and docs/mcp.md now say so. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 4 +++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index acbbb5d151..1046cae532 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1018,7 +1018,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e131421a2a..458bdf224b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1019,7 +1019,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..42af992810 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14318,7 +14318,9 @@ In the app, Edit › Find and Replace… opens a dialog that stays open (kind `f fields, Match Case, Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers, and Find, Replace, Replace & Find, Replace All and Done. Its fields are `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, `hiddenLayers`, `lockedLayers` and `action`; `ui.dialog.confirm` runs the `action`: `find` (the default), `replace`, -`replaceFind`, `replaceAll` or `done`, which closes the dialog. The dialog shows the match found in its line of text +`replaceFind`, `replaceAll` or `done`, which closes the dialog. It refuses an `action` whose button the open tab does +not show: `find` runs on the Find and Replace tabs, `replace`, `replaceFind` and `replaceAll` on the Replace tab, and +`done` on every tab. The dialog shows the match found in its line of text with its place among the matches. Replace and Replace & Find change a match that Find reached with the Find text and the options as they are now, and find one otherwise. Enter runs Find. Edit › Find Next goes on from the dialog's last search while the dialog is closed, and opens the dialog when there has been none. A place the search reached in one From 79a68f6469506db31a8d1a96a730333efdd29435 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:21:44 -0800 Subject: [PATCH 481/533] 3D: large caps are cut into triangles without testing every corner per ear Cutting a face into triangles tested each candidate ear against every corner left in the ring, so a cap with n corners took about n * n / 2 tests. An Extrude & Bevel with a Rounded bevel on an 18,204-corner polygon spent most of its mesh time there. Rings with more than 64 corners now sort their corners into a grid of square cells, and an ear looks only at the corners in the cells its triangle covers, widened by a margin well past the rounding of the corner tests. Ears with an angle whose sine is below 1e-6 still test every corner. The decision for each ear is the same, so the triangles are the same as before. --- crates/three-d/src/mesh.rs | 170 +++++++++++++++++++++++++++---- crates/three-d/src/mesh/tests.rs | 79 ++++++++++++++ 2 files changed, 231 insertions(+), 18 deletions(-) diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index 53e1cb5786..77c6371e49 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -527,41 +527,174 @@ fn bridge(ring: Vec, hole: &[Corner], others: &[Vec], work: &mut /// is set and it lies straight between them: it then stays a corner of the triangles beside it. If /// no ear is left (a ring that crosses itself), the rest is cut as a fan. fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> { + let grid = if ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + cut(ring, out, work, keep_straight, grid.as_ref()).map(|_| ()) +} + +/// Rings with more corners than this are sorted into a [`Grid`] before they are cut. +const GRID_CORNERS: usize = 64; + +/// The corners of a ring sorted into square cells, so that the test of an ear looks only at the +/// corners in the cells its triangle covers, widened by `margin`. +struct Grid { + x: f64, + y: f64, + size: f64, + cols: usize, + rows: usize, + /// Where each cell's corners start in `corners`, row by row, with the end of the last cell + /// after them. + start: Vec, + corners: Vec, + /// How far outside a triangle the cells looked at reach: far more than the rounding of the + /// tests of a corner against the triangle's edges, at the size and distance from the origin of + /// the ring. + margin: f64, +} + +impl Grid { + /// The grid of `ring`, about one corner to a cell. `None` for a ring with a corner that is not + /// finite or with no extent. + fn new(ring: &[Corner]) -> Option { + if !ring.iter().all(|c| c.x.is_finite() && c.y.is_finite()) { + return None; + } + let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for c in ring { + (x0, y0, x1, y1) = (x0.min(c.x), y0.min(c.y), x1.max(c.x), y1.max(c.y)); + } + let extent = (x1 - x0).max(y1 - y0); + let size = extent / (ring.len() as f64).sqrt().ceil(); + if !(size > 0.0 && size.is_finite()) { + return None; + } + let (cols, rows) = (((x1 - x0) / size) as usize + 1, ((y1 - y0) / size) as usize + 1); + let cells = cols.checked_mul(rows)?; + let reach = x0.abs().max(x1.abs()).max(y0.abs()).max(y1.abs()); + let margin = (extent + reach) * 1e-6 + 1e-8; + let mut grid = Grid { x: x0, y: y0, size, cols, rows, start: vec![], corners: vec![], margin }; + let mut start = vec![0usize; cells + 1]; + for c in ring { + start[grid.cell(c) + 1] += 1; + } + for k in 1..start.len() { + start[k] += start[k - 1]; + } + let mut fill = start.clone(); + let mut corners = vec![0; ring.len()]; + for (k, c) in ring.iter().enumerate() { + let at = &mut fill[grid.cell(c)]; + corners[*at] = k; + *at += 1; + } + (grid.start, grid.corners) = (start, corners); + Some(grid) + } + + fn col(&self, x: f64) -> usize { + (((x - self.x) / self.size).max(0.0) as usize).min(self.cols - 1) + } + + fn row(&self, y: f64) -> usize { + (((y - self.y) / self.size).max(0.0) as usize).min(self.rows - 1) + } + + fn cell(&self, c: &Corner) -> usize { + self.row(c.y) * self.cols + self.col(c.x) + } + + /// Whether `blocks` holds for a corner in a cell that triangle `t` covers, widened by the + /// margin. Every corner within the margin of the triangle is in such a cell. + fn any_near(&self, t: [&Corner; 3], mut blocks: impl FnMut(usize) -> bool) -> bool { + let m = self.margin; + let low = t.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let high = t.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + for r in self.row(low - m)..=self.row(high + m) { + // The triangle's extent across the row's band, widened by the margin each way. + let top = self.y + r as f64 * self.size; + let (from, to) = ((top - m).clamp(low, high), (top + self.size + m).clamp(low, high)); + let (mut left, mut right) = (f64::INFINITY, f64::NEG_INFINITY); + for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + let (p, q) = if p.y <= q.y { (p, q) } else { (q, p) }; + if q.y < from || p.y > to { + continue; + } + let xs = if q.y > p.y { + let at = |y: f64| p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x); + [at(from.max(p.y)), at(to.min(q.y))] + } else { + [p.x, q.x] + }; + for x in xs { + (left, right) = (left.min(x), right.max(x)); + } + } + if left > right { + continue; + } + for col in self.col(left - m)..=self.col(right + m) { + let cell = r * self.cols + col; + if self.corners[self.start[cell]..self.start[cell + 1]].iter().any(|&k| blocks(k)) { + return true; + } + } + } + false + } +} + +/// [`clip`], looking up the corners an ear's test needs in `grid` when there is one, for a triangle +/// whose every angle has a sine of at least 1e-6: a corner that passes the test then lies within +/// the grid's margin of the triangle. Other ears test every corner left. Returns the number of +/// corners tested against ears. +fn cut(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool, grid: Option<&Grid>) -> Result { let n = ring.len(); if n < 3 { - return Ok(()); + return Ok(0); } let mut next: Vec = (1..=n).map(|i| i % n).collect(); let mut prev: Vec = (0..n).map(|i| (i + n - 1) % n).collect(); - let (mut left, mut i, mut tried) = (n, 0usize, 0usize); + let mut gone = vec![false; n]; + let (mut left, mut i, mut tried, mut tested) = (n, 0usize, 0usize, 0usize); let cross = |a: &Corner, b: &Corner, c: &Corner| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); let same = |a: &Corner, b: &Corner| (a.x - b.x).hypot(a.y - b.y) < 1e-12; while left > 3 { let (a, c) = (prev[i], next[i]); let (pa, pb, pc) = (&ring[a], &ring[i], &ring[c]); let turn = cross(pa, pb, pc); - let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y); + let (ab, bc) = ((pb.x - pa.x).hypot(pb.y - pa.y), (pc.x - pb.x).hypot(pc.y - pb.y)); + let scale = ab * bc; let mut ear = false; let flat = turn.abs() <= 1e-12 * scale.max(1e-300); let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0; let drop = flat && !straight; if !flat && turn > 0.0 { spend(work, left)?; - ear = true; - let mut k = next[c]; - while k != a { + // A corner inside the ear, or a kept corner on the ear's new edge, which would be + // left off every triangle. + let mut blocks = |k: usize| { + if k == a || k == i || k == c || gone[k] { + return false; + } + tested += 1; let p = &ring[k]; - if !same(p, pa) && !same(p, pb) && !same(p, pc) && cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 { - ear = false; - break; + (cross(pa, pb, p) > 0.0 && cross(pb, pc, p) > 0.0 && cross(pc, pa, p) > 0.0 && !same(p, pa) && !same(p, pb) && !same(p, pc)) + || (keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y))) + }; + let ca = (pa.x - pc.x).hypot(pa.y - pc.y); + let blocked = match grid { + Some(grid) if turn >= 1e-6 * (ab * bc).max(ab * ca).max(bc * ca) => grid.any_near([pa, pb, pc], &mut blocks), + _ => { + let mut k = next[c]; + let mut found = false; + while k != a && !found { + found = blocks(k); + k = next[k]; + } + found } - // A kept corner on the ear's new edge would be left off every triangle. - if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) { - ear = false; - break; - } - k = next[k]; - } + }; + ear = !blocked; } if !ear && !drop && tried > left { // No ear anywhere: cut what is left as a fan. @@ -571,7 +704,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight out.push([ring[start].v, ring[k].v, ring[next[k]].v]); k = next[k]; } - return Ok(()); + return Ok(tested); } if ear || drop { if ear { @@ -579,6 +712,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } next[a] = c; prev[c] = a; + gone[i] = true; left -= 1; i = a; tried = 0; @@ -589,7 +723,7 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight } let (a, c) = (prev[i], next[i]); out.push([ring[a].v, ring[i].v, ring[c].v]); - Ok(()) + Ok(tested) } #[cfg(test)] diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 29d58a66f6..a4048f82ca 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -235,6 +235,85 @@ fn flat_triangles_stop_at_their_budget() { assert!(work >= all, "{work} of {all}"); } +fn ring_of(points: &[(f64, f64)]) -> Vec { + points.iter().map(|&(x, y)| Corner { x, y, v: V3(x, y, 0.0) }).collect() +} + +/// `n` corners on a circle of radius `r` about (`x`, `y`), every other one pulled in to `inner` +/// times the radius, counterclockwise, or clockwise when `back` is set. +fn star_ring(n: usize, x: f64, y: f64, r: f64, inner: f64, back: bool) -> Vec { + let mut points: Vec<(f64, f64)> = (0..n) + .map(|i| { + let (s, c) = (std::f64::consts::TAU * i as f64 / n as f64).sin_cos(); + let r = if i % 2 == 1 { r * inner } else { r }; + (x + r * c, y + r * s) + }) + .collect(); + if back { + points.reverse(); + } + ring_of(&points) +} + +/// The triangles `ring` is cut into, with the ring's corners sorted into a grid as [`clip`] sorts +/// them, or without one, and the number of corners tested against ears. +fn cut_ring(ring: &[Corner], keep_straight: bool, grid: bool) -> (Vec<[[u64; 3]; 3]>, usize) { + let grid = if grid && ring.len() > GRID_CORNERS { Grid::new(ring) } else { None }; + let (mut out, mut work) = (vec![], 0); + let tested = cut(ring, &mut out, &mut work, keep_straight, grid.as_ref()).unwrap(); + (out.into_iter().map(|t| t.map(|v| [v.0.to_bits(), v.1.to_bits(), v.2.to_bits()])).collect(), tested) +} + +#[test] +fn a_large_cap_is_cut_testing_few_corners_per_ear() { + // Tested against every corner left, the ears of a ring of n corners test about n * n / 2. + let n = 4096; + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 1.0, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a ring of {n} corners tested {tested} corners against its ears"); + let (triangles, tested) = cut_ring(&star_ring(n, 0.0, 0.0, 100.0, 0.9, false), false, true); + assert_eq!(triangles.len(), n - 2); + assert!(tested <= 64 * n, "a star of {n} corners tested {tested} corners against its ears"); +} + +#[test] +fn rings_cut_with_a_grid_give_the_triangles_cut_without_one() { + let mut rings = vec![ + star_ring(500, 0.0, 0.0, 100.0, 1.0, false), + star_ring(1000, 3.0, -7.0, 50.0, 0.4, false), + star_ring(999, 0.0, 0.0, 1.0, 0.97, false), + // Far from the origin, where the rounding of the tests is largest. + star_ring(800, 1e7, -3e7, 20.0, 0.6, false), + ]; + // Holes bridged to their outline, so that some corners appear twice. + let mut work = 0; + let mut outline = star_ring(600, 0.0, 0.0, 100.0, 0.8, false); + for (k, (x, y)) in [(30.0, 0.0), (-20.0, 25.0), (-10.0, -40.0)].into_iter().enumerate() { + let hole = star_ring(90 + 10 * k, x, y, 12.0, 0.5, true); + outline = bridge(outline, &hole, &[], &mut work).unwrap(); + } + rings.push(outline); + // Edges carrying corners midway, as a cell shares with its finer neighbors. + let mut square = vec![]; + for (from, to) in [((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), (0.0, 10.0)), ((0.0, 10.0), (0.0, 0.0))] { + for i in 0..40 { + let t = i as f64 / 40.0; + square.push((from.0 + (to.0 - from.0) * t, from.1 + (to.1 - from.1) * t)); + } + } + let square = ring_of(&square); + let dent = ring_of(&[(4.0, 4.0), (4.0, 6.0), (6.0, 6.0), (6.0, 5.0), (6.0, 4.0), (5.0, 4.0)]); + rings.push(bridge(square.clone(), &dent, &[], &mut work).unwrap()); + rings.push(square); + for (k, ring) in rings.iter().enumerate() { + for keep_straight in [false, true] { + let (with, _) = cut_ring(ring, keep_straight, true); + let (without, _) = cut_ring(ring, keep_straight, false); + assert!(with == without, "ring {k} (keep_straight {keep_straight}) is cut into other triangles with a grid"); + } + } +} + #[test] fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() { for points in [ From eb544fee30f35cda0bd064db9eb1a169fddd558e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:29:23 -0800 Subject: [PATCH 482/533] Export: warn when the pixel scale limit changes a requested width or height A raster width or height that needs more than 64 or less than 0.01 pixels per point was written at the clamped size with no note. The export now adds a warning naming the requested and the written size, for MCP export and the CLI's --width and --height alike. --- apps/vectorcraft-cli/tests/it/fileio.rs | 13 +++++++++++ crates/engine/src/cmd/fileio/encode.rs | 23 ++++++++++++++++--- crates/engine/src/cmd/fileio/tests_raster.rs | 24 ++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 59 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft-cli/tests/it/fileio.rs b/apps/vectorcraft-cli/tests/it/fileio.rs index 60486d27e7..9593d2630e 100644 --- a/apps/vectorcraft-cli/tests/it/fileio.rs +++ b/apps/vectorcraft-cli/tests/it/fileio.rs @@ -196,6 +196,19 @@ fn raster_export_takes_width_height_and_background() { assert_eq!(std::fs::read(&svg).unwrap(), std::fs::read(&plain).unwrap()); } +#[test] +fn raster_export_warns_when_width_is_clamped() { + let source = tmp("clamped-size.vectorcraft"); + ok(&["run", "--cmd", "file.new", "--params", r#"{"width":16,"height":8}"#, "--export", &source]); + let output = tmp("clamped-width.png"); + let r: Value = serde_json::from_str(&ok(&["convert", &source, &output, "--width", "1920"])).unwrap(); + assert_eq!(png_size(&output).0, 1024); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|s| s.contains("1920"))), "{r}"); + for path in [source, output] { + let _ = std::fs::remove_file(path); + } +} + #[test] fn raster_export_rejects_invalid_width_height_and_background() { for (flag, value, message) in [ diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index a79ac295e5..96e5d2210f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1210,12 +1210,29 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { vectorcraft_doc::cancel::progress(done as u64, total, &format!("Rendering artboard {} of {total}", done + 1)); let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; // `width` or `height`: each file gets the scale that makes its region that size. - if let Some(size) = size { - settings.ppi = clamped_ppi(72.0 * size.scale_for(C, region)?); + let requested_scale = size.map(|size| size.scale_for(C, region)).transpose()?; + if let Some(scale) = requested_scale { + settings.ppi = clamped_ppi(72.0 * scale); } let scale = settings.scale(); check_format_size(f, region.width() * scale, region.height() * scale)?; - vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + let (width, height) = vectorcraft_render::raster_size(region, scale).map_err(|e| bad(C, e))?; + if let Some(requested_scale) = requested_scale.filter(|scale| !(0.01..=64.0).contains(scale)) { + let dimension = match size { + Some(ScreenSize::Width(requested)) => Some(("width", requested, width, "wide")), + Some(ScreenSize::Height(requested)) => Some(("height", requested, height, "high")), + _ => None, + }; + if let Some((axis, requested, written, direction)) = dimension + && f64::from(written) != requested + { + let limit = if requested_scale > 64.0 { "more than 64" } else { "less than 0.01" }; + enc.add_setting_notes([format!( + "{axis} {requested} px needs {limit} pixels per point: artboard {} was written {written} px {direction}", + b + 1 + )]); + } + } enc.maps.extend(imagemap::build(doc, region, scale, map, enc.files.len())); let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?; // File Info as PNG text chunks. diff --git a/crates/engine/src/cmd/fileio/tests_raster.rs b/crates/engine/src/cmd/fileio/tests_raster.rs index b43f3d0547..93e875b35a 100644 --- a/crates/engine/src/cmd/fileio/tests_raster.rs +++ b/crates/engine/src/cmd/fileio/tests_raster.rs @@ -397,6 +397,30 @@ fn width_or_height_sets_the_pixel_size_of_a_raster_export() { assert_eq!(size(&mut s, json!({"format": "png", "width": 1})), (2, 1), "the scale stays at 0.01 pixels per point or more"); } +#[test] +fn raster_pixel_size_clamping_reports_the_requested_and_written_size() { + for (points, axis, requested, written, limit, direction) in [ + ((16.0, 8.0), "width", 1920, 1024, "more than 64", "wide"), + ((16.0, 8.0), "height", 1920, 512, "more than 64", "high"), + ((200.0, 100.0), "width", 1, 2, "less than 0.01", "wide"), + ((100.0, 200.0), "height", 1, 2, "less than 0.01", "high"), + ] { + let mut s = session(points.0, points.1, 1); + s.paint.stroke = vectorcraft_color::Paint::None; + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": points.0, "height": points.1})).unwrap(); + for extra in [json!({}), json!({"rect": [0, 0, points.0, points.1]}), json!({"useArtboards": false})] { + let mut p = json!({"format": "png"}); + p[axis] = json!(requested); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let r = s.execute("document.export", &p).unwrap(); + let size = rgba(&b64(&r)).dimensions(); + assert_eq!(if axis == "width" { size.0 } else { size.1 }, written, "{p}"); + let note = format!("{axis} {requested} px needs {limit} pixels per point: artboard 1 was written {written} px {direction}"); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str() == Some(note.as_str())), "{p}: {r}"); + } + } +} + #[test] fn a_width_or_height_that_is_not_a_positive_number_is_refused() { let mut s = session(200.0, 100.0, 1); diff --git a/docs/mcp.md b/docs/mcp.md index c92cd17a92..d10a911f14 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1578,7 +1578,8 @@ Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard (with `useArtboards`, each file), `rect` or art bounds gets the scale that makes it that wide or high, within 0.01–64 pixels per point, and the file stores the resolution that results, as with `ppi`. `width` wins over `height`, and -either one wins over `ppi` and `scale`. A value that is not a positive number is refused. CLI `run --export` and +either one wins over `ppi` and `scale`. A value that is not a positive number is refused. When that range keeps a +file from the requested size, the reply's `warnings` name the requested and the written size. CLI `run --export` and `convert` pass `--width N`, `--height N` and `--background V` on as these options for raster outputs. Export for Screens rows keep their own size (`scale: "512w"`). From b4580f9fb9a2a3b0de5968c4f938d805dd308864 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:42:11 -0800 Subject: [PATCH 483/533] Blend: steps between rounded rectangles keep round corners Steps between two live rectangles were made by matching the keys' anchors and moving each anchor and handle in a straight line. When the keys' corners had different anchor layouts (a sharp rectangle and a rounded one, or radii too large for one key), the steps' corners came out as skewed curves, and every step lost its live rectangle. Steps between two live rectangles with the same corner kinds and the same rotation, reflection and shear are now live rectangles whose width, height, position and corner radii lie between the keys'. Each key's radii are the radii it draws, so a stored radius too large for its rectangle counts as the largest that fits. A start anchor given for either key, and every other pair, keep anchor matching. Fixes #10707 --- crates/doc/src/blend.rs | 154 ++++++++++++++++++++++++- crates/engine/src/cmd/live/commands.rs | 2 +- docs/mcp.md | 7 +- docs/target-app-parity.md | 1 + 4 files changed, 161 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 7c40d9d133..c7ec77ac7f 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -21,11 +21,12 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; +use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; -use crate::node::{Node, NodeId, NodeKind}; +use crate::node::{LiveShape, Node, NodeId, NodeKind}; use crate::text::TextObject; // ===================================================================================== @@ -1032,6 +1033,9 @@ enum Shape { /// Paths and compound paths; `members`: the subpath count of each member when both keys are /// compound paths. Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec, Vec)> }, + /// Two live rectangles: each step is a live rectangle whose size, transform and corner radii + /// lie between the keys'. A shared shear or nonuniform scale makes the corners elliptical. + LiveRect(Box<(LiveRectParts, LiveRectParts)>), /// Text, symbols and images: their transforms interpolate. Placed, /// Anything else: a copy of the nearer key moved and scaled into the interpolated box. @@ -1046,6 +1050,47 @@ pub struct Lerp { shape: Shape, } +/// A live rectangle's size, transform, corner kinds and corner radii in document units. +#[derive(Clone, Debug)] +struct LiveRectParts { + w: f64, + h: f64, + radii: [f64; 4], + kinds: [CornerKind; 4], + xf: Affine, +} + +/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws. +fn live_rect(s: &LiveShape) -> Option { + let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None }; + let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h)); + let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative); + let corners = vectorcraft_geom::corners::path_corners(&base); + let mut drawn = [0.0; 4]; + for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) { + if let Some(d) = drawn.get_mut(c.index) { + *d = r; + } + } + Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf }) +} + +/// The parts of `a` and `b` when steps between them can be live rectangles: both are live +/// rectangles with the same corner kinds and the same rotation, reflection and shear, so each step +/// only moves and resizes. +fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> { + let (x, y) = (live_rect(a)?, live_rect(b)?); + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + let scale = p[..4].iter().chain(&q[..4]).map(|c| c.abs()).fold(0.0, f64::max); + let determinant_sign = |c: [f64; 6]| { + let scale = if scale > 0.0 { scale } else { 1.0 }; + let det = (c[0] / scale) * (c[3] / scale) - (c[1] / scale) * (c[2] / scale); + (det > 0.0, det < 0.0) + }; + (x.kinds == y.kinds && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() <= 1e-9 * scale) && determinant_sign(p) == determinant_sign(q)) + .then_some((x, y)) +} + /// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has. fn collapsed(n: &Node, c: Point) -> Node { let mut x = n.clone(); @@ -1083,6 +1128,12 @@ impl Lerp { | (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. }) | (NodeKind::Image(_), NodeKind::Image(_)) | (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed, + // A clicked start point asks for anchors to be paired; the path route does that. + (NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. }) + if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) => + { + Shape::LiveRect(Box::new(parts)) + } _ => match (node_path(a), node_path(b)) { (Some((pa, ra, ma)), Some((pb, rb, mb))) => { Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) } @@ -1145,6 +1196,28 @@ impl Lerp { } } } + Shape::LiveRect(parts) => { + let (x, y) = &**parts; + let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); + let live = LiveShape::Rectangle { + w: lerp_f64(x.w, y.w, t), + h: lerp_f64(x.h, y.h, t), + radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)), + kinds: x.kinds, + radii_relative: false, + xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]), + }; + let rule = match &base.kind { + NodeKind::Path { rule, .. } => *rule, + _ => FillRule::default(), + }; + let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default()); + if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind { + *r = rule; + *l = Some(Box::new(live)); + } + n + } Shape::Placed => { let mut n = base.clone(); match (&mut n.kind, &a.kind, &b.kind) { @@ -2321,6 +2394,85 @@ mod tests { assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0)); } + /// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`. + fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node { + let live = + LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) }; + let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut n.kind { + *l = Some(Box::new(live)); + } + n + } + + /// The step's live radii, after checking that every curve of its outline is a circular arc of + /// that radius about the matching corner center. + fn round_step_radii(step: &Node) -> [f64; 4] { + let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") }; + let r = radii[0]; + let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default(); + let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y)); + let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default(); + let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count(); + assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}"); + for seg in path.segments() { + if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg { + for u in [0.0, 0.25, 0.5, 0.75, 1.0] { + let p = c.eval(u); + let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min); + assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}"); + } + } + } + *radii + } + + /// Steps between live rectangles are live rectangles whose corner radii lie between the keys'. + #[test] + fn steps_between_rounded_rectangles_keep_round_corners() { + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 20.0).abs() < 1e-9, "{r}"); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + for t in [0.25, 0.5, 0.75] { + for r in round_step_radii(&blend.at(t)) { + assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}"); + } + } + // A radius too large for its rectangle counts as the radius it draws. + let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None)); + for r in round_step_radii(&blend.at(0.5)) { + assert!((r - 10.0).abs() < 1e-9, "{r}"); + } + // Keys turned differently keep the anchor-by-anchor route. + let mut turned = rounded(300.0, 200.0, 60.0, 30.0); + turned.transform(Affine::rotate(0.5), false); + assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. })); + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::rotate(30.0_f64.to_radians()), false); + b.transform(Affine::rotate(390.0_f64.to_radians()), false); + let blend = Lerp::new(&a, &b, (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let step = blend.at(0.5); + let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") }; + let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") }; + assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]); + for starts in [(Some(0), None), (None, Some(0))] { + assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. })); + } + b.transform(Affine::scale_non_uniform(-1.0, 1.0), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + for scale in [1.0, 1e-200] { + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + let mut b = rounded(300.0, 100.0, 100.0, 30.0); + a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false); + b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false); + assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); + } + } + /// A step between two distorted images has its corners between the keys' corners. #[test] fn steps_between_distorted_images_have_corners_between_theirs() { diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index b44a26e645..5724498e14 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Blend"], Some("Cmd+Alt+B"), - "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", + "{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}", has_doc, blend_make ), diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..b4eac5addb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16808,7 +16808,12 @@ key holds a gradient or a pattern, the count is the largest distance between the bounding-box edges divided by their mean width (left and right edges) or height (top and bottom), rounded, less one, from 1 to 1000. Keys with no width or no height are measured by their other side, keys with neither in points, and keys without bounds make 1 step. `starts` gives, per object, the anchor of its first subpath the blend starts -from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). With the +from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). Steps +between two live rectangles with the same corner kinds and the same rotation, reflection and shear are live +rectangles whose width, height, position and corner radii lie between the keys'. Rounded corners stay circular +arcs only when the keys are not sheared and have no nonuniform scale in their transforms; a shared shear draws +elliptical corners on the canvas. Other path and live-shape pairs use anchor matching. A start anchor given in +`starts` for either key also sends live rectangles through anchor matching; an all-null `starts` does not. With the Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend just made; the document and the selection stay as they are. A blend among the objects takes the others in as more key objects, keeping its options, name, transparency and whether it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 594d6de35b..bd63035ba5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2132,6 +2132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. A triple-click on a face selects every face of its group with that face's fill, and on an edge every edge of its group that has its stroke paint ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)); hidden faces and edges are left out, and Shift-triple-click adds them to the selection or removes them from it. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. + Steps between live rectangles with matching corner kinds and equivalent linear transforms stay live rectangles with interpolated sizes, positions and corner radii. A start anchor given for either key selects anchor matching instead; all-null `starts` keeps live rectangles. Rounded corners stay circular only without shear or a nonuniform scale in the keys' transforms. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. From 93ed763cd404fa976f99a011c0191aea37989390 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:30:42 -0800 Subject: [PATCH 484/533] Fix #10639: the Color Picker and preview dialogs leave the canvas undimmed Every dialog has a modal rank with a scrim, and the cover layer leaves the scrim off only the canvas a dialog registers. The Color Picker opened from the Color panel or a shortcut and the Color Balance, Vector Halftone, Convert to Indexed Color, Step and Repeat, Transform Each and Flatten Transparency dialogs registered no canvas, so the scrim darkened the art while they previewed it. They now pass the current window's canvas, as the effect (#10297) and transform (#10255) dialogs do. The picker turns off canvas sampling, since the app does not take its canvas eyedropper request: the wheel, a middle-button drag and a drag with Space held still move the view under it, and other presses on the canvas do not reach the tools. --- crates/ui-egui/src/dialogs/color_balance.rs | 7 ++- crates/ui-egui/src/dialogs/color_picker.rs | 5 +++ .../ui-egui/src/dialogs/color_picker/tests.rs | 43 +++++++++++++++++++ crates/ui-egui/src/dialogs/flatten.rs | 9 +++- crates/ui-egui/src/dialogs/halftone.rs | 9 +++- crates/ui-egui/src/dialogs/indexed_color.rs | 6 ++- crates/ui-egui/src/dialogs/step_repeat.rs | 7 ++- crates/ui-egui/src/dialogs/transform_each.rs | 6 ++- docs/mcp.md | 3 ++ 9 files changed, 87 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_balance.rs b/crates/ui-egui/src/dialogs/color_balance.rs index 110c124717..f508f52904 100644 --- a/crates/ui-egui/src/dialogs/color_balance.rs +++ b/crates/ui-egui/src/dialogs/color_balance.rs @@ -93,8 +93,13 @@ impl Adjust { { old.preview.cancel(app); } + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| { - ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true) + let dialog = ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?; *(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() }); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 6863ee28a7..042e6c74c0 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -212,6 +212,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); } + // The canvas stays undimmed under the picker, so its live preview shows the true color. Presses on it stay blocked: + // the app does not take the picker's canvas eyedropper request. + if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { + dialog = dialog.canvas(canvas).canvas_samples(false); + } let id = dialogs.with(|h| h.open(dialog)); // A picker the open replaced leaves its preview behind: end it. if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) { diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 1abafe7025..4d7e820a29 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -451,3 +451,46 @@ fn the_artboard_picker_leaves_restored_artboards_unchanged() { assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef")); } } + +/// The picker keeps the document's canvas open under its modal layer (#10639): the canvas is not dimmed, so the live +/// preview shows the true color, and the wheel over the canvas still scrolls the view. +#[test] +fn the_canvas_stays_open_under_the_picker() { + let step = |app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); + }; + let (mut app, ctx) = app(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + app.run("ui.colorPicker", json!({})).unwrap(); + for _ in 0..3 { + step(&mut app, &ctx, vec![]); + } + assert!(!app.color_dialogs.pickers.is_empty(), "the picker is open"); + let at = app.canvas_view().unwrap().rect.left_top() + egui::vec2(20.0, 20.0); + for _ in 0..3 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + } + let before = app.canvas_view().unwrap().center; + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -3.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::default(), + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..5 { + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel.clone()]); + } + assert_ne!(app.canvas_view().unwrap().center, before, "the wheel over the canvas scrolls the view under the picker"); + // A click on the canvas stays blocked: it does not reach the tool and clear the selection. + let selected = app.session.doc().unwrap().selection.clone(); + let press = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::default() }; + step(&mut app, &ctx, vec![egui::Event::PointerMoved(at), press(true)]); + step(&mut app, &ctx, vec![press(false)]); + step(&mut app, &ctx, vec![]); + assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the picker leaves the selection"); +} diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index 2b3760f38f..796a829836 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -249,8 +249,13 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field /// Open Flatten Transparency for the selection with the default preset. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| { - ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true) + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), move |fields| { + let dialog = ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }) // Flattening complex art is slow: the preview waits until it is turned on. .preview_off(); diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index ebc54223f6..916208960a 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -84,9 +84,14 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); - let dialog = HostedParamDialog::command(&ctx, CMD, initial, |fields| { + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::command(&ctx, CMD, initial, move |fields| { let rows = screen_params(false, fields); - ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)) + let dialog = ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields)); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; diff --git a/crates/ui-egui/src/dialogs/indexed_color.rs b/crates/ui-egui/src/dialogs/indexed_color.rs index 0f1aec1462..d9850c0edd 100644 --- a/crates/ui-egui/src/dialogs/indexed_color.rs +++ b/crates/ui-egui/src/dialogs/indexed_color.rs @@ -103,7 +103,11 @@ pub fn open(app: &mut VectorcraftApp) { if let Some(old) = app.object_dialogs.indexed.take() { old.cancel_preview(app); } - let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), move |fields| match canvas { + Some(canvas) => build(fields).canvas(canvas), + None => build(fields), + }); let opening = Arc::new(()); let cancelled = Arc::clone(&opening); let ok = |app: &mut VectorcraftApp, r: &ParamResult| { diff --git a/crates/ui-egui/src/dialogs/step_repeat.rs b/crates/ui-egui/src/dialogs/step_repeat.rs index 4a14fe4d2a..ab34502299 100644 --- a/crates/ui-egui/src/dialogs/step_repeat.rs +++ b/crates/ui-egui/src/dialogs/step_repeat.rs @@ -144,8 +144,13 @@ fn try_open(app: &mut VectorcraftApp) -> Result { 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); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| { - ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)) + let dialog = ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields)); + match canvas { + Some(canvas) => dialog.canvas(canvas), + None => dialog, + } }); let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?; diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 6bb3b55915..529da2d359 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -509,7 +509,11 @@ pub(crate) fn open(app: &mut VectorcraftApp) { } } apply_links(&mut f, shared); - let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| form(fields, shared, lengths)); + let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); + let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| match canvas { + Some(canvas) => form(fields, shared, lengths).canvas(canvas), + None => form(fields, shared, lengths), + }); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; if let Some(id) = open_held_with(app, dialog, move |app, result| ok(app, &ctx, result), options) { app.object_dialogs.each = diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..9d2203d7f1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -684,6 +684,9 @@ space. RGB edits preserve the other native channels; HSB uses those same working display sRGB retain their native numeric values. `ui.colorPanel` selects the panel mode and `ui.colorPicker` opens the picker through `run_command` with the remote backend. Edit › Keyboard Shortcuts lists `ui.colorPicker` as Color Picker… with no default key; a key assigned there opens the picker for the proxy in front, as `{}` does. +While the picker is open, the canvas of the current window is not dimmed, so the live preview shows the picked color. +The wheel scrolls and zooms the view, and a middle-button drag or a drag with Space held pans it; other presses on the +canvas do not reach the tools or sample a color. `ui.colorPanel {"recentColors": false}` unchecks the panel menu's Show Recent Colors, which hides the Color panel's Recent Colors row, and `true` shows it again; applied colors still join the list while it is hidden. `ui.colorPanel {"rgbPercent": true}` shows the Color panel's RGB fields in percent, as a double-click right of an RGB From 3537d1bb602bb20bfe900d99221a9131f4787888 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:47:40 -0800 Subject: [PATCH 485/533] Blend: live rectangle steps need keys with no scale left in their transforms Live rectangle steps keep the first key's rotation and reflection. A key whose transform still held a scale could pass the comparison with a large scale on one axis hiding a difference on the other, and Align to Path then folded that scale into each step, so its corners changed shape along the spine. Only keys whose transforms are a rotation or a reflection, the same for both, now take the live rectangle route; the rest keep anchor matching. --- crates/doc/src/blend.rs | 18 +++++++----------- docs/mcp.md | 7 +++---- docs/target-app-parity.md | 2 +- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index c7ec77ac7f..2101baddeb 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1034,7 +1034,7 @@ enum Shape { /// compound paths. Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec, Vec)> }, /// Two live rectangles: each step is a live rectangle whose size, transform and corner radii - /// lie between the keys'. A shared shear or nonuniform scale makes the corners elliptical. + /// lie between the keys', so their rounded corners stay circular arcs. LiveRect(Box<(LiveRectParts, LiveRectParts)>), /// Text, symbols and images: their transforms interpolate. Placed, @@ -1076,19 +1076,15 @@ fn live_rect(s: &LiveShape) -> Option { } /// The parts of `a` and `b` when steps between them can be live rectangles: both are live -/// rectangles with the same corner kinds and the same rotation, reflection and shear, so each step -/// only moves and resizes. +/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear +/// left in their transforms, so each step only moves and resizes and its corners stay circular. fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> { let (x, y) = (live_rect(a)?, live_rect(b)?); let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs()); - let scale = p[..4].iter().chain(&q[..4]).map(|c| c.abs()).fold(0.0, f64::max); - let determinant_sign = |c: [f64; 6]| { - let scale = if scale > 0.0 { scale } else { 1.0 }; - let det = (c[0] / scale) * (c[3] / scale) - (c[1] / scale) * (c[2] / scale); - (det > 0.0, det < 0.0) - }; - (x.kinds == y.kinds && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() <= 1e-9 * scale) && determinant_sign(p) == determinant_sign(q)) - .then_some((x, y)) + // A rotation or a reflection: unit columns at right angles. + let rigid = + |c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9; + (x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y)) } /// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has. diff --git a/docs/mcp.md b/docs/mcp.md index b4eac5addb..c4465ae0c1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16809,10 +16809,9 @@ bounding-box edges divided by their mean width (left and right edges) or height from 1 to 1000. Keys with no width or no height are measured by their other side, keys with neither in points, and keys without bounds make 1 step. `starts` gives, per object, the anchor of its first subpath the blend starts from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). Steps -between two live rectangles with the same corner kinds and the same rotation, reflection and shear are live -rectangles whose width, height, position and corner radii lie between the keys'. Rounded corners stay circular -arcs only when the keys are not sheared and have no nonuniform scale in their transforms; a shared shear draws -elliptical corners on the canvas. Other path and live-shape pairs use anchor matching. A start anchor given in +between two live rectangles with the same corner kinds and the same rotation and reflection, and with no scale +or shear left in their transforms, are live rectangles whose width, height, position and corner radii lie between +the keys', so their rounded corners stay circular arcs. Other path and live-shape pairs use anchor matching. A start anchor given in `starts` for either key also sends live rectangles through anchor matching; an all-null `starts` does not. With the Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend just made; the document and the selection stay as they are. A blend diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bd63035ba5..9e4dc14697 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2132,7 +2132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. A triple-click on a face selects every face of its group with that face's fill, and on an edge every edge of its group that has its stroke paint ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)); hidden faces and edges are left out, and Shift-triple-click adds them to the selection or removes them from it. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. - Steps between live rectangles with matching corner kinds and equivalent linear transforms stay live rectangles with interpolated sizes, positions and corner radii. A start anchor given for either key selects anchor matching instead; all-null `starts` keeps live rectangles. Rounded corners stay circular only without shear or a nonuniform scale in the keys' transforms. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`. + Steps between two live rectangles with the same corner kinds, turned and reflected alike, are live rectangles whose sizes, positions and corner radii lie between the keys', so their rounded corners stay circular arcs (#10707). A start point clicked on either key, a scale or shear left in a key's transform, and every other pair of paths keep anchor-by-anchor matching. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. From 6bb499f189a7fdaa86e4d0714736a68e1c3dc9b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:50:05 -0800 Subject: [PATCH 486/533] 3D: the cap grid's test also cuts 1,200 seeded random rings both ways rings_cut_with_a_grid_give_the_triangles_cut_without_one now adds 1,200 rings drawn from a fixed seed: spiky rings, rings with whole-number corners on slanted lines, rings with a corner midway along every edge, stretched rings, rings scaled down by 1e-7 and rings far from the origin. The test now fails when the grid's margin is 0, when the row band is narrowed by the margin instead of widened, or when removed corners are not skipped. --- crates/three-d/src/mesh/tests.rs | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index a4048f82ca..960f85dbf0 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -255,6 +255,56 @@ fn star_ring(n: usize, x: f64, y: f64, r: f64, inner: f64, back: bool) -> Vec Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + let mut unit = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + (0..count) + .map(|k| { + let n = 70 + (unit() * 200.0) as usize; + let mut angles: Vec = (0..n).map(|_| unit() * std::f64::consts::TAU).collect(); + angles.sort_by(f64::total_cmp); + angles.dedup(); + let spiky = k % 3 == 1; + let whole = k % 3 != 0; + let mut points: Vec<(f64, f64)> = angles + .iter() + .enumerate() + .map(|(i, a)| { + let r = if spiky && i % 2 == 1 { 0.05 + 0.1 * unit() } else { 0.5 + 0.5 * unit() }; + let (x, y) = (r * a.cos(), r * a.sin()); + if whole { + let (x, y) = ((40.0 * x).round(), (40.0 * y).round()); + (x + y, y) + } else { + (x, y) + } + }) + .collect(); + points.dedup(); + if points.first() == points.last() { + points.pop(); + } + if k % 2 == 0 { + points = points.iter().zip(points.iter().cycle().skip(1)).flat_map(|(&p, &q)| [p, ((p.0 + q.0) / 2.0, (p.1 + q.1) / 2.0)]).collect(); + } + let (sx, sy) = [(1.0, 1.0), (1024.0, 1.0), (1.0, 1.0 / 1024.0), (32.0, 64.0), (1e-7, 1e-7)][k % 5]; + let (ox, oy) = if k % 7 == 0 { ((1e6 * (unit() - 0.5)).round(), (1e6 * (unit() - 0.5)).round()) } else { (0.0, 0.0) }; + ring_of(&points.iter().map(|&(x, y)| (ox + sx * x, oy + sy * y)).collect::>()) + }) + .collect() +} + /// The triangles `ring` is cut into, with the ring's corners sorted into a grid as [`clip`] sorts /// them, or without one, and the number of corners tested against ears. fn cut_ring(ring: &[Corner], keep_straight: bool, grid: bool) -> (Vec<[[u64; 3]; 3]>, usize) { @@ -305,6 +355,7 @@ fn rings_cut_with_a_grid_give_the_triangles_cut_without_one() { let dent = ring_of(&[(4.0, 4.0), (4.0, 6.0), (6.0, 6.0), (6.0, 5.0), (6.0, 4.0), (5.0, 4.0)]); rings.push(bridge(square.clone(), &dent, &[], &mut work).unwrap()); rings.push(square); + rings.extend(random_rings(1200)); for (k, ring) in rings.iter().enumerate() { for keep_straight in [false, true] { let (with, _) = cut_ring(ring, keep_straight, true); From 988a9b91935e0f7fd8479449dd8da33df62f1811 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:02:16 -0800 Subject: [PATCH 487/533] Blend: test that unlike corner kinds keep the path route and steps keep the fill rule Keys whose corner kinds differ blend anchor by anchor, and the last step is the second key's outline. Steps between live rectangles keep the fill rule of the key they are nearer and stay live rectangles. --- crates/doc/src/blend.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 2101baddeb..fe7ef7a6be 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2467,6 +2467,31 @@ mod tests { b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false); assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. })); } + // Keys whose corner kinds differ keep the anchor-by-anchor route. + let mut kinds = [CornerKind::Round; 4]; + kinds[2] = CornerKind::InvertedRound; + let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) }; + let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default()); + if let NodeKind::Path { live: l, .. } = &mut inverted.kind { + *l = Some(Box::new(live)); + } + let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None)); + assert!(matches!(blend.shape, Shape::Path { .. })); + // The last step is the inverted key's outline. + assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds())); + // Each step keeps the fill rule of the key it is nearer. + let mut a = rounded(0.0, 100.0, 100.0, 10.0); + if let NodeKind::Path { rule, .. } = &mut a.kind { + *rule = FillRule::EvenOdd; + } + let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None)); + assert!(matches!(&blend.shape, Shape::LiveRect(_))); + let rule = |n: &Node| match &n.kind { + NodeKind::Path { rule, .. } => *rule, + _ => panic!("a path step: {n:?}"), + }; + assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd); + assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero); } /// A step between two distorted images has its corners between the keys' corners. From 9803e7438daf69d0fc0753eed3ec7bf62e288120 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:03:18 -0800 Subject: [PATCH 488/533] View: Curvature Comb overlay on selected paths View > Show Curvature Comb (view.curvatureComb) draws the curvature comb of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line joins the tips in the path's layer color. A bend with a radius of 100 screen points gives 20-point teeth at any zoom. - vectorcraft-geom: curvature_comb samples the signed curvature of a subpath. Straight segments give teeth of no length, points with no direction give none, and the line through the tips breaks at those points and at cusps between teeth. - The comb draws at most 20,000 teeth, shared among the selected paths by their number of segments, so a large selection gets fewer teeth everywhere instead of losing whole stretches. - The toggle is a view setting: it is not saved in the document, makes no undo step and rejects parameters. Docs: docs/mcp.md, ROADMAP progress log. Fixes #10659 --- ROADMAP.md | 2 + crates/engine/src/cmd/plugin.rs | 2 + crates/geom/src/curvature.rs | 222 ++++++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/canvas/marks.rs | 63 ++++++ crates/ui-egui/src/canvas/marks/tests.rs | 40 ++++ crates/ui-egui/src/canvas/tool_adapter.rs | 3 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/menus/entries.rs | 3 +- crates/ui-egui/src/menus/labels.rs | 3 + crates/ui-egui/src/menus/model.rs | 2 +- crates/ui-egui/src/menus/run.rs | 4 +- crates/ui-egui/src/menus/tests.rs | 1 + crates/ui-egui/src/menus/tree.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/state.rs | 4 + docs/mcp.md | 9 + 17 files changed, 369 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2b9961f821..9c4e5d22c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged. + - 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied. - 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e2ffb44d0c..33b38e567b 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -980,6 +980,8 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ (&["View"], "Show Corner Widget"), (&["View"], "Show Live Paint Gaps"), (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Show Curvature Comb"), + (&["View"], "Hide Curvature Comb"), (&["View"], "Guides"), (&["View"], "Smart Guides"), (&["View"], "Perspective Grid"), diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index aea7afde1d..54f5860a31 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -219,12 +219,234 @@ pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) } +/// One tooth of a curvature comb: it starts on the curve at `at` and ends at `tip`, along the +/// curve's normal on the side away from its center of curvature, `scale` times the curvature long. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CombTooth { + pub at: Point, + pub tip: Point, + /// The first tooth of the comb, the first after a point or segment that has no tooth, or the + /// first after the curve turns back on itself (a cusp between two teeth): a line through the + /// tips starts again here. + pub start: bool, +} + +/// The most teeth a curvature comb draws in all. +pub const MAX_COMB_TEETH: usize = 20_000; + +/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t` +/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment +/// gives teeth of no length, its ends included. A point of a curved segment where it has no +/// direction (a handle drawn back onto its anchor) gives no tooth, and neither does a segment +/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When +/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when +/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath. +pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec { + let n = sp.segment_count(); + if n == 0 || !scale.is_finite() || max_teeth < 2 { + return vec![]; + } + let per = if samples.max(2).saturating_mul(n) <= max_teeth { samples.max(2) } else { 2 }; + let stride = (per * n).div_ceil(max_teeth).max(1); + let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); + let mut start = true; + for seg in (0..n).step_by(stride) { + start |= stride > 1; + let c = sp.segment(seg); + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + start = true; + continue; + } + let (d1, d2) = (c.deriv(), c.deriv().deriv()); + // The control polygon's length sets what counts as no speed. + let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let chord = c.p3 - c.p0; + let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; + let mut previous_direction: Option = None; + for i in 0..per { + if teeth.len() >= max_teeth { + return teeth; + } + let t = i as f64 / (per - 1) as f64; + if line { + // A line stored with its handles on its anchors has no speed at its ends, but a + // direction and no curvature all along. + let at = c.eval(t); + if !at.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip: at, start }); + start = false; + continue; + } + let (v, a) = (d1.eval(t).to_vec2(), d2.eval(t).to_vec2()); + let speed = v.hypot(); + if speed <= CUSP_SHARE * size || !speed.is_finite() { + start = true; + continue; + } + let k = v.cross(a) / (speed * speed * speed); + let direction = v / speed; + start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0); + previous_direction = Some(direction); + let normal = Vec2::new(-direction.y, direction.x); + let at = c.eval(t); + let tip = at - normal * (k * scale); + if !at.is_finite() || !tip.is_finite() { + start = true; + continue; + } + teeth.push(CombTooth { at, tip, start }); + start = false; + } + } + teeth +} + #[cfg(test)] mod tests { use super::*; use crate::{Anchor, shapes}; use kurbo::Rect; + fn tooth_len(t: &CombTooth) -> f64 { + t.at.distance(t.tip) + } + + /// A circle's comb points away from the center, each tooth `scale` times the cubic's own + /// curvature at its point ([`curvature_circle_with`] without arcs), all within 3% of + /// `scale / r` (the usual cubic of a quarter turn strays that little from its circle). + #[test] + fn the_comb_of_a_circle_has_teeth_of_one_length() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + let teeth = curvature_comb(sp, 9, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 9 * sp.segment_count()); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "one unbroken comb"); + let center = Point::new(150.0, 150.0); + for (i, t) in teeth.iter().enumerate() { + let (seg, at) = (i / 9, (i % 9) as f64 / 8.0); + let r = curvature_circle_with(sp.segment(seg), at, false, false).unwrap().radius; + assert!((tooth_len(t) * r - 1000.0).abs() < 1e-6, "{t:?} {r}"); + assert!((tooth_len(t) - 10.0).abs() < 0.3, "{t:?}"); + assert!(t.tip.distance(center) > t.at.distance(center), "outward: {t:?}"); + } + } + + /// A straight line has teeth of no length, its two ends included. + #[test] + fn the_comb_of_a_line_is_flat() { + let sp = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 40.0), Point::new(200.0, 0.0)], false); + let teeth = curvature_comb(&sp, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 10); + assert!(teeth.iter().all(|t| tooth_len(t) < 1e-9), "{teeth:?}"); + assert_eq!(teeth[4].at, Point::new(100.0, 40.0), "the corner has a tooth on each side"); + } + + /// Two quarter circles of radius 100 and 50 that meet in one direction: the teeth double in + /// length at the anchor they share. + #[test] + fn the_comb_jumps_where_the_curvature_does() { + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan(); + let a0 = Anchor { h_out: Point::new(100.0 * k, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { + h_in: Point::new(100.0, 100.0 - 100.0 * k), + h_out: Point::new(100.0, 100.0 + 50.0 * k), + ..Anchor::corner(Point::new(100.0, 100.0)) + }; + let a2 = Anchor { h_in: Point::new(50.0 + 50.0 * k, 150.0), ..Anchor::corner(Point::new(50.0, 150.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + let (before, after) = (tooth_len(&teeth[2]), tooth_len(&teeth[3])); + assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); + assert!((before - 10.0).abs() < 0.3, "{before}"); + assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + } + + /// A segment with no length and a handle drawn back onto its anchor do not panic and give no + /// tooth where the curve has no direction; a scale that is not finite gives no comb. + #[test] + fn the_comb_skips_points_with_no_direction() { + let p = Point::new(10.0, 10.0); + assert!(curvature_comb(&SubPath::polyline(&[p, p], false), 4, 1000.0, MAX_COMB_TEETH).is_empty()); + let curve = SubPath::new( + vec![Anchor { h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(0.0, 0.0)) }, Anchor::corner(Point::new(100.0, 100.0))], + false, + ); + let teeth = curvature_comb(&curve, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the end whose handle sits on its anchor has no tooth: {teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, false]); + let back = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor { h_in: Point::new(50.0, 0.0), ..Anchor::corner(Point::new(100.0, 100.0)) }], + false, + ); + let teeth = curvature_comb(&back, 5, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the start, whose handle sits on its anchor, has no tooth: {teeth:?}"); + assert!(teeth[0].start, "the comb starts after the point with no tooth"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(curvature_comb(&curve, 5, f64::NAN, MAX_COMB_TEETH).is_empty()); + } + + /// A cusp between samples starts a new line through the comb's tips after the cusp. + #[test] + fn the_comb_breaks_at_a_cusp_between_samples() { + let bp = kurbo::BezPath::from_svg("M0 0 C100 100 0 100 100 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + let teeth = curvature_comb(sp, 6, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6, "the cusp falls between teeth"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + } + + /// A tooth whose tip overflows is skipped, and the next finite tooth starts a new envelope. + #[test] + fn the_comb_breaks_after_a_nonfinite_tip() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(-1.0, 1.0), Point::new(-1.0, 1.0), Point::new(-1.0 / 3.0, -1.0 / 3.0)), + Anchor::with_handles(Point::new(1.0, 1.0), Point::new(1.0 / 3.0, -1.0 / 3.0), Point::new(1.0, 1.0)), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, f64::MAX, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the middle tooth overflows"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, true, false]); + assert!(teeth[1].at.x < 0.0 && teeth[2].at.x > 0.0, "the gap is inside the segment"); + } + + /// A speed whose cube underflows gives no tooth, and the first finite tooth starts the comb. + #[test] + fn the_comb_skips_a_tip_when_speed_cubed_underflows() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::ORIGIN, Point::ORIGIN, Point::new(1e-109, 0.0)), + Anchor::with_handles(Point::ORIGIN, Point::new(1e-101, 1e-101), Point::ORIGIN), + ], + false, + ); + let teeth = curvature_comb(&sp, 5, 1.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 4, "the first tooth has a nonfinite tip"); + assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}"); + assert!(teeth[0].start && teeth[0].at.x > 0.0, "the comb starts after the skipped tooth"); + } + + /// A subpath with more segments than the budget allows keeps to it, with teeth spread to its + /// far end rather than stopping part way. + #[test] + fn the_comb_is_capped_and_spread() { + let points: Vec = (0..30_001).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let sp = SubPath::polyline(&points, false); + let teeth = curvature_comb(&sp, 16, 1.0, 1000); + assert!(teeth.len() <= 1000 && teeth.len() >= 900, "{}", teeth.len()); + assert!(teeth.last().is_some_and(|t| t.at.x > 29_000.0), "{:?}", teeth.last()); + assert_eq!(teeth.iter().filter(|t| t.start).count() * 2, teeth.len(), "each sampled segment starts a new line through the tips"); + let few = curvature_comb(&sp, 16, 1.0, 100_000); + assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index acbbb5d151..efc31ac652 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,6 +261,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} 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", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index abe7c5a6db..4e8c3776f0 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -835,3 +835,66 @@ pub(in crate::canvas) fn live_paint_gap_overlays(app: &mut VectorcraftApp) -> Ve }; gaps.to_vec() } + +/// Teeth View → Show Curvature Comb draws on each segment. +const COMB_SAMPLES: usize = 16; +/// The comb's length at zoom 1, in screen points squared: a curve that bends with a radius of +/// 100 screen points has teeth 20 screen points long at any zoom. VectorCraft's own value. +const COMB_SCALE: f64 = 2000.0; + +/// View → Show Curvature Comb: on each selected path, and each path of a selected compound path, a +/// tooth along the normal at evenly spaced points of every segment, as long as the curvature there, +/// and a line through the teeth's tips, in the path's layer color. At most +/// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their +/// number of segments, so a large selection gets fewer teeth everywhere. +pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, curvature_comb}; + let Some(st) = app.session.active() else { return vec![] }; + if !(zoom.is_finite() && zoom > 0.0) { + return vec![]; + } + let scale = COMB_SCALE / (zoom * zoom); + let mut paths = vec![]; + for &id in &st.selection.objects { + let Some(n) = st.doc.node(id).filter(|n| !n.is_guide()) else { continue }; + let color = st.doc.layer_color(id); + match &n.kind { + NodeKind::Compound { children, .. } => paths.extend(children.iter().filter_map(|c| c.path_data()).map(|pd| (pd, color))), + _ => paths.extend(n.path_data().map(|pd| (pd, color))), + } + } + let all: Vec<_> = + paths.iter().flat_map(|(pd, color)| pd.subpaths.iter().map(move |sp| (sp, *color))).filter(|(sp, _)| sp.segment_count() > 0).collect(); + // With more subpaths than the teeth allow 2 each, every k-th subpath gets a comb. + let stride = (all.len() * 2).div_ceil(MAX_COMB_TEETH).max(1); + let chosen: Vec<_> = all.into_iter().step_by(stride).collect(); + // Each chosen subpath has 2 teeth set aside; the rest are shared by number of segments. + let total: usize = chosen.iter().map(|(sp, _)| sp.segment_count()).sum(); + let spare = MAX_COMB_TEETH.saturating_sub(2 * chosen.len()); + let mut o = vec![]; + for (sp, color) in chosen { + let extra = (spare as u128) * (sp.segment_count() as u128) / (total.max(1) as u128); + let share = 2usize.saturating_add(usize::try_from(extra).unwrap_or(usize::MAX)); + let teeth = curvature_comb(sp, COMB_SAMPLES, scale, share); + let mut envelope = BezPath::new(); + for t in &teeth { + o.push(Overlay::Line { a: t.at, b: t.tip, color, dashed: false }); + if t.start { + envelope.move_to(t.tip); + } else { + envelope.line_to(t.tip); + } + } + // A closed subpath combed all the way round ends where it starts: the line closes there. + let unbroken = teeth.iter().filter(|t| t.start).count() == 1; + if let (true, true, Some(first), Some(last)) = (sp.closed, unbroken, teeth.first(), teeth.last()) + && first.at.distance(last.at) < 1e-9 + { + envelope.line_to(first.tip); + } + if teeth.len() > 1 { + o.push(Overlay::Path { path: envelope, color, width: 1.0, dashed: false }); + } + } + o +} diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 29336a8ad8..621a7b67e2 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -359,6 +359,46 @@ fn live_paint_gaps_follow_the_selected_groups() { assert!(live_paint_gap_overlays(&mut app).is_empty()); } +/// View → Show Curvature Comb: a selected circle of radius 100 gets teeth 20 screen points long at +/// zoom 1 and 10 at zoom 2, where it shows twice as large (within 3%: the circle is made of cubics), +/// and a line through their tips; a compound path gets a comb on each of its paths; nothing +/// selected draws nothing. +#[test] +fn the_curvature_comb_follows_the_selection_and_the_zoom() { + let mut app = app(); + let id = app.session.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let teeth = |o: &[Overlay], zoom: f64| -> Vec { + o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some(a.distance(*b) * zoom) } else { None }).collect() + }; + let at_one = teeth(&curvature_comb_overlays(&app, 1.0), 1.0); + for zoom in [1.0, 2.0] { + let o = curvature_comb_overlays(&app, zoom); + let got = teeth(&o, zoom); + assert_eq!(got.len(), 64, "16 teeth on each of the circle's four segments"); + let want = 2000.0 / (100.0 * zoom); + assert!(got.iter().all(|t| (t - want).abs() < 0.03 * want), "{zoom}: {got:?}"); + assert!(got.iter().zip(&at_one).all(|(t, one)| (t * zoom - one).abs() < 1e-9), "zoom divides each tooth's screen length"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1, "one line through the tips"); + let Some(Overlay::Path { path, .. }) = o.iter().find(|o| matches!(o, Overlay::Path { .. })) else { panic!("no line through the tips") }; + let ends: Vec<_> = path.elements().iter().filter_map(|e| e.end_point()).collect(); + assert_eq!(ends.first(), ends.last(), "the closed circle's line through the tips closes"); + } + let other = app.session.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.set", &json!({"ids": [id, other]})).unwrap(); + app.session.execute("object.compoundPath.make", &json!({})).unwrap(); + let o = curvature_comb_overlays(&app, 1.0); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 2, "the compound path's two paths"); + assert_eq!(teeth(&o, 1.0).len(), 128); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + assert!(curvature_comb_overlays(&app, 1.0).is_empty()); + assert!(app.run("view.curvatureComb", json!({"on": true})).is_err(), "it takes no parameters"); + assert!(!app.ui.view.curvature_comb, "a refused call leaves it off"); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(true)); + assert!(app.ui.view.curvature_comb); + assert!(app.run("view.curvatureComb", json!({})).unwrap() == json!(false)); +} + /// Draw Inside's arms: an open rectangle round the object, each arm a third of its side or 16 /// points at most, kept with the object deselected and gone with the mode. #[test] diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..9ae5044d0d 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -771,6 +771,9 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in if app.ui.view.live_paint_gaps { extra.extend(super::marks::live_paint_gap_overlays(app)); } + if app.ui.view.curvature_comb { + extra.extend(super::marks::curvature_comb_overlays(app, space.view.zoom)); + } } super::overlays::show(app, ui, &space, &list, &extra); } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e77c4bae56..cdbc54b58d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1035,6 +1035,7 @@ fn toggled_labels() -> Vec { "type.hiddenCharacters", "view.gradientAnnotator", "view.livePaintGaps", + "view.curvatureComb", "view.artboards", "view.template", "view.rulers", diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 66353c55be..71feba3195 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -76,7 +76,7 @@ const MENU_ONLY_COMMANDS: [&str; 5] = ["imageTrace.make", "imageTrace.makeAndExp /// action ([`plays_in_app`]): Outline, Pixel Preview, Trim View, Presentation Mode and Screen Mode, /// the zoom, fit and rotate view items, and the items that show or hide or turn snapping on or off. /// The saved-view slots are not among them. -const UI_STEP_COMMANDS: [&str; 30] = [ +const UI_STEP_COMMANDS: [&str; 31] = [ "view.outline", "view.pixelPreview", "view.trimView", @@ -100,6 +100,7 @@ const UI_STEP_COMMANDS: [&str; 30] = [ "view.gradientAnnotator", "view.cornerWidget", "view.livePaintGaps", + "view.curvatureComb", "view.guides", "view.smartGuides", "view.grid", diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 549d31b876..52ec3b33aa 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -29,6 +29,7 @@ fn view_toggle_label(app: &VectorcraftApp, id: &str) -> Option { "type.hiddenCharacters" => if v.hidden_chars { "Hide Hidden Characters" } else { "Show Hidden Characters" }.into(), "view.gradientAnnotator" => if v.gradient_annotator { "Hide Gradient Annotator" } else { "Show Gradient Annotator" }.into(), "view.livePaintGaps" => if v.live_paint_gaps { "Hide Live Paint Gaps" } else { "Show Live Paint Gaps" }.into(), + "view.curvatureComb" => if v.curvature_comb { "Hide Curvature Comb" } else { "Show Curvature Comb" }.into(), _ => return None, }; Some(text) @@ -356,6 +357,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Show Gradient Annotator", "Hide Live Paint Gaps", "Show Live Paint Gaps", + "Hide Curvature Comb", + "Show Curvature Comb", "Hide Artboards", "Show Artboards", "Hide Rulers", diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 73a4296dd9..bd406aabcc 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -133,7 +133,7 @@ fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let (prefs, v) = (&s.prefs, &app.ui.view); (prefs.font_preview, prefs.font_samples_on_white, prefs.font_names_in_english, crate::workspaces::current_name(&app.ui)).hash(&mut h); (v.edges, v.templates, v.corner_widgets, v.shape_widgets, v.text_threads, v.hidden_chars, v.gradient_annotator).hash(&mut h); - (v.live_paint_gaps, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); + (v.live_paint_gaps, v.curvature_comb, v.artboards, v.rulers, v.video_rulers, v.bounding_box, v.guides, v.grid).hash(&mut h); (app.outline_view(), s.guides_locked(), s.slices_hidden()).hash(&mut h); // The Align To choice: Object › Align's checks and the Distribute buttons with the Artboard tool. app.ui.align_to.hash(&mut h); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 50e2a7606e..35b09d45b6 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -408,7 +408,7 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { +fn run_ui_part4(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { let flag = |b: &mut bool| { *b = !*b; Ok(json!(*b)) @@ -419,6 +419,8 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option crate::panels::align::run_align_to(app, v), "view.gradientAnnotator" => flag(&mut app.ui.view.gradient_annotator), "view.livePaintGaps" => flag(&mut app.ui.view.live_paint_gaps), + "view.curvatureComb" if !(p.is_null() || p.as_object().is_some_and(|m| m.is_empty())) => Err("view.curvatureComb takes no parameters".into()), + "view.curvatureComb" => flag(&mut app.ui.view.curvature_comb), "effect.last" => match app.last_effect.clone() { Some((e, params)) => crate::dialogs::effect::open_last(app, &e, params), None => Err("no effect applied yet".into()), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 88c2e04540..3f53a3194d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -626,6 +626,7 @@ fn last_effect_dialog_and_view_toggles() { ("view.textThreads", "Hide Text Threads", "Show Text Threads"), ("view.gradientAnnotator", "Hide Gradient Annotator", "Show Gradient Annotator"), ("view.livePaintGaps", "Show Live Paint Gaps", "Hide Live Paint Gaps"), + ("view.curvatureComb", "Show Curvature Comb", "Hide Curvature Comb"), ("type.hiddenCharacters", "Show Hidden Characters", "Hide Hidden Characters"), ("view.template", "Hide Template", "Show Template"), ] { diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 7cd830ef05..e044ac2580 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -678,6 +678,7 @@ fn built_in_tree(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec c("Hide Gradient Annotator", "view.gradientAnnotator"), c("Hide Corner Widget", "view.cornerWidget"), c("Show Live Paint Gaps", "view.livePaintGaps"), + c("Show Curvature Comb", "view.curvatureComb"), Sep, sub( "Guides", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e131421a2a..54db93ca34 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -262,6 +262,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} 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", ), + ( + "view.curvatureComb", + "Show Curvature Comb", + "", + "{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on", + ), ( "type.hiddenCharacters", "Show Hidden Characters", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 990d245bc3..3b86fee727 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -410,6 +410,9 @@ pub struct ViewFlags { /// Preview Color. #[serde(default)] pub live_paint_gaps: bool, + /// View → Show/Hide Curvature Comb: draw the curvature comb of the selected paths. + #[serde(default)] + pub curvature_comb: bool, /// Type → Show Hidden Characters. pub hidden_chars: bool, /// Edit › Spelling › Auto Spell Check: a red underline under the words of the type its @@ -443,6 +446,7 @@ impl Default for ViewFlags { text_threads: true, gradient_annotator: true, live_paint_gaps: false, + curvature_comb: false, hidden_chars: false, auto_spell_check: false, templates: true, diff --git a/docs/mcp.md b/docs/mcp.md index 30ac0bfb82..5bb5f438c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9386,6 +9386,15 @@ of more than half a degree and the anchor is not marked smooth with both handles marked smooth), when the circle would reach past the canvas (4,000,000 pt from the origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, subpath or segment does not exist. +`view.curvatureComb` (View › Show Curvature Comb, or Hide Curvature Comb while it is on) turns on the curvature comb +of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly +spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line +joins the teeth's tips, in the path's layer color. A straight segment has teeth of no length, and a point of a curve +where it has no direction (a handle on its anchor) has no tooth. The length is VectorCraft's own value: a bend with a +radius of 100 screen points draws 20-point teeth at any zoom. The comb draws about 20,000 teeth at most, shared among +the selected paths by their number of segments: a larger selection gets 2 teeth per segment, then teeth on every k-th +segment. The setting belongs to the view: it is not saved in the document and makes no undo step. + The Curvature Circle tool, after the Circle tool in the Ellipse tool's toolbar group, draws with this command. The pointer snaps to the nearest path that is not a guide within the tool's Snap Tolerance (`snapTolerance` below, 5 screen points by default), or within Smart Guides › Snapping Tolerance when that is larger; with Snap with Smart From e32a12ebeb826b28ed79f0926611e6fceeb6fa4f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:10:28 -0800 Subject: [PATCH 489/533] xtask: ui-commands --check passes in a checkout with core.autocrlf cargo xtask ui-commands --check compares crates/mcp/src/ui_catalog.rs byte for byte with the rustfmt output the generator produces, which has LF line endings. With core.autocrlf=true, the Git for Windows default, git checked the file out with CRLF line endings, so the check and cargo xtask ci failed on an unchanged tree. The root .gitattributes now marks the file -text, as it does the DXF writer goldens, so git checks it out with the LF bytes stored in the index. --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index e3ff66fc1c..dc4403a4db 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,4 @@ # The DXF writer goldens are compared byte for byte with the writer's output (LF line endings). crates/cad/tests/data/*.dxf -text +# `cargo xtask ui-commands --check` compares this file byte for byte with rustfmt's output (LF line endings). +crates/mcp/src/ui_catalog.rs -text From 45a5c495961d63c8cc56bdb62d9eadf41406496f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:24:25 -0800 Subject: [PATCH 490/533] Tabs: Select All on a threaded story drops an unentered field value The fields' edit target read only the Type tool's frame and range. Select All on a frame whose text was already fully selected keeps that range but makes Enter set the stops of every frame of the story, so an unentered X, Leader or Align On value survived and reached the other frames. The target now also includes whether Select All took the story. --- crates/ui-egui/src/panels/tabs.rs | 6 +++-- crates/ui-egui/src/panels/tabs/tests.rs | 31 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 56c1362911..423223d4a8 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -345,7 +345,8 @@ fn shown_paragraph(app: &VectorcraftApp, t: &TextObject) -> usize { } /// The edit target of the panel's fields for text `n`: the active document and its reverts, the -/// selected objects, the Type tool's range, and the text and paragraph whose stops the panel shows. +/// selected objects, the Type tool's range and whether Select All took the threaded story, and the +/// text and paragraph whose stops the panel shows. /// A value typed in a field is dropped when this changes before it is entered, so it does not set /// the stops of other text, even text whose stop holds the same values. fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { @@ -354,7 +355,8 @@ fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt { _ => 0, }; let document = app.session.active().map(|st| (st.uid, st.reverts, &st.selection.objects)); - egui::IdSalt::new((document, super::character::text_editing(app), n.id, para)) + let typed = (super::character::text_editing(app), super::character::text_story(app)); + egui::IdSalt::new((document, typed, n.id, para)) } /// [`above_text`], then note the active document and text `n`. A floating panel is diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index f10afe5c98..39cb56fd33 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1303,3 +1303,34 @@ fn an_x_value_typed_before_file_revert_does_not_reach_the_restored_text() { panel.key(egui::Key::Enter, egui::Modifiers::NONE); assert_eq!(stops_of(&panel.app(), id), before, "X typed before File › Revert, entered after selecting the restored text"); } + +/// A Leader value typed with the Type tool's selection over all of a threaded frame's text and not +/// yet entered is dropped when Select All takes the whole story, though the frame's range stays +/// the same: Enter would set the stops of every frame of the story. +#[test] +fn a_field_value_typed_before_select_all_takes_the_story_does_not_reach_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let story = (1..=8).map(|i| format!("{i}\t1.5")).collect::>().join("\n"); + let a = app.run("text.create", json!({"x": 10, "y": 20, "text": story, "area": {"width": 300, "height": 50}})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [10, 300, 300, 200]})).unwrap()["id"].as_u64().unwrap(); + assert!(!text_of(&app, a).plain_text().is_empty() && !text_of(&app, b).plain_text().is_empty(), "the story runs through both frames"); + let before = (paragraph_stops(&app, a), paragraph_stops(&app, b)); + let len = text_of(&app, a).plain_text().len(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": len})); + let range = super::super::character::text_editing(&app); + let mut panel = crate::tests::panel_harness::Panel::new(app, show); + draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-"); + panel.app().run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_editing(&panel.app()), range, "Select All leaves the frame's range as it was"); + assert!(super::super::character::text_story(&panel.app()).is_some(), "Select All takes the story"); + panel.frame(); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + let after_a = paragraph_stops(&panel.app(), a); + let after_b = paragraph_stops(&panel.app(), b); + assert_eq!((after_a, after_b), before, "Leader typed for frame {a}'s text, entered after Select All took the story"); +} From 9711371ab97d7400ed886ca5361aad757e587992 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:36:01 -0800 Subject: [PATCH 491/533] Color picker: say the picker adds no dimming of its own Another open dialog, such as New Swatch, keeps its own scrim over the canvas while the picker is open. The doc line in docs/mcp.md and the comment in dialogs/color_picker.rs now say so. --- crates/ui-egui/src/dialogs/color_picker.rs | 3 ++- docs/mcp.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 042e6c74c0..479cbd1a34 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -212,7 +212,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); } - // The canvas stays undimmed under the picker, so its live preview shows the true color. Presses on it stay blocked: + // The picker adds no dimming of its own over the canvas, so its live preview shows the true color; another open + // dialog's scrim can still dim the canvas. Presses on it stay blocked: // the app does not take the picker's canvas eyedropper request. if let Some(canvas) = crate::doc_windows::current(app).map(crate::canvas::canvas_id) { dialog = dialog.canvas(canvas).canvas_samples(false); diff --git a/docs/mcp.md b/docs/mcp.md index 9d2203d7f1..40b15fe52e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -684,7 +684,7 @@ space. RGB edits preserve the other native channels; HSB uses those same working display sRGB retain their native numeric values. `ui.colorPanel` selects the panel mode and `ui.colorPicker` opens the picker through `run_command` with the remote backend. Edit › Keyboard Shortcuts lists `ui.colorPicker` as Color Picker… with no default key; a key assigned there opens the picker for the proxy in front, as `{}` does. -While the picker is open, the canvas of the current window is not dimmed, so the live preview shows the picked color. +While the picker is open, it adds no dimming of its own over the canvas of the current window, so the live preview shows the picked color. Another open dialog, such as New Swatch, can still dim the canvas with its own scrim. The wheel scrolls and zooms the view, and a middle-button drag or a drag with Space held pans it; other presses on the canvas do not reach the tools or sample a color. `ui.colorPanel {"recentColors": false}` unchecks the panel menu's Show Recent Colors, which hides the Color panel's From 80e8c74d5535e2229bbeb7ffdbd28f6f73155989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:57:29 -0800 Subject: [PATCH 492/533] View: Curvature Comb breaks at a cusp on an anchor The direction of the last curved tooth now carries from one segment to the next, so a cusp where two curved segments meet starts a new line through the tips. It is cleared wherever a tooth is left out, on a line and between strided segments. A closed comb now closes at its first anchor when the curve goes on there without turning back (comb_closes), instead of only when the comb has no break at all, so a cusp elsewhere does not open the join. --- crates/geom/src/curvature.rs | 66 +++++++++++++++++++++++++++++- crates/ui-egui/src/canvas/marks.rs | 7 ++-- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 54f5860a31..52054363e4 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -250,11 +250,18 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let stride = (per * n).div_ceil(max_teeth).max(1); let mut teeth = Vec::with_capacity((per * n / stride).min(max_teeth)); let mut start = true; + // The direction of the last curved tooth, carried across segments so that a cusp at an + // anchor also starts a new line through the tips. + let mut previous_direction: Option = None; for seg in (0..n).step_by(stride) { - start |= stride > 1; + if stride > 1 { + start = true; + previous_direction = None; + } let c = sp.segment(seg); if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { start = true; + previous_direction = None; continue; } let (d1, d2) = (c.deriv(), c.deriv().deriv()); @@ -262,7 +269,6 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let size = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); let chord = c.p3 - c.p0; let line = sp.segment_is_line(seg) && chord.hypot() > 0.0; - let mut previous_direction: Option = None; for i in 0..per { if teeth.len() >= max_teeth { return teeth; @@ -272,6 +278,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize // A line stored with its handles on its anchors has no speed at its ends, but a // direction and no curvature all along. let at = c.eval(t); + previous_direction = None; if !at.is_finite() { start = true; continue; @@ -284,6 +291,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let speed = v.hypot(); if speed <= CUSP_SHARE * size || !speed.is_finite() { start = true; + previous_direction = None; continue; } let k = v.cross(a) / (speed * speed * speed); @@ -295,6 +303,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize let tip = at - normal * (k * scale); if !at.is_finite() || !tip.is_finite() { start = true; + previous_direction = None; continue; } teeth.push(CombTooth { at, tip, start }); @@ -304,6 +313,23 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize teeth } +/// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where +/// it starts: `sp` is closed, its first and last teeth sit on the same point, and the curve does +/// not turn back on itself at its first anchor. +pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { + let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { + return false; + }; + if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { + return false; + } + let n = sp.segment_count(); + match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { + (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, + _ => false, + } +} + #[cfg(test)] mod tests { use super::*; @@ -363,6 +389,42 @@ mod tests { assert!((after / before - 2.0).abs() < 1e-9, "{before} {after}"); assert!((before - 10.0).abs() < 0.3, "{before}"); assert!(teeth[2].at.distance(teeth[3].at) < 1e-9, "both teeth start on the shared anchor"); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 1, "a smooth anchor keeps one unbroken comb"); + } + + /// Two segments that meet at a cusp on their shared anchor: the first segment ends heading + /// down and the second starts heading up, so the line through the tips starts again there. + #[test] + fn the_comb_breaks_at_a_cusp_on_an_anchor() { + let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + let sp = SubPath::new(vec![a0, a1, a2], false); + let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.len(), 6); + assert_eq!(teeth.iter().map(|t| t.start).collect::>(), [true, false, false, true, false, false]); + assert!(!comb_closes(&sp, &teeth), "an open subpath does not close"); + } + + /// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a + /// cusp elsewhere, and stays open when the first anchor is the cusp. + #[test] + fn the_comb_closes_unless_its_first_anchor_is_a_cusp() { + let closed = |h_in: Point| { + let a0 = Anchor { h_in, h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }; + let a1 = Anchor { h_in: Point::new(100.0, -50.0), h_out: Point::new(100.0, -25.0), ..Anchor::corner(Point::new(100.0, 0.0)) }; + let a2 = Anchor { h_in: Point::new(200.0, -25.0), h_out: Point::new(200.0, 50.0), ..Anchor::corner(Point::new(200.0, 0.0)) }; + SubPath::new(vec![a0, a1, a2], true) + }; + let smooth = closed(Point::new(0.0, 50.0)); + let teeth = curvature_comb(&smooth, 3, 1000.0, MAX_COMB_TEETH); + assert_eq!(teeth.iter().filter(|t| t.start).count(), 2, "the cusp at the second anchor breaks the comb"); + assert!(comb_closes(&smooth, &teeth)); + let cusp = closed(Point::new(0.0, -50.0)); + assert!(!comb_closes(&cusp, &curvature_comb(&cusp, 3, 1000.0, MAX_COMB_TEETH))); + let circle = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + let sp = &circle.subpaths[0]; + assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH))); } /// A segment with no length and a handle drawn back onto its anchor do not panic and give no diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index 4e8c3776f0..9993669339 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -848,7 +848,7 @@ const COMB_SCALE: f64 = 2000.0; /// [`vectorcraft_geom::curvature::MAX_COMB_TEETH`] teeth in all, shared among the subpaths by their /// number of segments, so a large selection gets fewer teeth everywhere. pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64) -> Vec { - use vectorcraft_geom::curvature::{MAX_COMB_TEETH, curvature_comb}; + use vectorcraft_geom::curvature::{MAX_COMB_TEETH, comb_closes, curvature_comb}; let Some(st) = app.session.active() else { return vec![] }; if !(zoom.is_finite() && zoom > 0.0) { return vec![]; @@ -886,9 +886,8 @@ pub(in crate::canvas) fn curvature_comb_overlays(app: &VectorcraftApp, zoom: f64 } } // A closed subpath combed all the way round ends where it starts: the line closes there. - let unbroken = teeth.iter().filter(|t| t.start).count() == 1; - if let (true, true, Some(first), Some(last)) = (sp.closed, unbroken, teeth.first(), teeth.last()) - && first.at.distance(last.at) < 1e-9 + if let Some(first) = teeth.first() + && comb_closes(sp, &teeth) { envelope.line_to(first.tip); } From a857b49af4bb5157fcc03c7722721390b52f28a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 08:46:32 -0800 Subject: [PATCH 493/533] Main: removeAll on a clipping path passes on a stale-point error #10682 made paths::see_all_points return a Result; d22384d6 had added a call in the mask-release path of removeAll that ignored it, so clippy -D warnings fails on main. The call now passes the error on with ?, as the other three callers do. --- crates/engine/src/script/dom.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index edd447afa3..1dda97ad95 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2863,7 +2863,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } // A compound path whose last path this is stays, empty, as it does after `move`. let params = json!({"ids": [item.id.0], "keepEmpty": true}); - paths::see_all_points(h); + paths::see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, ¶ms))); h.dom.editing.set(kept); From c618b9b22cfd4b02cdd4a00ca079c7aee1ef729b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:02:42 -0800 Subject: [PATCH 494/533] View: Curvature Comb does not close across segments a capped comb skips When a long subpath has more segments than the tooth budget, only every k-th segment gets teeth. comb_closes compared only the first and last tooth positions, so a last sampled segment that ended on the first anchor joined its tip to the first tooth across the skipped closing segment. Each tooth now records its segment, and the comb closes only when the segments between the last tooth and the first across the seam have no length. --- crates/geom/src/curvature.rs | 47 ++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 52054363e4..c36279ee76 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -229,6 +229,8 @@ pub struct CombTooth { /// first after the curve turns back on itself (a cusp between two teeth): a line through the /// tips starts again here. pub start: bool, + /// The index of the segment the tooth sits on. + pub segment: usize, } /// The most teeth a curvature comb draws in all. @@ -283,7 +285,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize start = true; continue; } - teeth.push(CombTooth { at, tip: at, start }); + teeth.push(CombTooth { at, tip: at, start, segment: seg }); start = false; continue; } @@ -306,7 +308,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize previous_direction = None; continue; } - teeth.push(CombTooth { at, tip, start }); + teeth.push(CombTooth { at, tip, start, segment: seg }); start = false; } } @@ -314,16 +316,23 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize } /// Does the line through the tips of `teeth`, the comb of `sp` ([`curvature_comb`]), close where -/// it starts: `sp` is closed, its first and last teeth sit on the same point, and the curve does -/// not turn back on itself at its first anchor. +/// it starts: `sp` is closed, only segments with no length lie between its last tooth and its +/// first across the seam, the two sit on the same point, and the curve does not turn back on itself at its +/// first anchor. A comb that skips segments to keep to its budget does not close across the ones +/// it skipped at the end. pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool { let (Some(first), Some(last)) = (teeth.first(), teeth.last()) else { return false; }; + let n = sp.segment_count(); if !sp.closed || teeth.len() < 2 || first.at.distance(last.at) >= 1e-9 { return false; } - let n = sp.segment_count(); + // Only segments with no length may lie between the last tooth and the first across the seam. + let no_length = |i: usize| start_direction(sp.segment(i)) == Vec2::ZERO; + if !(last.segment + 1..n).chain(0..first.segment).all(no_length) { + return false; + } match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) { (Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0, _ => false, @@ -509,6 +518,34 @@ mod tests { assert_eq!(few.len(), 60_000, "too many for 16 on each, so 2 on each"); } + /// A capped comb that skips the last segment does not close, even when the last segment it + /// samples ends on the first anchor: the line through the tips would cross the skipped loop. + #[test] + fn a_capped_comb_does_not_close_across_a_skipped_segment() { + let sp = SubPath::new( + vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(-50.0, -50.0), Point::new(50.0, 50.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(80.0, 40.0), Point::new(120.0, 20.0)), + Anchor::with_handles(Point::new(100.0, 100.0), Point::new(140.0, 80.0), Point::new(60.0, 140.0)), + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(30.0, 120.0), Point::new(-60.0, 60.0)), + ], + true, + ); + let teeth = curvature_comb(&sp, 16, 1000.0, 4); + let (first, last) = (&teeth[0], &teeth[teeth.len() - 1]); + assert!(last.segment < 3, "the closing segment is skipped: {teeth:?}"); + assert!(first.at.distance(last.at) < 1e-9, "the last sampled tooth sits on the first anchor"); + assert!(!comb_closes(&sp, &teeth), "the comb does not close across the skipped last segment"); + assert!(comb_closes(&sp, &curvature_comb(&sp, 16, 1000.0, MAX_COMB_TEETH)), "the full comb closes"); + let mut anchors: Vec = sp.anchors.iter().copied().collect(); + anchors[0].h_in = anchors[0].p; + anchors.insert(0, Anchor { h_in: Point::new(-50.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) }); + let seam = SubPath::new(anchors, true); + let full = curvature_comb(&seam, 16, 1000.0, MAX_COMB_TEETH); + assert_eq!(full.first().map(|t| t.segment), Some(1), "the segment of no length at the seam has no teeth"); + assert!(comb_closes(&seam, &full), "the comb closes across a segment of no length"); + } + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). #[test] From b09940b6a6b0b9e76073b80f3679ba09e0db708b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:09:20 -0800 Subject: [PATCH 495/533] Docs: blend steps take the keys' drawn radii, positions on a straight spine Steps between live rectangles interpolate each key's radius after it is fitted to its sides, not the stored radius. Their positions lie between the keys' only on a straight spine; on an edited or replaced spine each step sits on the spine. --- docs/mcp.md | 6 ++++-- docs/target-app-parity.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index c4465ae0c1..5eb8f4113b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16810,8 +16810,10 @@ from 1 to 1000. Keys with no width or no height are measured by their other side keys without bounds make 1 step. `starts` gives, per object, the anchor of its first subpath the blend starts from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). Steps between two live rectangles with the same corner kinds and the same rotation and reflection, and with no scale -or shear left in their transforms, are live rectangles whose width, height, position and corner radii lie between -the keys', so their rounded corners stay circular arcs. Other path and live-shape pairs use anchor matching. A start anchor given in +or shear left in their transforms, are live rectangles whose width, height and drawn corner radii lie between +the keys', so their rounded corners stay circular arcs. The drawn radius is a key's radius fitted to its sides (a +20 by 10 key that stores a radius of 50 blends with a radius of 5). On a straight spine the steps' positions also +lie between the keys'; on an edited or replaced spine each step sits on the spine. Other path and live-shape pairs use anchor matching. A start anchor given in `starts` for either key also sends live rectangles through anchor matching; an all-null `starts` does not. With the Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend just made; the document and the selection stay as they are. A blend diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9e4dc14697..304025ecbe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2132,7 +2132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. A triple-click on a face selects every face of its group with that face's fill, and on an edge every edge of its group that has its stroke paint ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)); hidden faces and edges are left out, and Shift-triple-click adds them to the selection or removes them from it. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. - Steps between two live rectangles with the same corner kinds, turned and reflected alike, are live rectangles whose sizes, positions and corner radii lie between the keys', so their rounded corners stay circular arcs (#10707). A start point clicked on either key, a scale or shear left in a key's transform, and every other pair of paths keep anchor-by-anchor matching. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`. + Steps between two live rectangles with the same corner kinds, turned and reflected alike, are live rectangles whose sizes and drawn corner radii lie between the keys', so their rounded corners stay circular arcs (#10707). The drawn radii are the radii after each key's radius is fitted to its sides: a 20 by 10 key that stores a radius of 50 draws and blends with a radius of 5. On a straight spine the steps' positions also lie between the keys'; on an edited or replaced spine each step sits on the spine. A start point clicked on either key, a scale or shear left in a key's transform, and every other pair of paths keep anchor-by-anchor matching. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. From 7cba3b786d1729f99b77ad638619be78e5c22a8f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:36:33 -0800 Subject: [PATCH 496/533] Links: clicking a link on desktop opens it in the browser again The desktop app sends every link it opens (Help menu community links, the app bar's Discord button, Home's Community links, About and credits, help links in dialogs, the updater's Open URL, an object's URL attribute) as egui's OpenUrl output. The app built eframe without its `links` feature, so egui-winit only logged "Cannot open url - feature \"links\" not enabled." and nothing opened. Turn on eframe's `links` feature in apps/vectorcraft. Cargo.lock adds webbrowser 1.2.8. The web build does not use egui-winit and is unchanged. The feature can be removed once the craft-libs pin includes storytold/craft-libs#5083, which opens links in the shared app setup. --- Cargo.lock | 17 +++++++++++++++++ apps/vectorcraft/Cargo.toml | 5 ++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 75c87011b4..be4b734a08 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2900,6 +2900,7 @@ dependencies = [ "raw-window-handle", "smithay-clipboard", "web-time", + "webbrowser", "windows-sys 0.61.2", "winit", ] @@ -9642,6 +9643,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b31216ad837f3f4062538be333d8431d37c11832ef86924a3d0ad50defdc2f" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.11" diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index bc000f0bd6..d4d2659b3e 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -23,7 +23,10 @@ vectorcraft-text = { workspace = true } # the update client. craft = { workspace = true, features = ["ui", "ui-app", "settings", "automation", "platform", "window", "dialogs", "print", "update"] } craft-nightly = { workspace = true } -eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] } +# `links` makes egui's OpenUrl output (every link the app opens) start the system browser; without it egui-winit only +# logs the request. Remove it when the craft-libs pin includes storytold/craft-libs#5083, which opens links in the +# shared app setup. +eframe = { workspace = true, features = ["clipboard", "default_fonts", "links", "wayland", "x11"] } egui = { workspace = true } egui_extras = { workspace = true } serde_json = { workspace = true } From bf13038b8d41cc4c860645df491ca9a0a79ea97d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:36:45 -0800 Subject: [PATCH 497/533] Docs: pathItems.removeAll keeps a clip that visible text holds The progress line for Document.pathItems now says that removeAll() still deletes the paths of a clipping group when visible text that lays out glyphs stays in it, as docs/mcp.md describes. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b896e0ac48..67c053ee0e 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: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a clipping group when a visible text object that lays out glyphs stays in the group, because the text then clips. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 6ba1e6cc235fc13528bd1b646db991707f0d546f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:46:51 -0800 Subject: [PATCH 498/533] EPS import: test the skipping of oversized image data under a 1 MiB limit the_data_of_an_image_too_large_to_hold_is_skipped built 300 MiB of zeros and Flate- and LZW-encoded each of them to get past the reader's 256 MiB data limit, and took about 8.7 s. Tests can now lower the limit on their own thread with `with_data_limit`; shipped builds keep the 256 MiB constant. The test runs under a 1 MiB limit with 2 MiB of data per filter, and checks that the Flate and LZW data is measured in full, so it fails when the lower limit does not take effect. It now takes about 0.14 s. --- crates/eps/src/import/data.rs | 2 +- crates/eps/src/import/data/filters.rs | 14 ++++----- crates/eps/src/import/data/ops.rs | 45 ++++++++++++++++++++++----- crates/eps/src/import/tests_images.rs | 37 +++++++++++++--------- 4 files changed, 69 insertions(+), 29 deletions(-) diff --git a/crates/eps/src/import/data.rs b/crates/eps/src/import/data.rs index 09f7531ff1..911b356793 100644 --- a/crates/eps/src/import/data.rs +++ b/crates/eps/src/import/data.rs @@ -22,4 +22,4 @@ mod pixels; pub(crate) use filters::Stream; #[cfg(test)] -pub(crate) use ops::measured; +pub(crate) use ops::{measured, with_data_limit}; diff --git a/crates/eps/src/import/data/filters.rs b/crates/eps/src/import/data/filters.rs index cada27219a..7f3d37e043 100644 --- a/crates/eps/src/import/data/filters.rs +++ b/crates/eps/src/import/data/filters.rs @@ -1,4 +1,4 @@ -use super::ops::MAX_DATA; +use super::ops::max_data; use super::{DictRef, ImageBlob, Key, Obj, PsError, Rc, RefCell, Res, find, hex_decode, jpeg_components, ps, ps_err}; use craft_stream_codecs::CcittParams; @@ -44,7 +44,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { out.extend(std::iter::repeat_n(b, 257 - usize::from(n))); } } - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } } @@ -54,7 +54,7 @@ fn run_length(raw: &[u8]) -> Res<(Vec, usize)> { /// zlib data inflated, and how many bytes of `raw` it took. fn flate(raw: &[u8]) -> Res<(Vec, usize)> { let mut z = flate2::Decompress::new(true); - let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(MAX_DATA)); + let mut out = Vec::with_capacity(raw.len().saturating_mul(3).min(max_data())); loop { let before = (z.total_in(), z.total_out()); if out.capacity() - out.len() < 64 * 1024 { @@ -62,7 +62,7 @@ fn flate(raw: &[u8]) -> Res<(Vec, usize)> { } let input = raw.get(z.total_in() as usize..).unwrap_or_default(); let status = z.decompress_vec(input, &mut out, flate2::FlushDecompress::None).map_err(|_| PsError::Ps("ioerror", "FlateDecode".into()))?; - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } match status { @@ -79,7 +79,7 @@ fn lzw(raw: &[u8]) -> Res<(Vec, usize)> { let mut out = vec![]; let used = lzw_into(raw, &mut |bytes| { out.extend_from_slice(bytes); - if out.len() > MAX_DATA { + if out.len() > max_data() { return Err(PsError::Limit("decoded data is too large")); } Ok(()) @@ -238,10 +238,10 @@ fn dct(raw: &[u8]) -> Res<(Vec, usize, u8)> { /// `EndOfBlock` the rows end at the end-of-block code (EOFB, or RTC in Group 3) regardless of /// `Rows`; without it they end after `Rows` rows, or at the end of the data when `Rows` is 0. /// Damaged data ends the rows: those decoded before it are kept, and damage in the first row is an -/// `ioerror`. Rows that would take more than `MAX_DATA` bytes are refused. +/// `ioerror`. Rows that would take more than [`max_data`] bytes are refused. fn fax(raw: &[u8], settings: CcittParams) -> Res<(Vec, usize)> { let row = (settings.columns as usize).div_ceil(8).max(1); - let most = u32::try_from(MAX_DATA / row).unwrap_or(u32::MAX); + let most = u32::try_from(max_data() / row).unwrap_or(u32::MAX); if !settings.end_of_block && settings.rows > i64::from(most) { return Err(PsError::Limit("decoded data is too large")); } diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c27dc3c3c6..c83b4dca4d 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -6,7 +6,38 @@ use super::{ }; /// Most bytes one filter or image reads. -pub(super) const MAX_DATA: usize = 1 << 28; +const MAX_DATA: usize = 1 << 28; + +#[cfg(test)] +thread_local! { + /// The most bytes one filter or image reads on this thread ([`MAX_DATA`] unless a test lowered it). + static DATA_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_DATA) }; +} + +/// The most bytes one filter or image reads: [`MAX_DATA`]. +#[cfg(not(test))] +pub(super) const fn max_data() -> usize { + MAX_DATA +} + +/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread. +#[cfg(test)] +pub(super) fn max_data() -> usize { + DATA_LIMIT.get() +} + +/// Runs `f` with [`max_data`] set to `limit` on this thread, and restores it afterwards. +#[cfg(test)] +pub(crate) fn with_data_limit(limit: usize, f: impl FnOnce() -> R) -> R { + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + DATA_LIMIT.set(self.0); + } + } + let _restore = Restore(DATA_LIMIT.replace(limit)); + f() +} /// Decoded bytes the measuring of an image's data left out charges one operation for. A program's /// budget grows by 64 operations for each byte of it, so the data of one image compressed up to @@ -410,7 +441,7 @@ impl Interp<'_> { Stream::Buf { data, pos: 0, rgb } } p @ Obj::Array { .. } => { - let raw = self.gather(&p, MAX_DATA)?; + let raw = self.gather(&p, max_data())?; let (data, _, rgb) = decode(&spec, &raw)?; self.charge_decoded(data.len())?; Stream::Buf { data, pos: 0, rgb } @@ -600,7 +631,7 @@ impl Interp<'_> { if last.predictor.is_some() || !matches!(&*last.name, "FlateDecode" | "LZWDecode") { return Ok(None); } - let Some(kept) = row.checked_mul(oh).filter(|k| *k <= MAX_DATA) else { return Ok(None) }; + let Some(kept) = row.checked_mul(oh).filter(|k| *k <= max_data()) else { return Ok(None) }; self.alloc(kept)?; // The compressed data: what the filters before the last one decode, or the file itself. let compressed = if head.is_empty() { @@ -618,7 +649,7 @@ impl Interp<'_> { }; let (mut rows, mut seen) = (Vec::with_capacity(kept), 0usize); // Past the image's data and as much again the data is not an image's: it stops there. - let most = row.saturating_mul(s.h).saturating_add(MAX_DATA); + let most = row.saturating_mul(s.h).saturating_add(max_data()); let mut sink = |mut chunk: &[u8]| -> Res { while !chunk.is_empty() { let (r, off) = (seen / row.max(1), seen % row.max(1)); @@ -829,7 +860,7 @@ impl Interp<'_> { let (mrow, drow) = (stencil.row_bytes(1), image.row_bytes(n)); let total = mrow.saturating_mul(stencil.h).saturating_add(drow.saturating_mul(image.h)); // What is read: an image past the pixel cap is reduced from the samples read. - charged = total.min(MAX_DATA); + charged = total.min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_rows(&raw, (mrow, stencil.h), (drow, image.h)) @@ -838,7 +869,7 @@ impl Interp<'_> { stencil.bpc = image.bpc; (stencil.w, stencil.h) = (image.w, image.h); let row = (image.w * (n + 1) * usize::from(image.bpc)).div_ceil(8); - charged = row.saturating_mul(image.h).min(MAX_DATA); + charged = row.saturating_mul(image.h).min(max_data()); self.alloc(charged)?; let raw = self.source_bytes(&src, charged)?; by_samples(&raw, image.w, image.h, n, image.bpc) @@ -1020,7 +1051,7 @@ impl Interp<'_> { // skipped), while one within the pixel cap whose samples are still too much data // (16-bit CMYK, say) stops the read with the limit, as before (#3568: such a plane // is refused). - let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= MAX_DATA) else { + let Some(plane) = row.checked_mul(s.h).filter(|p| *p <= max_data()) else { if step > 1 { return Ok(self.leave_out(&s)); } diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 2324de4eb4..ffc482f0f7 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -686,11 +686,15 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader /// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is -/// measured without keeping it. +/// measured without keeping it. The reader holds 1 MiB here, and each filter's data decompresses +/// to 2 MiB: Flate and LZW data is measured in full (run-length data is measured by its run +/// lengths, without decoding it). #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { + const LIMIT: usize = 1 << 20; + const DECODED: usize = 2 * LIMIT; let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; - let zeros = crate::ps::deflate(&vec![0u8; 300 << 20]); + let zeros = crate::ps::deflate(&vec![0u8; DECODED]); // Predicted rows aren't decoded a row at a time: such an image is left out. let mut flate = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); @@ -699,7 +703,7 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // The same through LZW, which counts the codes up to its end-of-data code. let mut lzw = b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); - lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true)); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; DECODED], true)); lzw.extend(format!("\n{after}").as_bytes()); // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in @@ -707,24 +711,29 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { // run's length and stays off by one. let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); run_length.extend([2, 200, 200, 200]); - run_length.extend([129u8, 200].repeat((300 << 20) / 128)); + run_length.extend([129u8, 200].repeat(DECODED / 128)); run_length.push(128); run_length.extend(format!("\n{after}").as_bytes()); - for program in [ - format!( - "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ - 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" - ) - .into_bytes(), - flate, - lzw, - run_length, + for (program, measured) in [ + ( + format!( + "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ + 10000 10000 8 [1 0 0 1 0 0] {{ F 4096 string readstring pop }} false 3 colorimage\n@@@@ not PostScript @@@@\n%%EndData\n{after}" + ) + .into_bytes(), + 0, + ), + (flate, DECODED as u64), + (lzw, DECODED as u64), + (run_length, 0), ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); file.extend(&program); file.extend(b"\nshowpage\n%%EOF\n"); - let r = import(&file).unwrap(); + let before = crate::import::data::measured(); + let r = crate::import::data::with_data_limit(LIMIT, || import(&file)).unwrap(); + assert_eq!(crate::import::data::measured() - before, measured, "{text}"); assert!(r.warnings.iter().any(|w| w.contains("too large to read")), "{text}: {:?}", r.warnings); let o = super::tests::objects(&r.document); assert_eq!(o.len(), 1, "{text}: {:?}", r.warnings); From 9c11c47f75cf870de92b7f8883fc8f89aab43793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:51:28 -0800 Subject: [PATCH 499/533] Doc tests: unsafe code is denied in doc tests too Rustdoc builds each doc test as its own crate, without the workspace's `unsafe_code = "deny"` and without a library's `#![forbid(unsafe_code)]`, so a doc test holding an `unsafe` block passed `cargo test --doc`. - Every library root now carries `#![doc(test(attr(forbid(unsafe_code))))]`, or `deny` in cad, eps and metafile, which rely on the workspace lint. - `cargo xtask layers` reports a library whose doc tests are missing the attribute, or use `deny` where the library forbids unsafe code. - AGENTS.md names the rule next to the `unsafe` allowlist. --- AGENTS.md | 2 +- crates/affinity/src/lib.rs | 1 + crates/apischema/src/lib.rs | 1 + crates/brush/src/lib.rs | 1 + crates/cad/src/lib.rs | 1 + crates/color/src/lib.rs | 1 + crates/doc/src/lib.rs | 1 + crates/effects/src/lib.rs | 1 + crates/engine/src/lib.rs | 1 + crates/eps/src/lib.rs | 1 + crates/format/src/lib.rs | 1 + crates/geom/src/lib.rs | 1 + crates/js/src/lib.rs | 1 + crates/mcp/src/lib.rs | 1 + crates/metafile/src/lib.rs | 1 + crates/pathops/src/lib.rs | 1 + crates/pdf/src/lib.rs | 1 + crates/plugins/src/lib.rs | 1 + crates/render/src/lib.rs | 1 + crates/scriptcheck/src/lib.rs | 1 + crates/svg/src/lib.rs | 1 + crates/testkit/src/lib.rs | 1 + crates/text/src/lib.rs | 1 + crates/three-d/src/lib.rs | 1 + crates/tools/src/lib.rs | 1 + crates/trace/src/lib.rs | 1 + crates/ui-egui/src/lib.rs | 1 + xtask/src/doc_tests.rs | 98 +++++++++++++++++++++++++++++++++++ xtask/src/main.rs | 11 ++-- 29 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 xtask/src/doc_tests.rs diff --git a/AGENTS.md b/AGENTS.md index bac119a742..2e02266c6d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator- For the crates you changed: `cargo fmt`, `cargo clippy -p --all-targets`, `cargo xtask test` or `cargo nextest run -p `. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`. ### Paths and conventions -- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. +- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it. - Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns. - Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty. - Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`. diff --git a/crates/affinity/src/lib.rs b/crates/affinity/src/lib.rs index e14c1439a7..1a69aeed48 100644 --- a/crates/affinity/src/lib.rs +++ b/crates/affinity/src/lib.rs @@ -1,6 +1,7 @@ //! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so //! the corpus tests and fuzz targets under it, and the CI job that runs them, still build. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub use craft_affinity::*; diff --git a/crates/apischema/src/lib.rs b/crates/apischema/src/lib.rs index cff749e84f..e78cde4ecb 100644 --- a/crates/apischema/src/lib.rs +++ b/crates/apischema/src/lib.rs @@ -18,6 +18,7 @@ //! //! The crate knows no command and depends on no other VectorCraft crate. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use std::fmt; diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 85dfc8e084..fffdd4f797 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -9,6 +9,7 @@ //! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it //! returns (caching them per node) and `object.expandBrush` inserts them as real objects. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod calli; mod colorize; diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index b54d9022bf..5f2d41d538 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -21,6 +21,7 @@ //! - `scene`: the document walk that turns objects into entities. //! - `import`: the reader, entities to art, blocks to symbols. //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. +#![doc(test(attr(deny(unsafe_code))))] mod aci; #[cfg(test)] diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bb4c88985..03aa259281 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -3,6 +3,7 @@ //! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB), //! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`]. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod blend; pub mod cms; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index cb8f077dae..8fe1cef218 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -4,6 +4,7 @@ //! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node. //! Keeping the previous `Document` value around is therefore a cheap undo snapshot. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod appearance; pub mod assets; diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index aef398c64e..c2be1804db 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -33,6 +33,7 @@ //! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells, //! anchored at the object's centre. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod adjust; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e1e7f5a5..d5c30cd89b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -5,6 +5,7 @@ //! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and //! reduce to commands, so every gesture is journaled and replayable. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod cmd; pub mod file_access; diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index d8b9a96295..6813b300aa 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -34,6 +34,7 @@ //! - `ai_graph`: the records of a live graph those two write around its group. //! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. +#![doc(test(attr(deny(unsafe_code))))] mod ai_editing; mod ai_graph; diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 9975527f78..c7157df94d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -37,6 +37,7 @@ //! already; [`save_with`] writes a version 1 document with them negated back for an older file //! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] #[cfg(not(target_arch = "wasm32"))] mod atomic; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3f11c71062..8a4cb4f7fb 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -6,6 +6,7 @@ //! //! Coordinates are document points (1/72 in), y pointing down. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod anchors; pub mod arc; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index a720940b06..77b3e00856 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -131,6 +131,7 @@ //! `await` (ECMA-262 2017 section 25.5, ). //! An `await` suspends its function's frame until the value settles, and a promise job resumes it. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ast; mod builtins; diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index efc9d44830..7e104e85f2 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -13,6 +13,7 @@ //! //! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod backend; mod headless; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index df23cbb073..66f3c4327b 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,6 +26,7 @@ //! formats. //! //! The app walks its document and maps its drawing operations to the shared writers. +#![doc(test(attr(deny(unsafe_code))))] #[cfg(test)] mod bytes; diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index da7960af0f..0190233191 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -5,6 +5,7 @@ //! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few //! anchors. See the crate README for the API overview. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod boolean; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 2dc6f1ec0a..a7118fd37a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -42,6 +42,7 @@ //! security handler, the algorithm following the compatibility ([`Encryption`]); either password //! opens an encrypted file. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod editing; mod encrypt; diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index c9c0e89521..4f79939c62 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -42,6 +42,7 @@ //! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each //! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod deferred; pub mod dialog; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4358cc180d..f2b76c525d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5,6 +5,7 @@ //! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups, //! gradients, images and text (via `vectorcraft-text` glyph outlines). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; mod brush_fx; diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 9075c53517..f0c8528919 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -22,6 +22,7 @@ //! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the //! input's size, and no input can overflow the stack. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod analyze; mod catalog; diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 222b90b25c..109b3a938a 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -100,6 +100,7 @@ //! letter and word spacing become character attributes (line breaks, kerning, baseline shift, //! rotation and style names). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] use craft_svg::tree::usvg; mod css; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index fa7b39aa9d..fd86ad3c89 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -22,6 +22,7 @@ // apply here. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod ai; pub mod ase; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 25e44392d6..4723f1ffcd 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -9,6 +9,7 @@ //! //! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod bitmap; mod colr; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f561c0b7c6..37768ea651 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -7,6 +7,7 @@ //! //! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod fold; mod solid; diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 5a32145ec0..5adcecd679 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -6,6 +6,7 @@ //! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable //! by the control channel and MCP, and keeps tools testable without a UI. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] pub mod addons; pub mod bbox; diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index 7bb59c79b1..02acf76de0 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -46,6 +46,7 @@ //! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color //! left out stays a hole. #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] mod centerline; mod contour; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a51817a7f1..948f1ad279 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4,6 +4,7 @@ //! (view/window) here and everything else to the engine. The same entry point serves menus, //! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]). #![forbid(unsafe_code)] +#![doc(test(attr(forbid(unsafe_code))))] /// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update /// prompt shows both, and an AppImage's menu entry gets the icon. diff --git a/xtask/src/doc_tests.rs b/xtask/src/doc_tests.rs new file mode 100644 index 0000000000..9ba395136c --- /dev/null +++ b/xtask/src/doc_tests.rs @@ -0,0 +1,98 @@ +//! Every library's doc tests deny unsafe code. +//! +//! Rustdoc compiles each doc test as a crate of its own, without the workspace's `[lints]` table +//! and without the library's own `#![forbid(unsafe_code)]`, so an `unsafe` block in a doc comment +//! passes `cargo test --doc`. Rustdoc adds the attributes in `#![doc(test(attr(...)))]` to every +//! doc test, so each library root carries `#![doc(test(attr(forbid(unsafe_code))))]`, or +//! `deny` where the library itself relies on the workspace's `deny`. `cargo xtask layers` runs +//! this check. + +use serde_json::Value; +use std::path::Path; + +/// Crate roots larger than this are reported instead of read. +const MAX_ROOT_BYTES: u64 = 8 * 1024 * 1024; + +/// The problems found in the workspace's library roots, one line each. +pub fn check(meta: &Value) -> Result, String> { + let pkgs = meta["packages"].as_array().ok_or("metadata: no packages array")?; + let root = Path::new(meta["workspace_root"].as_str().unwrap_or_default()); + let mut out = Vec::new(); + for p in pkgs { + let name = p["name"].as_str().ok_or("package without name")?; + for t in p["targets"].as_array().into_iter().flatten() { + let kinds: Vec<&str> = t["kind"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let doc_tested = t["doctest"].as_bool() == Some(true) && kinds.iter().any(|k| matches!(*k, "lib" | "rlib" | "proc-macro")); + if !doc_tested { + continue; + } + let path = t["src_path"].as_str().ok_or_else(|| format!("{name}: library target without src_path"))?; + if let Some(problem) = check_root(name, root, Path::new(path))? { + out.push(problem); + } + } + } + out.sort(); + Ok(out) +} + +fn check_root(name: &str, root: &Path, path: &Path) -> Result, String> { + let shown = path.strip_prefix(root).unwrap_or(path).display(); + let len = std::fs::metadata(path).map_err(|e| format!("{shown}: {e}"))?.len(); + if len > MAX_ROOT_BYTES { + return Ok(Some(format!("{name}: {shown} is larger than {MAX_ROOT_BYTES} bytes"))); + } + let src = std::fs::read_to_string(path).map_err(|e| format!("{shown}: {e}"))?; + Ok(problem(&src).map(|p| format!("{name}: {shown}: {p}"))) +} + +/// What a library root is missing, or `None` when its doc tests deny unsafe code at least as +/// strictly as the library does. +fn problem(src: &str) -> Option<&'static str> { + let attrs: Vec = + src.lines().map(|l| l.chars().filter(|c| !c.is_whitespace()).collect::()).filter(|l| l.starts_with("#![")).collect(); + let forbids = attrs.iter().any(|a| a == "#![forbid(unsafe_code)]"); + let doc_test = |level: &str| attrs.iter().any(|a| a.starts_with("#![doc(test(") && a.contains(&format!("{level}(unsafe_code)"))); + if doc_test("forbid") { + None + } else if forbids { + Some("forbids unsafe code but its doc tests do not: add #![doc(test(attr(forbid(unsafe_code))))]") + } else if doc_test("deny") { + None + } else { + Some("its doc tests allow unsafe code: add #![doc(test(attr(deny(unsafe_code))))]") + } +} + +#[cfg(test)] +mod tests { + use super::problem; + + #[test] + fn a_forbidding_library_needs_forbid_in_its_doc_tests() { + assert_eq!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert!(problem("#![forbid(unsafe_code)]\n").is_some_and(|p| p.contains("forbid(unsafe_code))))"))); + assert!(problem("#![forbid(unsafe_code)]\n#![doc(test(attr(deny(unsafe_code))))]\n").is_some_and(|p| p.contains("forbid"))); + } + + #[test] + fn a_library_on_the_workspace_deny_needs_deny_or_forbid() { + assert_eq!(problem("//! Docs.\n#![doc(test(attr(deny(unsafe_code))))]\n"), None); + assert_eq!(problem("#![doc(test(attr(forbid(unsafe_code))))]\n"), None); + assert!(problem("//! Docs.\npub fn f() {}\n").is_some_and(|p| p.contains("deny(unsafe_code))))"))); + } + + #[test] + fn comments_other_lints_and_allow_do_not_count() { + assert!(problem("// #![doc(test(attr(deny(unsafe_code))))]\n").is_some()); + assert!(problem("//! `#![doc(test(attr(deny(unsafe_code))))]`\n").is_some()); + assert!(problem("#![doc(test(attr(allow(unsafe_code))))]\n").is_some()); + assert!(problem("#![doc(test(attr(deny(warnings))))]\n").is_some()); + assert!(problem("#![deny(unsafe_code)]\n").is_some()); + } + + #[test] + fn spacing_and_other_attributes_in_the_list_are_accepted() { + assert_eq!(problem("#![doc(test(attr(deny(warnings), forbid( unsafe_code ))))]\n#![forbid(unsafe_code)]\n"), None); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 2152369254..a09949f548 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -9,6 +9,7 @@ mod brands; mod bundle; mod cache_units; mod cursors; +mod doc_tests; mod grant_sites; mod ico; mod layers; @@ -200,7 +201,8 @@ pub fn metadata() -> Result { } fn cmd_layers() -> Result<(), String> { - let crates = layers::from_metadata(&metadata()?)?; + let meta = metadata()?; + let crates = layers::from_metadata(&meta)?; println!("Dependency layering (plan/architecture.md §3)\n"); println!("{:<28} {:<14} workspace deps", "crate", "layer"); for c in &crates { @@ -219,17 +221,18 @@ fn cmd_layers() -> Result<(), String> { .collect(); println!("{:<28} {:<14} {}", c.name, layers::describe(layers::classify(&c.name)), ws.join(", ")); } - let violations = layers::check(&crates); + let mut violations: Vec = layers::check(&crates).iter().map(ToString::to_string).collect(); + violations.extend(doc_tests::check(&meta)?); println!(); if violations.is_empty() { - println!("OK: {} crates, no layering violations.", crates.len()); + println!("OK: {} crates, no layering violations, and every library's doc tests deny unsafe code.", crates.len()); Ok(()) } else { println!("{} violation(s):", violations.len()); for v in &violations { println!(" - {v}"); } - Err(format!("{} layering violation(s)", violations.len())) + Err(format!("{} violation(s)", violations.len())) } } From 9995ffc36c7dc4beab3e10e6e8cc2ceb7d28056c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:53:40 -0800 Subject: [PATCH 500/533] Image Trace: drop an unfinished slider value when the selection changes A value typed into an Image Trace slider row or the Divider and not yet committed stayed in the field after another object was selected, so pressing Enter applied it to the newly selected object. The settings sliders (Threshold, Colors, Paths, Corners, Noise, Stroke) and the Divider are now keyed on the selection, so another selection starts a fresh field. This stands in for SliderField::edit_target (storytold/craft-libs#5024) until the craft-libs pin includes it; the pin bump replaces each id_salt with edit_target. --- crates/ui-egui/src/panels/image_trace.rs | 13 ++++- crates/ui-egui/src/panels/image_trace/rows.rs | 29 +++++++--- .../ui-egui/src/panels/image_trace/tests.rs | 58 +++++++++++++++++++ 3 files changed, 90 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 372d3117aa..fb30859192 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -299,9 +299,18 @@ pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(split) = selected_split(app) else { return }; // The canvas sets the divider to a ten-thousandth: a hundredth of a percent. let pct = (split * 10_000.0).round() / 100.0; + // Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a value + // typed for one object when another is selected. The pin bump replaces this with `edit_target`. + let target = crate::panels::selection_target(app); let edit = Field::new(tl!("Divider")) .show(ui, |ui, _| { - SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).unit("%").show(ui).edit + SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0) + .layout(SliderFieldLayout::Inline) + .step(1.0) + .unit("%") + .id_salt(("divider", &target)) + .show(ui) + .edit }) .inner; let Some(edit) = edit else { return }; @@ -1031,7 +1040,7 @@ fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: } split_row(app, ui); - let data = RowsData::of(app); + let data = RowsData::of_selection(app); let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; let (main, advanced) = rows::settings_group(ui, |ui| { let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs index 2c87a42d50..cbcecc07bc 100644 --- a/crates/ui-egui/src/panels/image_trace/rows.rs +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -22,7 +22,7 @@ use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; use super::{MODES, PALETTES, ignore_color, palette_label}; use crate::VectorcraftApp; -use crate::panels::swatches; +use crate::panels::{SelectionTarget, selection_target, swatches}; /// Where the rows are shown. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -40,13 +40,21 @@ pub(crate) struct RowsData { pub(crate) libraries: Vec>, /// The active document's colour group names. pub(crate) groups: Vec, + /// The selection whose settings the rows show, for a host that follows the selection (the panel). A slider's + /// unfinished value is dropped when it changes. + pub(crate) target: Option, } impl RowsData { /// The lists for the active document. pub(crate) fn of(app: &VectorcraftApp) -> Self { // PLAN: assumed `swatches::library_entries(app: &VectorcraftApp) -> Vec>` (color-w10). - RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app) } + RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app), target: None } + } + + /// The lists for the active document, for rows that show the selection's settings. + pub(crate) fn of_selection(app: &VectorcraftApp) -> Self { + RowsData { target: Some(selection_target(app)), ..Self::of(app) } } } @@ -151,13 +159,18 @@ fn slider(key: &'static str, label: &'static str, range: RangeInclusive, un Slider { key, label, range, unit, default: 0.0 } } -fn slider_row(ui: &mut Ui, params: &mut Value, spec: Slider, enabled: bool, out: &mut RowsOutput) { +fn slider_row(ui: &mut Ui, params: &mut Value, data: &RowsData, spec: Slider, enabled: bool, out: &mut RowsOutput) { let Slider { key, label, range, unit, default } = spec; let value = params[key].as_f64().unwrap_or(default); let events = Field::new(label) .enabled(enabled) .show(ui, |ui, _| { let mut field = SliderField::new(label, Bind::given(value), range.clone()).layout(SliderFieldLayout::Inline).step(1.0).enabled(enabled); + // Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a + // value typed for one object when another is selected. The pin bump replaces this with `edit_target`. + if let Some(target) = &data.target { + field = field.id_salt((key, target)); + } if let Some(unit) = unit { field = field.unit(unit); } @@ -234,14 +247,14 @@ pub(crate) fn main_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, host: _ if matches!(palette.as_str(), "fullTone" | "automatic") => slider("colorDetail", tl!("Colors"), 0.0..=100.0, Some("%")), _ => slider("colors", tl!("Colors"), 2.0..=256.0, None), }; - slider_row(ui, params, count, true, &mut out); + slider_row(ui, params, data, count, true, &mut out); out } /// The Advanced settings: fidelity, method, Create, snapping, shapes, grouping, gradients and Ignore Color, with an -/// eyedropper for Ignore Color when the host passes a `sampler`. `_data` and `_host` are the arguments of +/// eyedropper for Ignore Color when the host passes a `sampler`. `data` and `_host` are the arguments of /// [`main_rows`], so a host passes the same set to both. -pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _host: RowsHost, sampler: Option) -> RowsOutput { +pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, _host: RowsHost, sampler: Option) -> RowsOutput { let mut out = RowsOutput::default(); let mode = text(params, "mode", "blackAndWhite"); for spec in [ @@ -249,7 +262,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ slider("corners", tl!("Corners"), 0.0..=100.0, Some("%")), slider("noise", tl!("Noise"), 1.0..=100.0, Some("px")), ] { - slider_row(ui, params, spec, true, &mut out); + slider_row(ui, params, data, spec, true, &mut out); } // Flat Logo always paints biggest shapes first with a hair of overlap, so there is no choice. if mode != "logo" { @@ -282,7 +295,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _ params[key] = json!(!create(params, key)); out.picked(); } - slider_row(ui, params, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out); + slider_row(ui, params, data, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out); } // (Black and White has one colour and Flat Logo flat ones: no gradients to find.) let gradients = mode == "grayscale" || mode == "color"; diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 00516ffd34..c97e3e1c27 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -599,6 +599,64 @@ fn the_divider_slider_keeps_an_exact_divider_and_a_drag_is_one_undo_step() { assert_eq!(undo(&panel.app()), steps + 1, "one undo step for the edit"); } +/// Two traced objects with the same settings, the first one selected: the app, the first and the second object. +fn two_traced_objects(app: VectorcraftApp) -> (VectorcraftApp, NodeId, NodeId) { + let mut app = app; + let a = first_selected(&app).unwrap().id; + app.run("edit.duplicate", json!({})).unwrap(); + let b = first_selected(&app).unwrap().id; + assert_ne!(a, b); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + (app, a, b) +} + +/// Types `text` into the number box of the slider row `name` without finishing the edit. +fn type_unfinished(panel: &mut Panel, name: &str, text: &str) { + panel.click_role(name, craft::ui::contract::Role::SPIN_BUTTON); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text(text); +} + +/// A value typed into a settings slider for one Image Trace object, and not finished, is dropped when another +/// object is selected: Enter afterwards changes neither object. +#[test] +fn an_unfinished_slider_value_is_dropped_when_another_object_is_selected() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (app, a, b) = two_traced_objects(traced_app()); + let mut panel = panel_over(app); + panel.frame(); + let threshold = param(&panel.app(), "threshold"); + let steps = undo(&panel.app()); + type_unfinished(&mut panel, "Threshold", "3"); + select(&mut panel, b); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(param(&panel.app(), "threshold"), threshold, "B keeps its threshold"); + assert_eq!(undo(&panel.app()), steps, "nothing was traced"); + select(&mut panel, a); + assert_eq!(param(&panel.app(), "threshold"), threshold, "A keeps its threshold"); +} + +/// A value typed into the Divider for one Image Trace object, and not finished, is dropped when another object is +/// selected: Enter afterwards moves neither divider. +#[test] +fn an_unfinished_divider_value_is_dropped_when_another_object_is_selected() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = traced_app(); + app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap(); + let (app, a, b) = two_traced_objects(app); + let mut panel = panel_over(app); + panel.frame(); + let steps = undo(&panel.app()); + type_unfinished(&mut panel, "Divider", "8"); + select(&mut panel, b); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B has the same divider"); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B keeps its divider"); + assert_eq!(undo(&panel.app()), steps, "no undo step"); + select(&mut panel, a); + assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "A keeps its divider"); +} + /// Properties shows the Divider slider of the selected Image Trace object in the Split view only, /// with its name and value for screen readers. #[test] From db1d346bc4dffac3407c9299fd4e6661c72e7223 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:56:28 -0800 Subject: [PATCH 501/533] Tests: Divide refuses cutting lines past the segment cap A square and an unfilled zigzag with one segment more than the planar map's cap: Divide returns the "select fewer paths" error and leaves the document and the undo history unchanged. With the check replaced by the unchecked Divide, the test fails because Divide returns the square uncut. --- crates/engine/src/tests/pathops.rs | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index a5a082058e..d1b5197012 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -171,6 +171,38 @@ fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Divide refuses a cutting line with more segments than its planar map takes, instead of +/// dividing the square without the line, and leaves the document and the undo history as they were. +#[test] +fn divide_refuses_cutting_lines_past_the_segment_cap() { + let mut s = session(); + let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap()); + // A zigzag across the square with one segment more than the cap, the square's four sides aside. + let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3; + s.edit("zigzag", |d, sel| { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((-10.0, 40.0)); + for i in 1..=segments { + let x = -10.0 + 120.0 * i as f64 / segments as f64; + bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 })); + } + // Unfilled, so the zigzag stays open and cuts. + let n = d.node_mut(cutter).unwrap(); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false }; + sel.set([cutter, base]); + Ok(()) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select fewer paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); From c976e47115c8c908a2c0223612a0aa1b201ea13b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 10:09:29 -0800 Subject: [PATCH 502/533] Panels: hidden or minimized palette windows no longer block canvas drops A floating panel's OS window counted as covering the canvas even while it was minimized, or hidden because a dialog or popup was open. Art dragged onto the canvas and released over the spot where such a window sat was refused, and the tools treated the pointer there as covered. os_window_at now skips windows the OS reports minimized, and reports no cover while a dialog or popup is open. This works around storytold/craft-libs#4739; the checks are removed when the craft-libs pin includes that change. --- crates/ui-egui/src/panel_docking.rs | 15 ++++-- .../ui-egui/src/panel_docking/native_tests.rs | 48 +++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 1a47d5a7d2..4e7edbbfa7 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1317,15 +1317,24 @@ fn window_viewport(app: &VectorcraftApp, panel: &str) -> Option