From 33bee45ab19ccae866ff485739a07973eb1b5736 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:14:31 -0800 Subject: [PATCH 001/156] 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/156] 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/156] 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 75cb9572678ceb7e142754e5fbd21db0f071b1eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 16:02:13 -0800 Subject: [PATCH 004/156] 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 005/156] 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 6a19ae164b18368ff74f751ad80325af21e4a1ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 23:34:45 -0800 Subject: [PATCH 006/156] 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 007/156] 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 1f71bda80f66f37344ca4c5dec48e21a19e4d0cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:05:09 -0800 Subject: [PATCH 008/156] 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 d199b0d257c9e972d34cdbb14fd2d5c3eb97bb2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:21:26 -0800 Subject: [PATCH 009/156] 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 61b7c8dbe1dbbf3bf1e7bc902287a2e1b085af94 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:13:29 -0800 Subject: [PATCH 010/156] 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 90400601189f9c204d0c1c2150f1b84f211d2e56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:38:52 -0800 Subject: [PATCH 011/156] 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 012/156] 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 2356ffe7475d85f079b6edfcb3f55f64da3386de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:55:12 -0800 Subject: [PATCH 013/156] 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 368915aff4f5d55e35dc0b13e9db6ec7dc16b97e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:06:25 -0800 Subject: [PATCH 014/156] 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 f0c2c946b9277dbf95d1e2c495236d9534f11be4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:58:43 -0800 Subject: [PATCH 015/156] 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 244472e98da464f34574fb0138a490261f32d43c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:53:42 -0800 Subject: [PATCH 016/156] 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 017/156] 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 4180df830d982adfbb0ec1059b7a08c56907e450 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:08:47 -0800 Subject: [PATCH 018/156] 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 5dbd4357c182f392dcb3717f02ea6e437319bc93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:21:54 -0800 Subject: [PATCH 019/156] 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 020/156] 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 021/156] 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 06eb0f252affed9df848712ff016eb9fd77e25e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:35:27 -0800 Subject: [PATCH 022/156] 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 b3dede0a252e7a8f1f123829fd43b633fdd95fc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 01:04:03 -0800 Subject: [PATCH 023/156] 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 024/156] 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 025/156] 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